context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Copyright 2014 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 System; using System.Collections.Generic; using System.Runtime.InteropServices; /* Wrapper for Objective-C iOS SDK */ public class GAIHandler { #if UNITY_IPHONE && !UNITY_EDITOR [DllImport("__Internal")] private static extern void setName(string name); public void _setName(string name){ setName(name); } [DllImport("__Internal")] private static extern void setOptOut(bool optOut); public void _setOptOut(bool optOut){ setOptOut(optOut); } [DllImport("__Internal")] private static extern void setDispatchInterval(int time); public void _setDispatchInterval(int time){ setDispatchInterval(time); } [DllImport("__Internal")] private static extern void anonymizeIP(); public void _anonymizeIP(){ anonymizeIP(); } [DllImport("__Internal")] private static extern void setTrackUncaughtExceptions(bool trackUncaughtExceptions); public void _setTrackUncaughtExceptions(bool trackUncaughtExceptions){ setTrackUncaughtExceptions(trackUncaughtExceptions); } [DllImport("__Internal")] private static extern void setDryRun(bool dryRun); public void _setDryRun(bool dryRun){ setDryRun(dryRun); } [DllImport("__Internal")] private static extern void setSampleFrequency(float sampleFrequency); public void _setSampleFrequency(float sampleFrequency){ setSampleFrequency(sampleFrequency); } [DllImport("__Internal")] private static extern void setLogLevel(int logLevel); public void _setLogLevel(int logLevel){ setLogLevel(logLevel); } [DllImport("__Internal")] private static extern void startSession(); public void _startSession(){ startSession(); } [DllImport("__Internal")] private static extern void stopSession(); public void _stopSession(){ stopSession(); } [DllImport("__Internal")] private static extern IntPtr trackerWithName(string name, string trackingId); public IntPtr _getTrackerWithName(string name, string trackingId){ return trackerWithName(name, trackingId); } [DllImport("__Internal")] private static extern IntPtr trackerWithTrackingId(string trackingId); public IntPtr _getTrackerWithTrackingId(string trackingId){ return trackerWithTrackingId(trackingId); } [DllImport("__Internal")] private static extern void set(string parameterName, string value); public void _set(string parameterName, object value){ set(parameterName, value.ToString()); } [DllImport("__Internal")] private static extern void setBool(string parameterName, bool value); public void _setBool(string parameterName, bool value){ setBool(parameterName, value); } [DllImport("__Internal")] private static extern string get(string parameterName); public string _get(string parameterName){ return get(parameterName); } [DllImport("__Internal")] private static extern void dispatch(); public void _dispatchHits(){ dispatch(); } [DllImport("__Internal")] private static extern void sendAppView(string screenName); public void _sendAppView(AppViewHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendAppView(builder.GetScreenName()); } [DllImport("__Internal")] private static extern void sendEvent(string category, string action, string label, long value); public void _sendEvent(EventHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendEvent(builder.GetEventCategory(), builder.GetEventAction(), builder.GetEventLabel(), builder.GetEventValue()); } [DllImport("__Internal")] private static extern void sendTransaction(string transactionID, string affiliation, double revenue, double tax, double shipping, string currencyCode); public void _sendTransaction(TransactionHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendTransaction(builder.GetTransactionID(), builder.GetAffiliation(), builder.GetRevenue(), builder.GetTax(), builder.GetShipping(), builder.GetCurrencyCode()); } [DllImport("__Internal")] private static extern void sendItemWithTransaction(string transactionID, string name, string sku, string category, double price, long quantity, string currencyCode); public void _sendItemWithTransaction(ItemHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendItemWithTransaction(builder.GetTransactionID(), builder.GetName(), builder.GetSKU(), builder.GetCategory(), builder.GetPrice(), builder.GetQuantity(),builder.GetCurrencyCode()); } [DllImport("__Internal")] private static extern void sendException(string exceptionDescription, bool isFatal); public void _sendException(ExceptionHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendException(builder.GetExceptionDescription(), builder.IsFatal()); } [DllImport("__Internal")] private static extern void sendSocial(string socialNetwork, string socialAction, string targetUrl); public void _sendSocial(SocialHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendSocial(builder.GetSocialNetwork(), builder.GetSocialAction(), builder.GetSocialTarget()); } [DllImport("__Internal")] private static extern void sendTiming(string timingCategory,long timingInterval, string timingName, string timingLabel); public void _sendTiming(TimingHitBuilder builder){ _buildCustomMetricsDictionary(builder); _buildCustomDimensionsDictionary(builder); _buildCampaignParametersDictionary(builder); sendTiming(builder.GetTimingCategory(), builder.GetTimingInterval(), builder.GetTimingName(), builder.GetTimingLabel()); } [DllImport("__Internal")] private static extern void addCustomDimensionToDictionary(int key, string value); public void _buildCustomDimensionsDictionary<T>(HitBuilder<T> builder){ foreach(KeyValuePair<int, string> entry in builder.GetCustomDimensions()) { addCustomDimensionToDictionary(entry.Key, entry.Value); } } [DllImport("__Internal")] private static extern void addCustomMetricToDictionary(int key, string value); public void _buildCustomMetricsDictionary<T>(HitBuilder<T> builder){ foreach(KeyValuePair<int, string> entry in builder.GetCustomMetrics()) { addCustomMetricToDictionary(entry.Key, entry.Value); } } [DllImport("__Internal")] private static extern void buildCampaignParametersDictionary(string source, string medium, string name, string content, string keyword); public void _buildCampaignParametersDictionary<T>(HitBuilder<T> builder){ if(!String.IsNullOrEmpty(builder.GetCampaignSource())){ buildCampaignParametersDictionary(builder.GetCampaignSource(), builder.GetCampaignMedium() != null ? builder.GetCampaignMedium() : "", builder.GetCampaignName() != null? builder.GetCampaignName() : "", builder.GetCampaignContent() != null? builder.GetCampaignContent() : "", builder.GetCampaignKeyword() != null? builder.GetCampaignKeyword() : ""); } else if(!String.IsNullOrEmpty(builder.GetCampaignMedium()) || !String.IsNullOrEmpty(builder.GetCampaignName()) || !String.IsNullOrEmpty(builder.GetCampaignMedium()) || !String.IsNullOrEmpty(builder.GetCampaignContent()) || !String.IsNullOrEmpty(builder.GetCampaignKeyword())) { Debug.Log("A required parameter (campaign source) is null or empty. No campaign parameters will be added to hit."); } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { #if HTTP_DLL internal enum WindowsProxyUsePolicy #else public enum WindowsProxyUsePolicy #endif { DoNotUseProxy = 0, // Don't use a proxy at all. UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported. UseWinInetProxy = 2, // WPAD protocol and PAC files supported. UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property. } #if HTTP_DLL internal enum CookieUsePolicy #else public enum CookieUsePolicy #endif { IgnoreCookies = 0, UseInternalCookieStoreOnly = 1, UseSpecifiedCookieContainer = 2 } #if HTTP_DLL internal class WinHttpHandler : HttpMessageHandler #else public class WinHttpHandler : HttpMessageHandler #endif { #if NET46 internal static readonly Version HttpVersion20 = new Version(2, 0); internal static readonly Version HttpVersionUnknown = new Version(0, 0); #else internal static Version HttpVersion20 => HttpVersionInternal.Version20; internal static Version HttpVersionUnknown => HttpVersionInternal.Unknown; #endif private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); [ThreadStatic] private static StringBuilder t_requestHeadersBuilder; private object _lockObject = new object(); private bool _doManualDecompressionCheck = false; private WinInetProxyHelper _proxyHelper = null; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; private CookieContainer _cookieContainer = null; private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available. private Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback = null; private bool _checkCertificateRevocationList = false; private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual; private X509Certificate2Collection _clientCertificates = null; // Only create collection when required. private ICredentials _serverCredentials = null; private bool _preAuthenticate = false; private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy; private ICredentials _defaultProxyCredentials = null; private IWebProxy _proxy = null; private int _maxConnectionsPerServer = int.MaxValue; private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30); private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _maxResponseDrainSize = 64 * 1024; private IDictionary<String, Object> _properties; // Only create dictionary when required. private volatile bool _operationStarted; private volatile bool _disposed; private SafeWinHttpHandle _sessionHandle; private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper(); public WinHttpHandler() { } #region Properties public bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } public int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } public CookieUsePolicy CookieUsePolicy { get { return _cookieUsePolicy; } set { if (value != CookieUsePolicy.IgnoreCookies && value != CookieUsePolicy.UseInternalCookieStoreOnly && value != CookieUsePolicy.UseSpecifiedCookieContainer) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _cookieUsePolicy = value; } } public CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } public SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } public Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } public bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } public ClientCertificateOption ClientCertificateOption { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } public X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } public bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } public ICredentials ServerCredentials { get { return _serverCredentials; } set { _serverCredentials = value; } } public WindowsProxyUsePolicy WindowsProxyUsePolicy { get { return _windowsProxyUsePolicy; } set { if (value != WindowsProxyUsePolicy.DoNotUseProxy && value != WindowsProxyUsePolicy.UseWinHttpProxy && value != WindowsProxyUsePolicy.UseWinInetProxy && value != WindowsProxyUsePolicy.UseCustomProxy) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _windowsProxyUsePolicy = value; } } public ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } public IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } public int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { // In WinHTTP, setting this to 0 results in it being reset to 2. // So, we'll only allow settings above 0. throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } public TimeSpan SendTimeout { get { return _sendTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _sendTimeout = value; } } public TimeSpan ReceiveHeadersTimeout { get { return _receiveHeadersTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveHeadersTimeout = value; } } public TimeSpan ReceiveDataTimeout { get { return _receiveDataTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveDataTimeout = value; } } public int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } public int MaxResponseDrainSize { get { return _maxResponseDrainSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseDrainSize = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (disposing && _sessionHandle != null) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } } base.Dispose(disposing); } #if HTTP_DLL protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #else protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #endif { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } // Check for invalid combinations of properties. if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy); } if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null) { throw new InvalidOperationException(SR.net_http_invalid_proxy); } if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); // Create state object and save current values of handler settings. var state = new WinHttpRequestState(); state.Tcs = tcs; state.CancellationToken = cancellationToken; state.RequestMessage = request; state.Handler = this; state.CheckCertificateRevocationList = _checkCertificateRevocationList; state.ServerCertificateValidationCallback = _serverCertificateValidationCallback; state.WindowsProxyUsePolicy = _windowsProxyUsePolicy; state.Proxy = _proxy; state.ServerCredentials = _serverCredentials; state.DefaultProxyCredentials = _defaultProxyCredentials; state.PreAuthenticate = _preAuthenticate; Task.Factory.StartNew( s => { var whrs = (WinHttpRequestState)s; whrs.Handler.StartRequest(whrs); }, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return tcs.Task; } private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage) { bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue && requestMessage.Headers.TransferEncodingChunked.Value; HttpContent requestContent = requestMessage.Content; if (requestContent != null) { if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up // stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain // the same behavior. requestContent.Headers.ContentLength = null; } } else { if (!chunkedMode) { // Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given. // Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and // buffers the content as well in some cases. But the WinHttpHandler can't access // the protected internal TryComputeLength() method of the content. So, it // will use'Transfer-Encoding: chunked' semantics. chunkedMode = true; requestMessage.Headers.TransferEncodingChunked = true; } } } else if (chunkedMode) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } return chunkedMode; } private static void AddRequestHeaders( SafeWinHttpHandle requestHandle, HttpRequestMessage requestMessage, CookieContainer cookies) { // Get a StringBuilder to use for creating the request headers. // We cache one in TLS to avoid creating a new one for each request. StringBuilder requestHeadersBuffer = t_requestHeadersBuilder; if (requestHeadersBuffer != null) { requestHeadersBuffer.Clear(); } else { t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder(); } // Manually add cookies. if (cookies != null && cookies.Count > 0) { string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies); if (!string.IsNullOrEmpty(cookieHeader)) { requestHeadersBuffer.AppendLine(cookieHeader); } } // Serialize general request headers. requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString()); // Serialize entity-body (content) headers. if (requestMessage.Content != null) { // TODO (#5523): Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (requestMessage.Content.Headers.ContentLength.HasValue) { long contentLength = requestMessage.Content.Headers.ContentLength.Value; requestMessage.Content.Headers.ContentLength = null; requestMessage.Content.Headers.ContentLength = contentLength; } requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString()); } // Add request headers to WinHTTP request handle. if (!Interop.WinHttp.WinHttpAddRequestHeaders( requestHandle, requestHeadersBuffer, (uint)requestHeadersBuffer.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void EnsureSessionHandleExists(WinHttpRequestState state) { if (_sessionHandle == null) { lock (_lockObject) { if (_sessionHandle == null) { SafeWinHttpHandle sessionHandle; uint accessType; // If a custom proxy is specified and it is really the system web proxy // (initial WebRequest.DefaultWebProxy) then we need to update the settings // since that object is only a sentinel. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { Debug.Assert(state.Proxy != null); try { state.Proxy.GetProxy(state.RequestMessage.RequestUri); } catch (PlatformNotSupportedException) { // This is the system web proxy. state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; state.Proxy = null; } } if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { // Either no proxy at all or a custom IWebProxy proxy is specified. // For a custom IWebProxy, we'll need to calculate and set the proxy // on a per request handle basis using the request Uri. For now, // we set the session handle to have no proxy. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy) { // Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY; } else { // Use WinInet per-user proxy settings. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY; } WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, accessType, Interop.WinHttp.WINHTTP_NO_PROXY_NAME, Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); if (sessionHandle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError); if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER) { ThrowOnInvalidHandle(sessionHandle); } // We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support // WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy // settings ourself using our WinInetProxyHelper object. _proxyHelper = new WinInetProxyHelper(); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, _proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, _proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME, _proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); ThrowOnInvalidHandle(sessionHandle); } uint optionAssuredNonBlockingTrue = 1; // TRUE if (!Interop.WinHttp.WinHttpSetOption( sessionHandle, Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS, ref optionAssuredNonBlockingTrue, (uint)sizeof(uint))) { // This option is not available on downlevel Windows versions. While it improves // performance, we can ignore the error that the option is not available. int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw WinHttpException.CreateExceptionUsingError(lastError); } } SetSessionHandleOptions(sessionHandle); _sessionHandle = sessionHandle; } } } } private async void StartRequest(WinHttpRequestState state) { if (state.CancellationToken.IsCancellationRequested) { state.Tcs.TrySetCanceled(state.CancellationToken); state.ClearSendRequestState(); return; } SafeWinHttpHandle connectHandle = null; try { EnsureSessionHandleExists(state); // Specify an HTTP server. connectHandle = Interop.WinHttp.WinHttpConnect( _sessionHandle, state.RequestMessage.RequestUri.Host, (ushort)state.RequestMessage.RequestUri.Port, 0); ThrowOnInvalidHandle(connectHandle); connectHandle.SetParentHandle(_sessionHandle); // Try to use the requested version if a known/supported version was explicitly requested. // Otherwise, we simply use winhttp's default. string httpVersion = null; if (state.RequestMessage.Version == HttpVersionInternal.Version10) { httpVersion = "HTTP/1.0"; } else if (state.RequestMessage.Version == HttpVersionInternal.Version11) { httpVersion = "HTTP/1.1"; } // Turn off additional URI reserved character escaping (percent-encoding). This matches // .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding // of reserved characters. uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE; if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https) { flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE; } // Create an HTTP request handle. state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest( connectHandle, state.RequestMessage.Method.Method, state.RequestMessage.RequestUri.PathAndQuery, httpVersion, Interop.WinHttp.WINHTTP_NO_REFERER, Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES, flags); ThrowOnInvalidHandle(state.RequestHandle); state.RequestHandle.SetParentHandle(connectHandle); // Set callback function. SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate); // Set needed options on the request handle. SetRequestHandleOptions(state); bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage); AddRequestHeaders( state.RequestHandle, state.RequestMessage, _cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null); uint proxyAuthScheme = 0; uint serverAuthScheme = 0; state.RetryRequest = false; // The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle. // We will detect a cancellation request on the cancellation token by registering a callback. // If the callback is invoked, then we begin the abort process by disposing the handle. This // will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks // on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide // a more timely, cooperative, cancellation pattern. using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state)) { do { _authHelper.PreAuthenticateRequest(state, proxyAuthScheme); await InternalSendRequestAsync(state); if (state.RequestMessage.Content != null) { await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false); } bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0; if (receivedResponse) { // If we're manually handling cookies, we need to add them to the container after // each response has been received. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state); } _authHelper.CheckResponseForAuthentication( state, ref proxyAuthScheme, ref serverAuthScheme); } } while (state.RetryRequest); } state.CancellationToken.ThrowIfCancellationRequested(); // Since the headers have been read, set the "receive" timeout to be based on each read // call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each // lower layer winsock read. uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds); SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData); HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck); state.Tcs.TrySetResult(responseMessage); } catch (Exception ex) { HandleAsyncException(state, state.SavedException ?? ex); } finally { SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle); state.ClearSendRequestState(); } } private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle) { SetSessionHandleConnectionOptions(sessionHandle); SetSessionHandleTlsOptions(sessionHandle); SetSessionHandleTimeoutOptions(sessionHandle); } private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle) { uint optionData = (uint)_maxConnectionsPerServer; SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData); SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData); } private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle) { uint optionData = 0; SslProtocols sslProtocols = (_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols; if ((sslProtocols & SslProtocols.Tls) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1; } if ((sslProtocols & SslProtocols.Tls11) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1; } if ((sslProtocols & SslProtocols.Tls12) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; } SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData); } private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle) { if (!Interop.WinHttp.WinHttpSetTimeouts( sessionHandle, 0, 0, (int)_sendTimeout.TotalMilliseconds, (int)_receiveHeadersTimeout.TotalMilliseconds)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void SetRequestHandleOptions(WinHttpRequestState state) { SetRequestHandleProxyOptions(state); SetRequestHandleDecompressionOptions(state.RequestHandle); SetRequestHandleRedirectionOptions(state.RequestHandle); SetRequestHandleCookieOptions(state.RequestHandle); SetRequestHandleTlsOptions(state.RequestHandle); SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri); SetRequestHandleCredentialsOptions(state); SetRequestHandleBufferingOptions(state.RequestHandle); SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version); } private void SetRequestHandleProxyOptions(WinHttpRequestState state) { // We've already set the proxy on the session handle if we're using no proxy or default proxy settings. // We only need to change it on the request handle if we have a specific IWebProxy or need to manually // implement Wininet-style auto proxy detection. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy) { var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO(); bool updateProxySettings = false; Uri uri = state.RequestMessage.RequestUri; try { if (state.Proxy != null) { Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy); updateProxySettings = true; if (state.Proxy.IsBypassed(uri)) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; Uri proxyUri = state.Proxy.GetProxy(uri); string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority; proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString); } } else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed) { if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo)) { updateProxySettings = true; } } if (updateProxySettings) { GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned); try { SetWinHttpOption( state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_PROXY, pinnedHandle.AddrOfPinnedObject(), (uint)Marshal.SizeOf(proxyInfo)); } finally { pinnedHandle.Free(); } } } finally { Marshal.FreeHGlobal(proxyInfo.Proxy); Marshal.FreeHGlobal(proxyInfo.ProxyBypass); } } } private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticDecompression != DecompressionMethods.None) { if ((_automaticDecompression & DecompressionMethods.GZip) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP; } if ((_automaticDecompression & DecompressionMethods.Deflate) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE; } try { SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData); } catch (WinHttpException ex) { if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw; } // We are running on a platform earlier than Win8.1 for which WINHTTP.DLL // doesn't support this option. So, we'll have to do the decompression // manually. _doManualDecompressionCheck = true; } } } private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticRedirection) { optionData = (uint)_maxAutomaticRedirections; SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS, ref optionData); } optionData = _automaticRedirection ? Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP : Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData); } private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle) { if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer || _cookieUsePolicy == CookieUsePolicy.IgnoreCookies) { uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData); } } private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle) { // If we have a custom server certificate validation callback method then // we need to have WinHTTP ignore some errors so that the callback method // will have a chance to be called. uint optionData; if (_serverCertificateValidationCallback != null) { optionData = Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData); } else if (_checkCertificateRevocationList) { // If no custom validation method, then we let WinHTTP do the revocation check itself. optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData); } } private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri) { if (requestUri.Scheme != UriScheme.Https) { return; } X509Certificate2 clientCertificate = null; if (_clientCertificateOption == ClientCertificateOption.Manual) { clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates); } else { clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(); } if (clientCertificate != null) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, clientCertificate.Handle, (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>()); } else { SetNoClientCertificate(requestHandle); } } internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, IntPtr.Zero, 0); } private void SetRequestHandleCredentialsOptions(WinHttpRequestState state) { // By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials // (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends // default credentials to a server (401 response) if the server is considered to be on the Intranet. // WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between // proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in // the request processing (after getting a 401/407 response) when the proxy or server credential is set as // CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials // from being automatically sent until we get a 401/407 response. _authHelper.ChangeDefaultCredentialsPolicy( state.RequestHandle, Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER, allowDefaultCredentials:false); } private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle) { uint optionData = (uint)(_maxResponseHeadersLength * 1024); SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData); optionData = (uint)_maxResponseDrainSize; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData); } private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion) { Debug.Assert(requestHandle != null); if (requestVersion == HttpVersion20) { WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: setting HTTP/2 option"); uint optionData = Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2; if (Interop.WinHttp.WinHttpSetOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, ref optionData)) { WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option supported"); } else { WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option not supported"); } } } private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData) { Debug.Assert(handle != null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, ref optionData)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData) { Debug.Assert(handle != null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, optionData, (uint)optionData.Length)) { WinHttpException.ThrowExceptionUsingLastError(); } } private static void SetWinHttpOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionSize) { Debug.Assert(handle != null); if (!Interop.WinHttp.WinHttpSetOption( handle, option, optionData, optionSize)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void HandleAsyncException(WinHttpRequestState state, Exception ex) { if (state.CancellationToken.IsCancellationRequested) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. state.Tcs.TrySetCanceled(state.CancellationToken); } else if (ex is WinHttpException || ex is IOException || ex is InvalidOperationException) { // Wrap expected exceptions as HttpRequestExceptions since this is considered an error during // execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions // are 'unexpected' or caused by user error and should not be wrapped. state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } else { state.Tcs.TrySetException(ex); } } private void SetOperationStarted() { if (!_operationStarted) { _operationStarted = true; } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_operationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private void SetStatusCallback( SafeWinHttpHandle requestHandle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback) { const uint notificationFlags = Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST; IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback( requestHandle, callback, notificationFlags, IntPtr.Zero); if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)) { int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed. { throw WinHttpException.CreateExceptionUsingError(lastError); } } } private void ThrowOnInvalidHandle(SafeWinHttpHandle handle) { if (handle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError); throw WinHttpException.CreateExceptionUsingError(lastError); } } private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state) { lock (state.Lock) { state.Pin(); if (!Interop.WinHttp.WinHttpSendRequest( state.RequestHandle, null, 0, IntPtr.Zero, 0, 0, state.ToIntPtr())) { int lastError = Marshal.GetLastWin32Error(); Debug.Assert((unchecked((int)lastError) != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER && unchecked((int)lastError) != unchecked((int)0x80090321)), // SEC_E_BUFFER_TOO_SMALL $"Unexpected async error in WinHttpRequestCallback: {unchecked((int)lastError)}"); // Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate // our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING // notifications which would normally cause the state object to be unpinned and disposed. state.Dispose(); throw WinHttpException.CreateExceptionUsingError(lastError); } } return state.LifecycleAwaitable; } private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend) { using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend)) { await state.RequestMessage.Content.CopyToAsync( requestStream, state.TransportContext).ConfigureAwait(false); await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false); } } private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state) { lock (state.Lock) { if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero)) { throw WinHttpException.CreateExceptionUsingLastError(); } } return state.LifecycleAwaitable; } } }
// *********************************************************************** // Copyright (c) 2008-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Builders { /// <summary> /// NUnitTestCaseBuilder is a utility class used by attributes /// that build test cases. /// </summary> public class NUnitTestCaseBuilder { private readonly Randomizer _randomizer = Randomizer.CreateRandomizer(); private readonly TestNameGenerator _nameGenerator; /// <summary> /// Constructs an <see cref="NUnitTestCaseBuilder"/> /// </summary> public NUnitTestCaseBuilder() { _nameGenerator = new TestNameGenerator(); } /// <summary> /// Builds a single NUnitTestMethod, either as a child of the fixture /// or as one of a set of test cases under a ParameterizedTestMethodSuite. /// </summary> /// <param name="method">The MethodInfo from which to construct the TestMethod</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> /// <param name="parms">The ParameterSet to be used, or null</param> /// <returns></returns> public TestMethod BuildTestMethod(IMethodInfo method, Test parentSuite, TestCaseParameters parms) { var testMethod = new TestMethod(method, parentSuite) { Seed = _randomizer.Next() }; CheckTestMethodSignature(testMethod, parms); if (parms == null || parms.Arguments == null) testMethod.ApplyAttributesToTest(method.MethodInfo); // NOTE: After the call to CheckTestMethodSignature, the Method // property of testMethod may no longer be the same as the // original MethodInfo, so we don't use it here. string prefix = testMethod.Method.TypeInfo.FullName; // Needed to give proper fullname to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. if (parentSuite != null) prefix = parentSuite.FullName; if (parms != null) { parms.ApplyToTest(testMethod); if (parms.TestName != null) { // The test is simply for efficiency testMethod.Name = parms.TestName.Contains("{") ? new TestNameGenerator(parms.TestName).GetDisplayName(testMethod, parms.OriginalArguments) : parms.TestName; } else { testMethod.Name = _nameGenerator.GetDisplayName(testMethod, parms.OriginalArguments); } } else { testMethod.Name = _nameGenerator.GetDisplayName(testMethod, null); } testMethod.FullName = prefix + "." + testMethod.Name; return testMethod; } #region Helper Methods /// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the _values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> /// <remarks> /// The return value is no longer used internally, but is retained /// for testing purposes. /// </remarks> private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms) { if (testMethod.Method.IsAbstract) return MarkAsNotRunnable(testMethod, "Method is abstract"); if (!testMethod.Method.IsPublic) return MarkAsNotRunnable(testMethod, "Method is not public"); IParameterInfo[] parameters; parameters = testMethod.Method.GetParameters(); int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) minArgsNeeded++; } int maxArgsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } ITypeInfo returnType = testMethod.Method.ReturnType; #if ASYNC if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo)) { if (returnType.IsType(typeof(void))) return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type"); var returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>); if (returnsGenericTask && (parms == null || !parms.HasExpectedResult)) return MarkAsNotRunnable(testMethod, "Async test method must have non-generic Task return type when no result is expected"); if (!returnsGenericTask && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected"); } else #endif if (returnType.IsType(typeof(void))) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); } else if (parms == null || !parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); if (argsProvided > 0 && maxArgsNeeded == 0) return MarkAsNotRunnable(testMethod, "Arguments provided for method with no parameters"); if (argsProvided == 0 && minArgsNeeded > 0) return MarkAsNotRunnable(testMethod, "No arguments were provided"); if (argsProvided < minArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded)); if (argsProvided > maxArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded)); if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { var typeArguments = new GenericMethodHelper(testMethod.Method.MethodInfo).GetTypeArguments(arglist); foreach (Type o in typeArguments) if (o == null || o == TypeHelper.NonmatchingType) return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (arglist != null && parameters != null) TypeHelper.ConvertArgumentList(arglist, parameters); return true; } private static bool MarkAsNotRunnable(TestMethod testMethod, string reason) { testMethod.MakeInvalid(reason); return false; } #endregion } }
/* * 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 QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// In this algorithm we submit/update/cancel each order type /// </summary> /// <meta name="tag" content="trading and orders" /> /// <meta name="tag" content="placing orders" /> /// <meta name="tag" content="managing orders" /> /// <meta name="tag" content="order tickets" /> /// <meta name="tag" content="updating orders" /> public class OrderTicketDemoAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private const string symbol = "SPY"; private readonly List<OrderTicket> _openMarketOnOpenOrders = new List<OrderTicket>(); private readonly List<OrderTicket> _openMarketOnCloseOrders = new List<OrderTicket>(); private readonly List<OrderTicket> _openLimitOrders = new List<OrderTicket>(); private readonly List<OrderTicket> _openStopMarketOrders = new List<OrderTicket>(); private readonly List<OrderTicket> _openStopLimitOrders = new List<OrderTicket>(); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 7); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { // MARKET ORDERS MarketOrders(); // LIMIT ORDERS LimitOrders(); // STOP MARKET ORDERS StopMarketOrders(); // STOP LIMIT ORDERS StopLimitOrders(); // MARKET ON OPEN ORDERS MarketOnOpenOrders(); // MARKET ON CLOSE ORDERS MarketOnCloseOrders(); } /// <summary> /// MarketOrders are the only orders that are processed synchronously by default, so /// they'll fill by the next line of code. This behavior equally applies to live mode. /// You can opt out of this behavior by specifying the 'asynchronous' parameter as true. /// </summary> private void MarketOrders() { if (TimeIs(7, 9, 31)) { Log("Submitting MarketOrder"); // submit a market order to buy 10 shares, this function returns an OrderTicket object // we submit the order with asynchronous:false, so it block until it is filled var newTicket = MarketOrder(symbol, 10, asynchronous: false); if (newTicket.Status != OrderStatus.Filled) { Log("Synchronous market order was not filled synchronously!"); Quit(); } // we can also submit the ticket asynchronously. In a backtest, we'll still perform // the fill before the next time events for your algorithm. here we'll submit the order // asynchronously and try to cancel it, sometimes it will, sometimes it will be filled // first. newTicket = MarketOrder(symbol, 10, asynchronous: true); var response = newTicket.Cancel("Attempt to cancel async order"); if (response.IsSuccess) { Log("Successfully canceled async market order: " + newTicket.OrderId); } else { Log("Unable to cancel async market order: " + response.ErrorCode); } } } /// <summary> /// LimitOrders are always processed asynchronously. Limit orders are used to /// set 'good' entry points for an order. For example, you may wish to go /// long a stock, but want a good price, so can place a LimitOrder to buy with /// a limit price below the current market price. Likewise the opposite is true /// when selling, you can place a LimitOrder to sell with a limit price above the /// current market price to get a better sale price. /// You can submit requests to update or cancel the LimitOrder at any time. /// The 'LimitPrice' for an order can be retrieved from the ticket using the /// OrderTicket.Get(OrderField) method, for example: /// <code> /// var currentLimitPrice = orderTicket.Get(OrderField.LimitPrice); /// </code> /// </summary> private void LimitOrders() { if (TimeIs(7, 12, 0)) { Log("Submitting LimitOrder"); // submit a limit order to buy 10 shares at .1% below the bar's close var close = Securities[symbol].Close; var newTicket = LimitOrder(symbol, 10, close * .999m); _openLimitOrders.Add(newTicket); // submit another limit order to sell 10 shares at .1% above the bar's close newTicket = LimitOrder(symbol, -10, close * 1.001m); _openLimitOrders.Add(newTicket); } // when we submitted new limit orders we placed them into this list, // so while there's two entries they're still open and need processing if (_openLimitOrders.Count == 2) { var openOrders = _openLimitOrders; // check if either is filled and cancel the other var longOrder = openOrders[0]; var shortOrder = openOrders[1]; if (CheckPairOrdersForFills(longOrder, shortOrder)) { _openLimitOrders.Clear(); return; } // if niether order has filled, bring in the limits by a penny var newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01m; var newShortLimit = shortOrder.Get(OrderField.LimitPrice) - 0.01m; Log($"Updating limits - Long: {newLongLimit.ToStringInvariant("0.00")} Short: {newShortLimit.ToStringInvariant("0.00")}"); longOrder.Update(new UpdateOrderFields { // we could change the quantity, but need to specify it //Quantity = LimitPrice = newLongLimit, Tag = "Update #" + (longOrder.UpdateRequests.Count + 1) }); shortOrder.Update(new UpdateOrderFields { LimitPrice = newShortLimit, Tag = "Update #" + (shortOrder.UpdateRequests.Count + 1) }); } } /// <summary> /// StopMarketOrders work in the opposite way that limit orders do. /// When placing a long trade, the stop price must be above current /// market price. In this way it's a 'stop loss' for a short trade. /// When placing a short trade, the stop price must be below current /// market price. In this way it's a 'stop loss' for a long trade. /// You can submit requests to update or cancel the StopMarketOrder at any time. /// The 'StopPrice' for an order can be retrieved from the ticket using the /// OrderTicket.Get(OrderField) method, for example: /// <code> /// var currentStopPrice = orderTicket.Get(OrderField.StopPrice); /// </code> /// </summary> private void StopMarketOrders() { if (TimeIs(7, 12 + 4, 0)) { Log("Submitting StopMarketOrder"); // a long stop is triggered when the price rises above the value // so we'll set a long stop .25% above the current bar's close var close = Securities[symbol].Close; var stopPrice = close * 1.0025m; var newTicket = StopMarketOrder(symbol, 10, stopPrice); _openStopMarketOrders.Add(newTicket); // a short stop is triggered when the price falls below the value // so we'll set a short stop .25% below the current bar's close stopPrice = close * .9975m; newTicket = StopMarketOrder(symbol, -10, stopPrice); _openStopMarketOrders.Add(newTicket); } // when we submitted new stop market orders we placed them into this list, // so while there's two entries they're still open and need processing if (_openStopMarketOrders.Count == 2) { // check if either is filled and cancel the other var longOrder = _openStopMarketOrders[0]; var shortOrder = _openStopMarketOrders[1]; if (CheckPairOrdersForFills(longOrder, shortOrder)) { _openStopMarketOrders.Clear(); return; } // if niether order has filled, bring in the stops by a penny var newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01m; var newShortStop = shortOrder.Get(OrderField.StopPrice) + 0.01m; Log($"Updating stops - Long: {newLongStop.ToStringInvariant("0.00")} Short: {newShortStop.ToStringInvariant("0.00")}"); longOrder.Update(new UpdateOrderFields { // we could change the quantity, but need to specify it //Quantity = StopPrice = newLongStop, Tag = "Update #" + (longOrder.UpdateRequests.Count + 1) }); shortOrder.Update(new UpdateOrderFields { StopPrice = newShortStop, Tag = "Update #" + (shortOrder.UpdateRequests.Count + 1) }); } } /// <summary> /// StopLimitOrders work as a combined stop and limit order. First, the /// price must pass the stop price in the same way a StopMarketOrder works, /// but then we're also gauranteed a fill price at least as good as the /// limit price. This order type can be beneficial in gap down scenarios /// where a StopMarketOrder would have triggered and given the not as beneficial /// gapped down price, whereas the StopLimitOrder could protect you from /// getting the gapped down price through prudent placement of the limit price. /// You can submit requests to update or cancel the StopLimitOrder at any time. /// The 'StopPrice' or 'LimitPrice' for an order can be retrieved from the ticket /// using the OrderTicket.Get(OrderField) method, for example: /// <code> /// var currentStopPrice = orderTicket.Get(OrderField.StopPrice); /// var currentLimitPrice = orderTicket.Get(OrderField.LimitPrice); /// </code> /// </summary> private void StopLimitOrders() { if (TimeIs(8, 12, 1)) { Log("Submitting StopLimitOrder"); // a long stop is triggered when the price rises above the value // so we'll set a long stop .25% above the current bar's close // now we'll also be setting a limit, this means we are gauranteed // to get at least the limit price for our fills, so make the limit // price a little softer than the stop price var close = Securities[symbol].Close; var stopPrice = close * 1.001m; var limitPrice = close - 0.03m; var newTicket = StopLimitOrder(symbol, 10, stopPrice, limitPrice); _openStopLimitOrders.Add(newTicket); // a short stop is triggered when the price falls below the value // so we'll set a short stop .25% below the current bar's close // now we'll also be setting a limit, this means we are gauranteed // to get at least the limit price for our fills, so make the limit // price a little softer than the stop price stopPrice = close * .999m; limitPrice = close + 0.03m; newTicket = StopLimitOrder(symbol, -10, stopPrice, limitPrice); _openStopLimitOrders.Add(newTicket); } // when we submitted new stop limit orders we placed them into this list, // so while there's two entries they're still open and need processing if (_openStopLimitOrders.Count == 2) { // check if either is filled and cancel the other var longOrder = _openStopLimitOrders[0]; var shortOrder = _openStopLimitOrders[1]; if (CheckPairOrdersForFills(longOrder, shortOrder)) { _openStopLimitOrders.Clear(); return; } // if niether order has filled, bring in the stops/limits in by a penny var newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01m; var newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01m; var newShortStop = shortOrder.Get(OrderField.StopPrice) + 0.01m; var newShortLimit = shortOrder.Get(OrderField.LimitPrice) - 0.01m; Log($"Updating stops - Long: {newLongStop.ToStringInvariant("0.00")} Short: {newShortStop.ToStringInvariant("0.00")}"); Log($"Updating limits - Long: {newLongLimit.ToStringInvariant("0.00")} Short: {newShortLimit.ToStringInvariant("0.00")}"); longOrder.Update(new UpdateOrderFields { // we could change the quantity, but need to specify it //Quantity = StopPrice = newLongStop, LimitPrice = newLongLimit, Tag = "Update #" + (longOrder.UpdateRequests.Count + 1) }); shortOrder.Update(new UpdateOrderFields { StopPrice = newShortStop, LimitPrice = newShortLimit, Tag = "Update #" + (shortOrder.UpdateRequests.Count + 1) }); } } /// <summary> /// MarketOnCloseOrders are always executed at the next market's closing /// price. The only properties that can be updated are the quantity and /// order tag properties. /// </summary> private void MarketOnCloseOrders() { if (TimeIs(9, 12, 0)) { Log("Submitting MarketOnCloseOrder"); // open a new position or triple our existing position var qty = Portfolio[symbol].Quantity; qty = qty == 0 ? 100 : 2*qty; var newTicket = MarketOnCloseOrder(symbol, qty); _openMarketOnCloseOrders.Add(newTicket); } if (_openMarketOnCloseOrders.Count == 1 && Time.Minute == 59) { var ticket = _openMarketOnCloseOrders[0]; // check for fills if (ticket.Status == OrderStatus.Filled) { _openMarketOnCloseOrders.Clear(); return; } var quantity = ticket.Quantity + 1; Log("Updating quantity - New Quantity: " + quantity); // we can update the quantity and tag ticket.Update(new UpdateOrderFields { Quantity = quantity, Tag = "Update #" + (ticket.UpdateRequests.Count + 1) }); } if (TimeIs(EndDate.Day, 12 + 3, 45)) { Log("Submitting MarketOnCloseOrder to liquidate end of algorithm"); MarketOnCloseOrder(symbol, -Portfolio[symbol].Quantity, "Liquidate end of algorithm"); } } /// <summary> /// MarketOnOpenOrders are always executed at the next market's opening /// price. The only properties that can be updated are the quantity and /// order tag properties. /// </summary> private void MarketOnOpenOrders() { if (TimeIs(8, 12 + 2, 0)) { Log("Submitting MarketOnOpenOrder"); // its EOD, let's submit a market on open order to short even more! var newTicket = MarketOnOpenOrder(symbol, 50); _openMarketOnOpenOrders.Add(newTicket); } if (_openMarketOnOpenOrders.Count == 1 && Time.Minute == 59) { var ticket = _openMarketOnOpenOrders[0]; // check for fills if (ticket.Status == OrderStatus.Filled) { _openMarketOnOpenOrders.Clear(); return; } var quantity = ticket.Quantity + 1; Log("Updating quantity - New Quantity: " + quantity); // we can update the quantity and tag ticket.Update(new UpdateOrderFields { Quantity = quantity, Tag = "Update #" + (ticket.UpdateRequests.Count + 1) }); } } public override void OnOrderEvent(OrderEvent orderEvent) { var order = Transactions.GetOrderById(orderEvent.OrderId); Console.WriteLine("{0}: {1}: {2}", Time, order.Type, orderEvent); if (orderEvent.Quantity == 0) { throw new Exception("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity"); } if (orderEvent.Quantity != order.Quantity) { throw new Exception("OrderEvent quantity should hold the current order Quantity"); } if (order is LimitOrder && orderEvent.LimitPrice == 0 || order is StopLimitOrder && orderEvent.LimitPrice == 0) { throw new Exception("OrderEvent LimitPrice is Not expected to be 0 for LimitOrder and StopLimitOrder"); } if (order is StopMarketOrder && orderEvent.StopPrice == 0) { throw new Exception("OrderEvent StopPrice is Not expected to be 0 for StopMarketOrder"); } } private bool CheckPairOrdersForFills(OrderTicket longOrder, OrderTicket shortOrder) { if (longOrder.Status == OrderStatus.Filled) { Log(shortOrder.OrderType + ": Cancelling short order, long order is filled."); shortOrder.Cancel("Long filled."); return true; } if (shortOrder.Status == OrderStatus.Filled) { Log(longOrder.OrderType + ": Cancelling long order, short order is filled."); longOrder.Cancel("Short filled"); return true; } return false; } private bool TimeIs(int day, int hour, int minute) { return Time.Day == day && Time.Hour == hour && Time.Minute == minute; } /// <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", "8"}, {"Average Win", "0%"}, {"Average Loss", "-0.01%"}, {"Compounding Annual Return", "91.836%"}, {"Drawdown", "0.100%"}, {"Expectancy", "-1"}, {"Net Profit", "0.836%"}, {"Sharpe Ratio", "12.924"}, {"Probabilistic Sharpe Ratio", "99.044%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.247"}, {"Beta", "0.23"}, {"Annual Standard Deviation", "0.054"}, {"Annual Variance", "0.003"}, {"Information Ratio", "-7.426"}, {"Tracking Error", "0.172"}, {"Treynor Ratio", "3.059"}, {"Total Fees", "$8.00"}, {"Estimated Strategy Capacity", "$48000000.00"}, {"Lowest Capacity Asset", "SPY R735QTJ8XC9X"}, {"Fitness Score", "0.093"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "150.447"}, {"Return Over Maximum Drawdown", "1180.131"}, {"Portfolio Turnover", "0.093"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "11d64052951ca2d3abf586c88d41a97a"} }; } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace System.Windows.Controls { /// <summary> /// A column that displays a hyperlink. /// </summary> public class DataGridHyperlinkColumn : DataGridBoundColumn { static DataGridHyperlinkColumn() { ElementStyleProperty.OverrideMetadata(typeof(DataGridHyperlinkColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); EditingElementStyleProperty.OverrideMetadata(typeof(DataGridHyperlinkColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); } #region Hyperlink Column Properties /// <summary> /// Dependecy property for TargetName Property /// </summary> public static readonly DependencyProperty TargetNameProperty = Hyperlink.TargetNameProperty.AddOwner( typeof(DataGridHyperlinkColumn), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DataGridColumn.NotifyPropertyChangeForRefreshContent))); /// <summary> /// The property which determines the target name of the hyperlink /// </summary> public string TargetName { get { return (string)GetValue(TargetNameProperty); } set { SetValue(TargetNameProperty, value); } } /// <summary> /// The binding to the content to be display under hyperlink /// </summary> public BindingBase ContentBinding { get { return _contentBinding; } set { if (_contentBinding != value) { BindingBase oldValue = _contentBinding; _contentBinding = value; OnContentBindingChanged(oldValue, value); } } } /// <summary> /// Called when ContentBinding changes. /// </summary> /// <remarks> /// Default implementation notifies the DataGrid and its subtree about the change. /// </remarks> /// <param name="oldBinding">The old binding.</param> /// <param name="newBinding">The new binding.</param> protected virtual void OnContentBindingChanged(BindingBase oldBinding, BindingBase newBinding) { NotifyPropertyChanged("ContentBinding"); } /// <summary> /// Try applying ContentBinding. If it doesnt work out apply Binding. /// </summary> /// <param name="target"></param> /// <param name="property"></param> private void ApplyContentBinding(DependencyObject target, DependencyProperty property) { if (ContentBinding != null) { BindingOperations.SetBinding(target, property, ContentBinding); } else if (Binding != null) { BindingOperations.SetBinding(target, property, Binding); } else { BindingOperations.ClearBinding(target, property); } } #endregion #region Property Changed Handler /// <summary> /// Override which rebuilds the cell's visual tree for ContentBinding change /// and Modifies Hyperlink for TargetName change /// </summary> /// <param name="element"></param> /// <param name="propertyName"></param> protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null && !cell.IsEditing) { if (string.Compare(propertyName, "ContentBinding", StringComparison.Ordinal) == 0) { cell.BuildVisualTree(); } else if (string.Compare(propertyName, "TargetName", StringComparison.Ordinal) == 0) { TextBlock outerBlock = cell.Content as TextBlock; if (outerBlock != null && outerBlock.Inlines.Count > 0) { Hyperlink link = outerBlock.Inlines.FirstInline as Hyperlink; if (link != null) { link.TargetName = TargetName; } } } } else { base.RefreshCellContent(element, propertyName); } } #endregion #region Styles /// <summary> /// The default value of the ElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultElementStyle { get { return DataGridTextColumn.DefaultElementStyle; } } /// <summary> /// The default value of the EditingElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultEditingElementStyle { get { return DataGridTextColumn.DefaultEditingElementStyle; } } #endregion #region Element Generation /// <summary> /// Creates the visual tree for cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock outerBlock = new TextBlock(); Hyperlink link = new Hyperlink(); InlineUIContainer inlineContainer = new InlineUIContainer(); ContentPresenter innerContentPresenter = new ContentPresenter(); outerBlock.Inlines.Add(link); link.Inlines.Add(inlineContainer); inlineContainer.Child = innerContentPresenter; link.TargetName = TargetName; ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, outerBlock); ApplyBinding(link, Hyperlink.NavigateUriProperty); ApplyContentBinding(innerContentPresenter, ContentPresenter.ContentProperty); DataGridHelper.RestoreFlowDirection(outerBlock, cell); return outerBlock; } /// <summary> /// Creates the visual tree for cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { TextBox textBox = new TextBox(); ApplyStyle(/* isEditing = */ true, /* defaultToElementStyle = */ false, textBox); ApplyBinding(textBox, TextBox.TextProperty); DataGridHelper.RestoreFlowDirection(textBox, cell); return textBox; } #endregion #region Editing /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { TextBox textBox = editingElement as TextBox; if (textBox != null) { textBox.Focus(); string originalValue = textBox.Text; TextCompositionEventArgs textArgs = editingEventArgs as TextCompositionEventArgs; if (textArgs != null) { // If text input started the edit, then replace the text with what was typed. string inputText = textArgs.Text; textBox.Text = inputText; // Place the caret after the end of the text. textBox.Select(inputText.Length, 0); } else { // If something else started the edit, then select the text textBox.SelectAll(); } return originalValue; } return null; } /// <summary> /// Called when a cell's value is to be restored to its original value, /// just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="uneditedValue">The original, unedited value of the cell.</param> protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { DataGridHelper.CacheFlowDirection(editingElement, editingElement != null ? editingElement.Parent as DataGridCell : null); base.CancelCellEdit(editingElement, uneditedValue); } /// <summary> /// Called when a cell's value is to be committed, just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <returns>false if there is a validation error. true otherwise.</returns> protected override bool CommitCellEdit(FrameworkElement editingElement) { DataGridHelper.CacheFlowDirection(editingElement, editingElement != null ? editingElement.Parent as DataGridCell : null); return base.CommitCellEdit(editingElement); } internal override void OnInput(InputEventArgs e) { // Text input will start an edit. // Escape is meant to be for CancelEdit. But DataGrid // may not handle KeyDown event for Escape if nothing // is cancelable. Such KeyDown if unhandled by others // will ultimately get promoted to TextInput and be handled // here. But BeginEdit on escape could be confusing to the user. // Hence escape key is special case and BeginEdit is performed if // there is atleast one non espace key character. if (DataGridHelper.HasNonEscapeCharacters(e as TextCompositionEventArgs)) { BeginEdit(e, true); } else if (DataGridHelper.IsImeProcessed(e as KeyEventArgs)) { if (DataGridOwner != null) { DataGridCell cell = DataGridOwner.CurrentCellContainer; if (cell != null && !cell.IsEditing) { Debug.Assert(e.RoutedEvent == Keyboard.PreviewKeyDownEvent, "We should only reach here on the PreviewKeyDown event because the TextBox within is expected to handle the preview event and hence trump the successive KeyDown event."); BeginEdit(e, false); // // The TextEditor for the TextBox establishes contact with the IME // engine lazily at background priority. However in this case we // want to IME engine to know about the TextBox in earnest before // PostProcessing this input event. Only then will the IME key be // recorded in the TextBox. Hence the call to synchronously drain // the Dispatcher queue. // Dispatcher.Invoke((Action)delegate(){}, System.Windows.Threading.DispatcherPriority.Background); } } } } #endregion #region Data private BindingBase _contentBinding = null; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for VaultsOperations. /// </summary> public static partial class VaultsOperationsExtensions { /// <summary> /// Get the Vault details. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> public static Vault Get(this IVaultsOperations operations, string resourceGroupName, string vaultName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVaultsOperations)s).GetAsync(resourceGroupName, vaultName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the Vault details. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Vault> GetAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a Recovery Services vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> public static Vault CreateOrUpdate(this IVaultsOperations operations, string resourceGroupName, string vaultName, Vault vault) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVaultsOperations)s).CreateOrUpdateAsync(resourceGroupName, vaultName, vault), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a Recovery Services vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Vault> CreateOrUpdateAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, Vault vault, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vaultName, vault, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> public static void Delete(this IVaultsOperations operations, string resourceGroupName, string vaultName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IVaultsOperations)s).DeleteAsync(resourceGroupName, vaultName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> public static Microsoft.Rest.Azure.IPage<Vault> ListByResourceGroup(this IVaultsOperations operations, string resourceGroupName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVaultsOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Vault>> ListByResourceGroupAsync(this IVaultsOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<Vault> ListByResourceGroupNext(this IVaultsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVaultsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Vault>> ListByResourceGroupNextAsync(this IVaultsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes an instance. /// </summary> public partial class Instance { private int? _amiLaunchIndex; private ArchitectureValues _architecture; private List<InstanceBlockDeviceMapping> _blockDeviceMappings = new List<InstanceBlockDeviceMapping>(); private string _clientToken; private bool? _ebsOptimized; private HypervisorType _hypervisor; private IamInstanceProfile _iamInstanceProfile; private string _imageId; private string _instanceId; private InstanceLifecycleType _instanceLifecycle; private InstanceType _instanceType; private string _kernelId; private string _keyName; private DateTime? _launchTime; private Monitoring _monitoring; private List<InstanceNetworkInterface> _networkInterfaces = new List<InstanceNetworkInterface>(); private Placement _placement; private PlatformValues _platform; private string _privateDnsName; private string _privateIpAddress; private List<ProductCode> _productCodes = new List<ProductCode>(); private string _publicDnsName; private string _publicIpAddress; private string _ramdiskId; private string _rootDeviceName; private DeviceType _rootDeviceType; private List<GroupIdentifier> _securityGroups = new List<GroupIdentifier>(); private bool? _sourceDestCheck; private string _spotInstanceRequestId; private string _sriovNetSupport; private InstanceState _state; private StateReason _stateReason; private string _stateTransitionReason; private string _subnetId; private List<Tag> _tags = new List<Tag>(); private VirtualizationType _virtualizationType; private string _vpcId; /// <summary> /// Gets and sets the property AmiLaunchIndex. /// <para> /// The AMI launch index, which can be used to find this instance in the launch group. /// </para> /// </summary> public int AmiLaunchIndex { get { return this._amiLaunchIndex.GetValueOrDefault(); } set { this._amiLaunchIndex = value; } } // Check to see if AmiLaunchIndex property is set internal bool IsSetAmiLaunchIndex() { return this._amiLaunchIndex.HasValue; } /// <summary> /// Gets and sets the property Architecture. /// <para> /// The architecture of the image. /// </para> /// </summary> public ArchitectureValues Architecture { get { return this._architecture; } set { this._architecture = value; } } // Check to see if Architecture property is set internal bool IsSetArchitecture() { return this._architecture != null; } /// <summary> /// Gets and sets the property BlockDeviceMappings. /// <para> /// Any block device mapping entries for the instance. /// </para> /// </summary> public List<InstanceBlockDeviceMapping> BlockDeviceMappings { get { return this._blockDeviceMappings; } set { this._blockDeviceMappings = value; } } // Check to see if BlockDeviceMappings property is set internal bool IsSetBlockDeviceMappings() { return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0; } /// <summary> /// Gets and sets the property ClientToken. /// <para> /// The idempotency token you provided when you launched the instance. /// </para> /// </summary> public string ClientToken { get { return this._clientToken; } set { this._clientToken = value; } } // Check to see if ClientToken property is set internal bool IsSetClientToken() { return this._clientToken != null; } /// <summary> /// Gets and sets the property EbsOptimized. /// <para> /// Indicates whether the instance is optimized for EBS I/O. This optimization provides /// dedicated throughput to Amazon EBS and an optimized configuration stack to provide /// optimal I/O performance. This optimization isn't available with all instance types. /// Additional usage charges apply when using an EBS Optimized instance. /// </para> /// </summary> public bool EbsOptimized { get { return this._ebsOptimized.GetValueOrDefault(); } set { this._ebsOptimized = value; } } // Check to see if EbsOptimized property is set internal bool IsSetEbsOptimized() { return this._ebsOptimized.HasValue; } /// <summary> /// Gets and sets the property Hypervisor. /// <para> /// The hypervisor type of the instance. /// </para> /// </summary> public HypervisorType Hypervisor { get { return this._hypervisor; } set { this._hypervisor = value; } } // Check to see if Hypervisor property is set internal bool IsSetHypervisor() { return this._hypervisor != null; } /// <summary> /// Gets and sets the property IamInstanceProfile. /// <para> /// The IAM instance profile associated with the instance. /// </para> /// </summary> public IamInstanceProfile IamInstanceProfile { get { return this._iamInstanceProfile; } set { this._iamInstanceProfile = value; } } // Check to see if IamInstanceProfile property is set internal bool IsSetIamInstanceProfile() { return this._iamInstanceProfile != null; } /// <summary> /// Gets and sets the property ImageId. /// <para> /// The ID of the AMI used to launch the instance. /// </para> /// </summary> public string ImageId { get { return this._imageId; } set { this._imageId = value; } } // Check to see if ImageId property is set internal bool IsSetImageId() { return this._imageId != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The ID of the instance. /// </para> /// </summary> public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property InstanceLifecycle. /// <para> /// Indicates whether this is a Spot Instance. /// </para> /// </summary> public InstanceLifecycleType InstanceLifecycle { get { return this._instanceLifecycle; } set { this._instanceLifecycle = value; } } // Check to see if InstanceLifecycle property is set internal bool IsSetInstanceLifecycle() { return this._instanceLifecycle != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type. /// </para> /// </summary> public InstanceType InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property KernelId. /// <para> /// The kernel associated with this instance. /// </para> /// </summary> public string KernelId { get { return this._kernelId; } set { this._kernelId = value; } } // Check to see if KernelId property is set internal bool IsSetKernelId() { return this._kernelId != null; } /// <summary> /// Gets and sets the property KeyName. /// <para> /// The name of the key pair, if this instance was launched with an associated key pair. /// </para> /// </summary> public string KeyName { get { return this._keyName; } set { this._keyName = value; } } // Check to see if KeyName property is set internal bool IsSetKeyName() { return this._keyName != null; } /// <summary> /// Gets and sets the property LaunchTime. /// <para> /// The time the instance was launched. /// </para> /// </summary> public DateTime LaunchTime { get { return this._launchTime.GetValueOrDefault(); } set { this._launchTime = value; } } // Check to see if LaunchTime property is set internal bool IsSetLaunchTime() { return this._launchTime.HasValue; } /// <summary> /// Gets and sets the property Monitoring. /// <para> /// The monitoring information for the instance. /// </para> /// </summary> public Monitoring Monitoring { get { return this._monitoring; } set { this._monitoring = value; } } // Check to see if Monitoring property is set internal bool IsSetMonitoring() { return this._monitoring != null; } /// <summary> /// Gets and sets the property NetworkInterfaces. /// <para> /// [EC2-VPC] One or more network interfaces for the instance. /// </para> /// </summary> public List<InstanceNetworkInterface> NetworkInterfaces { get { return this._networkInterfaces; } set { this._networkInterfaces = value; } } // Check to see if NetworkInterfaces property is set internal bool IsSetNetworkInterfaces() { return this._networkInterfaces != null && this._networkInterfaces.Count > 0; } /// <summary> /// Gets and sets the property Placement. /// <para> /// The location where the instance launched. /// </para> /// </summary> public Placement Placement { get { return this._placement; } set { this._placement = value; } } // Check to see if Placement property is set internal bool IsSetPlacement() { return this._placement != null; } /// <summary> /// Gets and sets the property Platform. /// <para> /// The value is <code>Windows</code> for Windows instances; otherwise blank. /// </para> /// </summary> public PlatformValues Platform { get { return this._platform; } set { this._platform = value; } } // Check to see if Platform property is set internal bool IsSetPlatform() { return this._platform != null; } /// <summary> /// Gets and sets the property PrivateDnsName. /// <para> /// The private DNS name assigned to the instance. This DNS name can only be used inside /// the Amazon EC2 network. This name is not available until the instance enters the <code>running</code> /// state. /// </para> /// </summary> public string PrivateDnsName { get { return this._privateDnsName; } set { this._privateDnsName = value; } } // Check to see if PrivateDnsName property is set internal bool IsSetPrivateDnsName() { return this._privateDnsName != null; } /// <summary> /// Gets and sets the property PrivateIpAddress. /// <para> /// The private IP address assigned to the instance. /// </para> /// </summary> public string PrivateIpAddress { get { return this._privateIpAddress; } set { this._privateIpAddress = value; } } // Check to see if PrivateIpAddress property is set internal bool IsSetPrivateIpAddress() { return this._privateIpAddress != null; } /// <summary> /// Gets and sets the property ProductCodes. /// <para> /// The product codes attached to this instance. /// </para> /// </summary> public List<ProductCode> ProductCodes { get { return this._productCodes; } set { this._productCodes = value; } } // Check to see if ProductCodes property is set internal bool IsSetProductCodes() { return this._productCodes != null && this._productCodes.Count > 0; } /// <summary> /// Gets and sets the property PublicDnsName. /// <para> /// The public DNS name assigned to the instance. This name is not available until the /// instance enters the <code>running</code> state. /// </para> /// </summary> public string PublicDnsName { get { return this._publicDnsName; } set { this._publicDnsName = value; } } // Check to see if PublicDnsName property is set internal bool IsSetPublicDnsName() { return this._publicDnsName != null; } /// <summary> /// Gets and sets the property PublicIpAddress. /// <para> /// The public IP address assigned to the instance. /// </para> /// </summary> public string PublicIpAddress { get { return this._publicIpAddress; } set { this._publicIpAddress = value; } } // Check to see if PublicIpAddress property is set internal bool IsSetPublicIpAddress() { return this._publicIpAddress != null; } /// <summary> /// Gets and sets the property RamdiskId. /// <para> /// The RAM disk associated with this instance. /// </para> /// </summary> public string RamdiskId { get { return this._ramdiskId; } set { this._ramdiskId = value; } } // Check to see if RamdiskId property is set internal bool IsSetRamdiskId() { return this._ramdiskId != null; } /// <summary> /// Gets and sets the property RootDeviceName. /// <para> /// The root device name (for example, <code>/dev/sda1</code>). /// </para> /// </summary> public string RootDeviceName { get { return this._rootDeviceName; } set { this._rootDeviceName = value; } } // Check to see if RootDeviceName property is set internal bool IsSetRootDeviceName() { return this._rootDeviceName != null; } /// <summary> /// Gets and sets the property RootDeviceType. /// <para> /// The root device type used by the AMI. The AMI can use an Amazon EBS volume or an instance /// store volume. /// </para> /// </summary> public DeviceType RootDeviceType { get { return this._rootDeviceType; } set { this._rootDeviceType = value; } } // Check to see if RootDeviceType property is set internal bool IsSetRootDeviceType() { return this._rootDeviceType != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// One or more security groups for the instance. /// </para> /// </summary> public List<GroupIdentifier> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SourceDestCheck. /// <para> /// Specifies whether to enable an instance launched in a VPC to perform NAT. This controls /// whether source/destination checking is enabled on the instance. A value of <code>true</code> /// means checking is enabled, and <code>false</code> means checking is disabled. The /// value must be <code>false</code> for the instance to perform NAT. For more information, /// see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html">NAT /// Instances</a> in the <i>Amazon Virtual Private Cloud User Guide</i>. /// </para> /// </summary> public bool SourceDestCheck { get { return this._sourceDestCheck.GetValueOrDefault(); } set { this._sourceDestCheck = value; } } // Check to see if SourceDestCheck property is set internal bool IsSetSourceDestCheck() { return this._sourceDestCheck.HasValue; } /// <summary> /// Gets and sets the property SpotInstanceRequestId. /// <para> /// The ID of the Spot Instance request. /// </para> /// </summary> public string SpotInstanceRequestId { get { return this._spotInstanceRequestId; } set { this._spotInstanceRequestId = value; } } // Check to see if SpotInstanceRequestId property is set internal bool IsSetSpotInstanceRequestId() { return this._spotInstanceRequestId != null; } /// <summary> /// Gets and sets the property SriovNetSupport. /// <para> /// Specifies whether enhanced networking is enabled. /// </para> /// </summary> public string SriovNetSupport { get { return this._sriovNetSupport; } set { this._sriovNetSupport = value; } } // Check to see if SriovNetSupport property is set internal bool IsSetSriovNetSupport() { return this._sriovNetSupport != null; } /// <summary> /// Gets and sets the property State. /// <para> /// The current state of the instance. /// </para> /// </summary> public InstanceState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property StateReason. /// <para> /// The reason for the most recent state transition. /// </para> /// </summary> public StateReason StateReason { get { return this._stateReason; } set { this._stateReason = value; } } // Check to see if StateReason property is set internal bool IsSetStateReason() { return this._stateReason != null; } /// <summary> /// Gets and sets the property StateTransitionReason. /// <para> /// The reason for the most recent state transition. This might be an empty string. /// </para> /// </summary> public string StateTransitionReason { get { return this._stateTransitionReason; } set { this._stateTransitionReason = value; } } // Check to see if StateTransitionReason property is set internal bool IsSetStateTransitionReason() { return this._stateTransitionReason != null; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// The ID of the subnet in which the instance is running. /// </para> /// </summary> public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the instance. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property VirtualizationType. /// <para> /// The virtualization type of the instance. /// </para> /// </summary> public VirtualizationType VirtualizationType { get { return this._virtualizationType; } set { this._virtualizationType = value; } } // Check to see if VirtualizationType property is set internal bool IsSetVirtualizationType() { return this._virtualizationType != null; } /// <summary> /// Gets and sets the property VpcId. /// <para> /// The ID of the VPC in which the instance is running. /// </para> /// </summary> public string VpcId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this._vpcId != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime; using System.Threading.Tasks; using System.ServiceModel.Diagnostics; namespace System.ServiceModel.Channels { public abstract class CommunicationObject : ICommunicationObject, IAsyncCommunicationObject { private bool _aborted; private bool _closeCalled; private object _mutex; private bool _onClosingCalled; private bool _onClosedCalled; private bool _onOpeningCalled; private bool _onOpenedCalled; private bool _raisedClosed; private bool _raisedClosing; private bool _raisedFaulted; private bool _traceOpenAndClose; private object _eventSender; private CommunicationState _state; private bool _onOpenAsyncCalled; private bool _onCloseAsyncCalled; private bool _isSynchronousOpen; private bool _isSynchronousClose; protected CommunicationObject() : this(new object()) { } protected CommunicationObject(object mutex) { _mutex = mutex; _eventSender = this; _state = CommunicationState.Created; } internal bool Aborted { get { return _aborted; } } internal object EventSender { get { return _eventSender; } set { _eventSender = value; } } protected bool IsDisposed { get { return _state == CommunicationState.Closed; } } public CommunicationState State { get { return _state; } } protected object ThisLock { get { return _mutex; } } protected abstract TimeSpan DefaultCloseTimeout { get; } protected abstract TimeSpan DefaultOpenTimeout { get; } internal TimeSpan InternalCloseTimeout { get { return this.DefaultCloseTimeout; } } internal TimeSpan InternalOpenTimeout { get { return this.DefaultOpenTimeout; } } public event EventHandler Closed; public event EventHandler Closing; public event EventHandler Faulted; public event EventHandler Opened; public event EventHandler Opening; public void Abort() { lock (ThisLock) { if (_aborted || _state == CommunicationState.Closed) return; _aborted = true; _state = CommunicationState.Closing; } try { OnClosing(); if (!_onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); OnAbort(); OnClosed(); if (!_onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } finally { } } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return this.BeginClose(this.DefaultCloseTimeout, callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return CloseAsyncInternal(timeout).ToApm(callback, state); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return this.BeginOpen(this.DefaultOpenTimeout, callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OpenAsyncInternal(timeout).ToApm(callback, state); } public void Close() { this.Close(this.DefaultCloseTimeout); } public void Close(TimeSpan timeout) { _isSynchronousClose = true; CloseAsyncInternal(timeout).WaitForCompletion(); } private async Task CloseAsyncInternal(TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await ((IAsyncCommunicationObject)this).CloseAsync(timeout); } async Task IAsyncCommunicationObject.CloseAsync(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.SFxTimeoutOutOfRange0)); CommunicationState originalState; lock (ThisLock) { originalState = _state; if (originalState != CommunicationState.Closed) _state = CommunicationState.Closing; _closeCalled = true; } switch (originalState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: this.Abort(); if (originalState == CommunicationState.Faulted) { throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); } break; case CommunicationState.Opened: { bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnClosing(); if (!_onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); await OnCloseAsync(actualTimeout.RemainingTime()); OnClosed(); if (!_onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); throwing = false; } finally { if (throwing) { Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: break; default: throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } } private Exception CreateNotOpenException() { return new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeUsed, this.GetCommunicationObjectType().ToString(), _state.ToString())); } private Exception CreateImmutableException() { return new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeModifiedInState, this.GetCommunicationObjectType().ToString(), _state.ToString())); } private Exception CreateBaseClassMethodNotCalledException(string method) { return new InvalidOperationException(SR.Format(SR.CommunicationObjectBaseClassMethodNotCalled, this.GetCommunicationObjectType().ToString(), method)); } internal Exception CreateClosedException() { if (!_closeCalled) { return CreateAbortedException(); } else { return new ObjectDisposedException(this.GetCommunicationObjectType().ToString()); } } internal Exception CreateFaultedException() { string message = SR.Format(SR.CommunicationObjectFaulted1, this.GetCommunicationObjectType().ToString()); return new CommunicationObjectFaultedException(message); } internal Exception CreateAbortedException() { return new CommunicationObjectAbortedException(SR.Format(SR.CommunicationObjectAborted1, this.GetCommunicationObjectType().ToString())); } internal bool DoneReceivingInCurrentState() { this.ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: return false; case CommunicationState.Closing: return true; case CommunicationState.Closed: return true; case CommunicationState.Faulted: return true; default: throw Fx.AssertAndThrow("DoneReceivingInCurrentState: Unknown CommunicationObject.state"); } } public void EndClose(IAsyncResult result) { result.ToApmEnd(); } public void EndOpen(IAsyncResult result) { result.ToApmEnd(); } protected void Fault() { lock (ThisLock) { if (_state == CommunicationState.Closed || _state == CommunicationState.Closing) return; if (_state == CommunicationState.Faulted) return; _state = CommunicationState.Faulted; } OnFaulted(); } public void Open() { this.Open(this.DefaultOpenTimeout); } public void Open(TimeSpan timeout) { _isSynchronousOpen = true; OpenAsyncInternal(timeout).WaitForCompletion(); } private async Task OpenAsyncInternal(TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await ((IAsyncCommunicationObject)this).OpenAsync(timeout); } async Task IAsyncCommunicationObject.OpenAsync(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.SFxTimeoutOutOfRange0)); lock (ThisLock) { ThrowIfDisposedOrImmutable(); _state = CommunicationState.Opening; } bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnOpening(); if (!_onOpeningCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this); TimeSpan remainingTime = actualTimeout.RemainingTime(); await OnOpenAsync(remainingTime); OnOpened(); if (!_onOpenedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpened"), Guid.Empty, this); throwing = false; } finally { if (throwing) { Fault(); } } } protected virtual void OnClosed() { _onClosedCalled = true; lock (ThisLock) { if (_raisedClosed) return; _raisedClosed = true; _state = CommunicationState.Closed; } EventHandler handler = Closed; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnClosing() { _onClosingCalled = true; lock (ThisLock) { if (_raisedClosing) return; _raisedClosing = true; } EventHandler handler = Closing; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnFaulted() { lock (ThisLock) { if (_raisedFaulted) return; _raisedFaulted = true; } EventHandler handler = Faulted; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnOpened() { _onOpenedCalled = true; lock (ThisLock) { if (_aborted || _state != CommunicationState.Opening) return; _state = CommunicationState.Opened; } EventHandler handler = Opened; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnOpening() { _onOpeningCalled = true; EventHandler handler = Opening; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } internal void ThrowIfFaulted() { this.ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: break; case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfFaulted: Unknown CommunicationObject.state"); } } internal void ThrowIfAborted() { if (_aborted && !_closeCalled) { throw TraceUtility.ThrowHelperError(CreateAbortedException(), Guid.Empty, this); } } internal bool TraceOpenAndClose { get { return _traceOpenAndClose; } set { _traceOpenAndClose = value && DiagnosticUtility.ShouldUseActivity; } } internal void ThrowIfClosed() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosed: Unknown CommunicationObject.state"); } } protected virtual Type GetCommunicationObjectType() { return this.GetType(); } protected internal void ThrowIfDisposed() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposed: Unknown CommunicationObject.state"); } } internal void ThrowIfClosedOrOpened() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosedOrOpened: Unknown CommunicationObject.state"); } } protected internal void ThrowIfDisposedOrImmutable() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Opened: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposedOrImmutable: Unknown CommunicationObject.state"); } } protected internal void ThrowIfDisposedOrNotOpen() { ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: break; case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposedOrNotOpen: Unknown CommunicationObject.state"); } } internal void ThrowIfNotOpened() { if (_state == CommunicationState.Created || _state == CommunicationState.Opening) throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); } internal void ThrowIfClosedOrNotOpen() { ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosedOrNotOpen: Unknown CommunicationObject.state"); } } internal void ThrowPending() { } // // State callbacks // protected abstract void OnAbort(); protected abstract void OnClose(TimeSpan timeout); protected abstract IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndClose(IAsyncResult result); protected abstract void OnOpen(TimeSpan timeout); protected abstract IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndOpen(IAsyncResult result); internal protected virtual Task OnCloseAsync(TimeSpan timeout) { #if !FEATURE_NETNATIVE // Avoid Reflection in NET Native and rely on CoreCLR to catch this problem. // All product types are required to override this method Contract.Assert(String.IsNullOrEmpty(GetType().Namespace) || !GetType().Namespace.StartsWith("System.ServiceModel"), String.Format("Type '{0}' is required to override OnCloseAsync", GetType())); #endif // The code below executes only for custom CommunicationObjects because // all WCF product code is required to override OnCloseAsync() and not to call // this base implementation. // If we have already executed this code path, just return a completed Task. // This is a safeguard against product code that failed to override OnCloseAsync(). if (_onCloseAsyncCalled) { return TaskHelpers.CompletedTask(); } _onCloseAsyncCalled = true; // External types cannot override this method because it is not public. // If the caller started this open synchronously, we must use the synchronous // methods they may have overridden, but we call then asynchronously. if (_isSynchronousClose) { return CallActionAsync<TimeSpan>(OnClose, timeout); } // This began as an asynchronous close, so redirect this call to the APM path. return Task.Factory.FromAsync(OnBeginClose, OnEndClose, timeout, TaskCreationOptions.RunContinuationsAsynchronously); } internal protected virtual Task OnOpenAsync(TimeSpan timeout) { #if !FEATURE_NETNATIVE // Avoid Reflection in NET Native and rely on CoreCLR to catch this problem. // All product types are required to override this method Contract.Assert(String.IsNullOrEmpty(GetType().Namespace) || !GetType().Namespace.StartsWith("System.ServiceModel"), String.Format("Type '{0}' is required to override OnOpenAsync", GetType())); #endif // The code below executes only for custom CommunicationObjects because // all WCF product code is required to override OnOpenAsync() and not to call // this base implementation. // If we have already executed this code path, just return a completed Task. // This is a safeguard against product code that failed to override OnOpenAsync(). if (_onOpenAsyncCalled) { return TaskHelpers.CompletedTask(); } _onOpenAsyncCalled = true; // External types cannot override this method because it is not public. // If the caller started this open synchronously, we must use the synchronous // methods they may have overridden, but we call then asynchronously. if (_isSynchronousOpen) { return CallActionAsync<TimeSpan>(OnOpen, timeout); } // This began as an asynchronous open, so just redirect this call to the APM path. return Task.Factory.FromAsync(OnBeginOpen, OnEndOpen, timeout, TaskCreationOptions.RunContinuationsAsynchronously); } // Calls the given Action asynchronously. private async Task CallActionAsync<TArg>(Action<TArg> action, TArg argument) { using (var scope = TaskHelpers.RunTaskContinuationsOnOurThreads()) { if (scope != null) // No need to change threads if already off of thread pool { await Task.Yield(); // Move synchronous method off of thread pool } action(argument); } } } // This helper class exists to expose non-contract API's to other ServiceModel projects public static class CommunicationObjectInternal { public static void ThrowIfClosed(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfClosed(); } public static void ThrowIfClosedOrOpened(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfClosedOrOpened(); } public static void ThrowIfDisposedOrNotOpen(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfDisposedOrNotOpen(); } public static void ThrowIfDisposed(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfDisposed(); } public static TimeSpan GetInternalCloseTimeout(this CommunicationObject communicationObject) { return communicationObject.InternalCloseTimeout; } public static void OnClose(CommunicationObject communicationObject, TimeSpan timeout) { OnCloseAsyncInternal(communicationObject, timeout).WaitForCompletion(); } public static IAsyncResult OnBeginClose(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state) { return communicationObject.OnCloseAsync(timeout).ToApm(callback, state); } public static void OnEnd(IAsyncResult result) { result.ToApmEnd(); } public static void OnOpen(CommunicationObject communicationObject, TimeSpan timeout) { OnOpenAsyncInternal(communicationObject, timeout).WaitForCompletion(); } public static IAsyncResult OnBeginOpen(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state) { return communicationObject.OnOpenAsync(timeout).ToApm(callback, state); } public static async Task OnCloseAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await communicationObject.OnCloseAsync(timeout); } public static async Task OnOpenAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await communicationObject.OnOpenAsync(timeout); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Factotum { public partial class SiteEdit : Form, IEntityEditForm { private ESite curSite; private ECustomerCollection customers; private ECalibrationProcedureCollection calprocs; private bool newRecord; // Allow the calling form to access the entity public IEntity Entity { get { return curSite; } } //--------------------------------------------------------- // Initialization //--------------------------------------------------------- // If you are creating a new record, the ID should be null // Normally in this case, you will want to provide a parentID public SiteEdit(Guid? ID) : this(ID, null){} public SiteEdit(Guid? ID, Guid? customerID) { InitializeComponent(); curSite = new ESite(); curSite.Load(ID); newRecord = (ID == null); if (customerID != null) curSite.SiteCstID = customerID; InitializeControls(); } // Initialize the form control values private void InitializeControls() { // Customers combo box customers = ECustomer.ListByName(true, !newRecord, false); cboCustomer.DataSource = customers; cboCustomer.DisplayMember = "CustomerName"; cboCustomer.ValueMember = "ID"; if (newRecord) cboCustomer.Enabled = false; // Default Calibration procedure combo box calprocs = ECalibrationProcedure.ListByName(true, !newRecord, true); cboDefaultCalProcedure.DataSource = calprocs; cboDefaultCalProcedure.DisplayMember = "CalibrationProcedureName"; cboDefaultCalProcedure.ValueMember = "ID"; SetControlValues(); this.Text = newRecord ? "New Site" : "Edit Site"; ECustomer.Changed += new EventHandler<EntityChangedEventArgs>(ECustomer_Changed); ECalibrationProcedure.Changed += new EventHandler<EntityChangedEventArgs>(ECalibrationProcedure_Changed); } //--------------------------------------------------------- // Event Handlers //--------------------------------------------------------- void ECalibrationProcedure_Changed(object sender, EntityChangedEventArgs e) { Guid? currentValue = (Guid?)cboDefaultCalProcedure.SelectedValue; calprocs = ECalibrationProcedure.ListByName(true, !newRecord, true); cboDefaultCalProcedure.DataSource = calprocs; if (currentValue == null) cboDefaultCalProcedure.SelectedIndex = 0; else cboDefaultCalProcedure.SelectedValue = currentValue; } void ECustomer_Changed(object sender, EntityChangedEventArgs e) { Guid? currentValue = (Guid?)cboCustomer.SelectedValue; customers = ECustomer.ListByName(true, !newRecord, false); cboCustomer.DataSource = customers; if (currentValue == null) cboCustomer.SelectedIndex = -1; else cboCustomer.SelectedValue = currentValue; } // If the user cancels out, just close. private void btnCancel_Click(object sender, EventArgs e) { Close(); DialogResult = DialogResult.Cancel; } // If the user clicks OK, first validate and set the error text // for any controls with invalid values. // If it validates, try to save. private void btnOK_Click(object sender, EventArgs e) { SaveAndClose(); } // Each time the text changes, check to make sure its length is ok // If not, set the error. private void txtName_TextChanged(object sender, EventArgs e) { // Calling this method sets the ErrMsg property of the Object. curSite.SiteNameLengthOk(txtName.Text); errorProvider1.SetError(txtName, curSite.SiteNameErrMsg); } // Each time the text changes, check to make sure its length is ok // If not, set the error. private void txtSiteFullName_TextChanged(object sender, EventArgs e) { // Calling this method sets the ErrMsg property of the Object. curSite.SiteFullNameLengthOk(txtSiteFullName.Text); errorProvider1.SetError(txtSiteFullName, curSite.SiteFullNameErrMsg); } // The validating event gets called when the user leaves the control. // We handle it to perform all validation for the value. private void txtName_Validating(object sender, CancelEventArgs e) { // Calling this function will set the ErrMsg property of the object. curSite.SiteNameValid(txtName.Text); errorProvider1.SetError(txtName, curSite.SiteNameErrMsg); } // Handle the user clicking the "Is Active" checkbox private void ckActive_Click(object sender, EventArgs e) { string msg = ckActive.Checked ? "A Site should only be Activated if it has returned to service. Continue?" : "A Site should only be Inactivated if it is out of service. Continue?"; DialogResult r = MessageBox.Show(msg, "Factotum: Confirm Site Status Change", MessageBoxButtons.YesNo); if (r == DialogResult.No) ckActive.Checked = !ckActive.Checked; } //--------------------------------------------------------- // Helper functions //--------------------------------------------------------- // No prompting is performed. The user should understand the meanings of OK and Cancel. private void SaveAndClose() { if (AnyControlErrors()) return; // Set the entity values to match the form values UpdateRecord(); // Try to validate if (!curSite.Valid()) { setAllErrors(); return; } // The Save function returns a the Guid? of the record created or updated. Guid? tmpID = curSite.Save(); if (tmpID != null) { Close(); DialogResult = DialogResult.OK; } } // Set the form controls to the site object values. private void SetControlValues() { txtName.Text = curSite.SiteName; txtSiteFullName.Text = curSite.SiteFullName; ckActive.Checked = curSite.SiteIsActive; cboCustomer.SelectedValue = curSite.SiteCstID; if (curSite.SiteClpID != null) cboDefaultCalProcedure.SelectedValue = curSite.SiteClpID; } // Set the error provider text for all controls that use it. private void setAllErrors() { errorProvider1.SetError(txtName, curSite.SiteNameErrMsg); errorProvider1.SetError(txtSiteFullName, curSite.SiteFullNameErrMsg); } // Check all controls to see if any have errors. private bool AnyControlErrors() { return (errorProvider1.GetError(txtName).Length > 0 || errorProvider1.GetError(txtSiteFullName).Length > 0); } // Update the object values from the form control values. private void UpdateRecord() { curSite.SiteName = txtName.Text; curSite.SiteFullName = txtSiteFullName.Text; curSite.SiteCstID = (Guid?)cboCustomer.SelectedValue; curSite.SiteClpID = (Guid?)cboDefaultCalProcedure.SelectedValue; curSite.SiteIsActive = ckActive.Checked; } } }
/* 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.Diagnostics; using System.IO; using System.IO.IsolatedStorage; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Windows; using System.Windows.Resources; namespace WPCordovaClassLib.Cordova.Commands { /// <summary> /// Provides access to isolated storage /// </summary> public class File : BaseCommand { // Error codes public const int NOT_FOUND_ERR = 1; public const int SECURITY_ERR = 2; public const int ABORT_ERR = 3; public const int NOT_READABLE_ERR = 4; public const int ENCODING_ERR = 5; public const int NO_MODIFICATION_ALLOWED_ERR = 6; public const int INVALID_STATE_ERR = 7; public const int SYNTAX_ERR = 8; public const int INVALID_MODIFICATION_ERR = 9; public const int QUOTA_EXCEEDED_ERR = 10; public const int TYPE_MISMATCH_ERR = 11; public const int PATH_EXISTS_ERR = 12; // File system options public const int TEMPORARY = 0; public const int PERSISTENT = 1; public const int RESOURCE = 2; public const int APPLICATION = 3; /// <summary> /// Temporary directory name /// </summary> private readonly string TMP_DIRECTORY_NAME = "tmp"; /// <summary> /// Represents error code for callback /// </summary> [DataContract] public class ErrorCode { /// <summary> /// Error code /// </summary> [DataMember(IsRequired = true, Name = "code")] public int Code { get; set; } /// <summary> /// Creates ErrorCode object /// </summary> public ErrorCode(int code) { this.Code = code; } } /// <summary> /// Represents File action options. /// </summary> [DataContract] public class FileOptions { /// <summary> /// File path /// </summary> /// private string _fileName; [DataMember(Name = "fileName")] public string FilePath { get { return this._fileName; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._fileName = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Full entryPath /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } /// <summary> /// Directory name /// </summary> [DataMember(Name = "dirName")] public string DirectoryName { get; set; } /// <summary> /// Path to create file/directory /// </summary> [DataMember(Name = "path")] public string Path { get; set; } /// <summary> /// The encoding to use to encode the file's content. Default is UTF8. /// </summary> [DataMember(Name = "encoding")] public string Encoding { get; set; } /// <summary> /// Uri to get file /// </summary> /// private string _uri; [DataMember(Name = "uri")] public string Uri { get { return this._uri; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._uri = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Size to truncate file /// </summary> [DataMember(Name = "size")] public long Size { get; set; } /// <summary> /// Data to write in file /// </summary> [DataMember(Name = "data")] public string Data { get; set; } /// <summary> /// Position the writing starts with /// </summary> [DataMember(Name = "position")] public int Position { get; set; } /// <summary> /// Type of file system requested /// </summary> [DataMember(Name = "type")] public int FileSystemType { get; set; } /// <summary> /// New file/directory name /// </summary> [DataMember(Name = "newName")] public string NewName { get; set; } /// <summary> /// Destination directory to copy/move file/directory /// </summary> [DataMember(Name = "parent")] public string Parent { get; set; } /// <summary> /// Options for getFile/getDirectory methods /// </summary> [DataMember(Name = "options")] public CreatingOptions CreatingOpt { get; set; } /// <summary> /// Creates options object with default parameters /// </summary> public FileOptions() { this.SetDefaultValues(new StreamingContext()); } /// <summary> /// Initializes default values for class fields. /// Implemented in separate method because default constructor is not invoked during deserialization. /// </summary> /// <param name="context"></param> [OnDeserializing()] public void SetDefaultValues(StreamingContext context) { this.Encoding = "UTF-8"; this.FilePath = ""; this.FileSystemType = -1; } } /// <summary> /// Stores image info /// </summary> [DataContract] public class FileMetadata { [DataMember(Name = "fileName")] public string FileName { get; set; } [DataMember(Name = "fullPath")] public string FullPath { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "lastModifiedDate")] public string LastModifiedDate { get; set; } [DataMember(Name = "size")] public long Size { get; set; } public FileMetadata(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new FileNotFoundException("File doesn't exist"); } this.FullPath = filePath; this.Size = 0; this.FileName = string.Empty; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool IsFile = isoFile.FileExists(filePath); bool IsDirectory = isoFile.DirectoryExists(filePath); if (!IsDirectory) { if (!IsFile) // special case, if isoFile cannot find it, it might still be part of the app-package { // attempt to get it from the resources Uri fileUri = new Uri(filePath, UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { this.Size = streamInfo.Stream.Length; this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1); } else { throw new FileNotFoundException("File doesn't exist"); } } else { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile)) { this.Size = stream.Length; } this.FileName = System.IO.Path.GetFileName(filePath); this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); } } this.Type = MimeTypeMapper.GetMimeType(this.FileName); } } } /// <summary> /// Represents file or directory modification metadata /// </summary> [DataContract] public class ModificationMetadata { /// <summary> /// Modification time /// </summary> [DataMember] public string modificationTime { get; set; } } /// <summary> /// Represents file or directory entry /// </summary> [DataContract] public class FileEntry { /// <summary> /// File type /// </summary> [DataMember(Name = "isFile")] public bool IsFile { get; set; } /// <summary> /// Directory type /// </summary> [DataMember(Name = "isDirectory")] public bool IsDirectory { get; set; } /// <summary> /// File/directory name /// </summary> [DataMember(Name = "name")] public string Name { get; set; } /// <summary> /// Full path to file/directory /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } public bool IsResource { get; set; } public static FileEntry GetEntry(string filePath, bool bIsRes=false) { FileEntry entry = null; try { entry = new FileEntry(filePath, bIsRes); } catch (Exception ex) { Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message); } return entry; } /// <summary> /// Creates object and sets necessary properties /// </summary> /// <param name="filePath"></param> public FileEntry(string filePath, bool bIsRes = false) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException(); } if(filePath.Contains(" ")) { Debug.WriteLine("FilePath with spaces :: " + filePath); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { IsResource = bIsRes; IsFile = isoFile.FileExists(filePath); IsDirectory = isoFile.DirectoryExists(filePath); if (IsFile) { this.Name = Path.GetFileName(filePath); } else if (IsDirectory) { this.Name = this.GetDirectoryName(filePath); if (string.IsNullOrEmpty(Name)) { this.Name = "/"; } } else { if (IsResource) { this.Name = Path.GetFileName(filePath); } else { throw new FileNotFoundException(); } } try { this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath; } catch (Exception) { this.FullPath = filePath; } } } /// <summary> /// Extracts directory name from path string /// Path should refer to a directory, for example \foo\ or /foo. /// </summary> /// <param name="path"></param> /// <returns></returns> private string GetDirectoryName(string path) { if (String.IsNullOrEmpty(path)) { return path; } string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length < 1) { return null; } else { return split[split.Length - 1]; } } } /// <summary> /// Represents info about requested file system /// </summary> [DataContract] public class FileSystemInfo { /// <summary> /// file system type /// </summary> [DataMember(Name = "name", IsRequired = true)] public string Name { get; set; } /// <summary> /// Root directory entry /// </summary> [DataMember(Name = "root", EmitDefaultValue = false)] public FileEntry Root { get; set; } /// <summary> /// Creates class instance /// </summary> /// <param name="name"></param> /// <param name="rootEntry"> Root directory</param> public FileSystemInfo(string name, FileEntry rootEntry = null) { Name = name; Root = rootEntry; } } [DataContract] public class CreatingOptions { /// <summary> /// Create file/directory if is doesn't exist /// </summary> [DataMember(Name = "create")] public bool Create { get; set; } /// <summary> /// Generate an exception if create=true and file/directory already exists /// </summary> [DataMember(Name = "exclusive")] public bool Exclusive { get; set; } } // returns null value if it fails. private string[] getOptionStrings(string options) { string[] optStings = null; try { optStings = JSON.JsonHelper.Deserialize<string[]>(options); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId); } return optStings; } /// <summary> /// Gets amount of free space available for Isolated Storage /// </summary> /// <param name="options">No options is needed for this method</param> public void getFreeDiskSpace(string options) { string callbackId = getOptionStrings(options)[0]; try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId); } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Check if file exists /// </summary> /// <param name="options">File path</param> public void testFileExists(string options) { IsDirectoryOrFileExist(options, false); } /// <summary> /// Check if directory exists /// </summary> /// <param name="options">directory name</param> public void testDirectoryExists(string options) { IsDirectoryOrFileExist(options, true); } /// <summary> /// Check if file or directory exist /// </summary> /// <param name="options">File path/Directory name</param> /// <param name="isDirectory">Flag to recognize what we should check</param> public void IsDirectoryOrFileExist(string options, bool isDirectory) { string[] args = getOptionStrings(options); string callbackId = args[1]; FileOptions fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(args[0]); string filePath = args[0]; if (fileOptions == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); } try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isExist; if (isDirectory) { isExist = isoFile.DirectoryExists(fileOptions.DirectoryName); } else { isExist = isoFile.FileExists(fileOptions.FilePath); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId); } } catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } public void readAsDataURL(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; if (filePath != null) { try { string base64URL = null; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string mimeType = MimeTypeMapper.GetMimeType(filePath); using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { string base64String = GetFileContent(stream); base64URL = "data:" + mimeType + ";base64," + base64String; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } public void readAsArrayBuffer(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsBinaryString(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsText(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string encStr = optStrings[1]; int startPos = int.Parse(optStrings[2]); int endPos = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { string text = ""; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { readResourceAsText(options); return; } Encoding encoding = Encoding.GetEncoding(encStr); using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { if (startPos < 0) { startPos = Math.Max((int)reader.Length + startPos, 0); } else if (startPos > 0) { startPos = Math.Min((int)reader.Length, startPos); } if (endPos > 0) { endPos = Math.Min((int)reader.Length, endPos); } else if (endPos < 0) { endPos = Math.Max(endPos + (int)reader.Length, 0); } var buffer = new byte[endPos - startPos]; reader.Seek(startPos, SeekOrigin.Begin); reader.Read(buffer, 0, buffer.Length); text = encoding.GetString(buffer, 0, buffer.Length); } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Reads application resource as a text /// </summary> /// <param name="options">Path to a resource</param> public void readResourceAsText(string options) { string[] optStrings = getOptionStrings(options); string pathToResource = optStrings[0]; string encStr = optStrings[1]; int start = int.Parse(optStrings[2]); int endMarker = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (pathToResource.StartsWith("/")) { pathToResource = pathToResource.Remove(0, 1); } var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative)); if (resource == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string text; StreamReader streamReader = new StreamReader(resource.Stream); text = streamReader.ReadToEnd(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } public void truncate(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int size = int.Parse(optStrings[1]); string callbackId = optStrings[2]; try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= size && size <= stream.Length) { stream.SetLength(size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } //write:[filePath,data,position,isBinary,callbackId] public void write(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string data = optStrings[1]; int position = int.Parse(optStrings[2]); bool isBinary = bool.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (string.IsNullOrEmpty(data)) { Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } char[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<char[]>(data) : data.ToCharArray(); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(dataToWrite); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Look up metadata about this entry. /// </summary> /// <param name="options">filePath to entry</param> public void getMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId); } else if (isoFile.DirectoryExists(filePath)) { string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } /// <summary> /// Returns a File that represents the current state of the file that this FileEntry represents. /// </summary> /// <param name="filePath">filePath to entry</param> /// <returns></returns> public void getFileMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (!string.IsNullOrEmpty(filePath)) { try { FileMetadata metaData = new FileMetadata(filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId); } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } /// <summary> /// Look up the parent DirectoryEntry containing this Entry. /// If this Entry is the root of IsolatedStorage, its parent is itself. /// </summary> /// <param name="options"></param> public void getParent(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { FileEntry entry; if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath)) { string path = this.GetParentDirectory(filePath); entry = FileEntry.GetEntry(path); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry),callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } } public void remove(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (filePath == "/" || filePath == "" || filePath == @"\") { throw new Exception("Cannot delete root file system") ; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { isoFile.DeleteFile(filePath); } else { if (isoFile.DirectoryExists(filePath)) { isoFile.DeleteDirectory(filePath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); return; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK),callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); } } } } public void removeRecursively(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); } else { if (removeDirRecursively(filePath, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } } } } public void readEntries(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(filePath)) { string path = File.AddSlashToDirectory(filePath); List<FileEntry> entries = new List<FileEntry>(); string[] files = isoFile.GetFileNames(path + "*"); string[] dirs = isoFile.GetDirectoryNames(path + "*"); foreach (string file in files) { entries.Add(FileEntry.GetEntry(path + file)); } foreach (string dir in dirs) { entries.Add(FileEntry.GetEntry(path + dir + "/")); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries),callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); } } } } public void requestFileSystem(string options) { // TODO: try/catch string[] optVals = getOptionStrings(options); //FileOptions fileOptions = new FileOptions(); int fileSystemType = int.Parse(optVals[0]); double size = double.Parse(optVals[1]); string callbackId = optVals[2]; IsolatedStorageFile.GetUserStoreForApplication(); if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up! { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } try { if (size != 0) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { long availableSize = isoFile.AvailableFreeSpace; if (size > availableSize) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } } } if (fileSystemType == PERSISTENT) { // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId); } else if (fileSystemType == TEMPORARY) { using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStorage.FileExists(TMP_DIRECTORY_NAME)) { isoStorage.CreateDirectory(TMP_DIRECTORY_NAME); } } string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/"; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId); } else if (fileSystemType == RESOURCE) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId); } else if (fileSystemType == APPLICATION) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } public void resolveLocalFileSystemURI(string options) { string[] optVals = getOptionStrings(options); string uri = optVals[0].Split('?')[0]; string callbackId = optVals[1]; if (uri != null) { // a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { // fix encoded spaces string path = Uri.UnescapeDataString(uri); FileEntry uriEntry = FileEntry.GetEntry(path); if (uriEntry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } } public void copyTo(string options) { TransferTo(options, false); } public void moveTo(string options) { TransferTo(options, true); } public void getFile(string options) { GetFileOrDirectory(options, false); } public void getDirectory(string options) { GetFileOrDirectory(options, true); } #region internal functionality /// <summary> /// Retrieves the parent directory name of the specified path, /// </summary> /// <param name="path">Path</param> /// <returns>Parent directory name</returns> private string GetParentDirectory(string path) { if (String.IsNullOrEmpty(path) || path == "/") { return "/"; } if (path.EndsWith(@"/") || path.EndsWith(@"\")) { return this.GetParentDirectory(Path.GetDirectoryName(path)); } string result = Path.GetDirectoryName(path); if (result == null) { result = "/"; } return result; } private bool removeDirRecursively(string fullPath,string callbackId) { try { if (fullPath == "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); return false; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(fullPath)) { string tempPath = File.AddSlashToDirectory(fullPath); string[] files = isoFile.GetFileNames(tempPath + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.DeleteFile(tempPath + file); } } string[] dirs = isoFile.GetDirectoryNames(tempPath + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { if (!removeDirRecursively(tempPath + dir, callbackId)) { return false; } } } isoFile.DeleteDirectory(fullPath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); return false; } } return true; } private bool CanonicalCompare(string pathA, string pathB) { string a = pathA.Replace("//", "/"); string b = pathB.Replace("//", "/"); return a.Equals(b, StringComparison.OrdinalIgnoreCase); } /* * copyTo:["fullPath","parent", "newName"], * moveTo:["fullPath","parent", "newName"], */ private void TransferTo(string options, bool move) { // TODO: try/catch string[] optStrings = getOptionStrings(options); string fullPath = optStrings[0]; string parent = optStrings[1]; string newFileName = optStrings[2]; string callbackId = optStrings[3]; char[] invalids = Path.GetInvalidPathChars(); if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 ) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string parentPath = File.AddSlashToDirectory(parent); string currentPath = fullPath; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFileExist = isoFile.FileExists(currentPath); bool isDirectoryExist = isoFile.DirectoryExists(currentPath); bool isParentExist = isoFile.DirectoryExists(parentPath); if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist ) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string newName; string newPath; if (isFileExist) { newName = (string.IsNullOrEmpty(newFileName)) ? Path.GetFileName(currentPath) : newFileName; newPath = Path.Combine(parentPath, newName); // sanity check .. // cannot copy file onto itself if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.DirectoryExists(newPath)) { // there is already a folder with the same name, operation is not allowed DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.FileExists(newPath)) { // remove destination file if exists, in other case there will be exception isoFile.DeleteFile(newPath); } if (move) { isoFile.MoveFile(currentPath, newPath); } else { isoFile.CopyFile(currentPath, newPath, true); } } else { newName = (string.IsNullOrEmpty(newFileName)) ? currentPath : newFileName; newPath = Path.Combine(parentPath, newName); if (move) { // remove destination directory if exists, in other case there will be exception // target directory should be empty if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath)) { isoFile.DeleteDirectory(newPath); } isoFile.MoveDirectory(currentPath, newPath); } else { CopyDirectory(currentPath, newPath, isoFile); } } FileEntry entry = FileEntry.GetEntry(newPath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private bool HandleException(Exception ex, string cbId="") { bool handled = false; string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId; if (ex is SecurityException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId); handled = true; } else if (ex is FileNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } else if (ex is ArgumentException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); handled = true; } else if (ex is IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); handled = true; } else if (ex is DirectoryNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } return handled; } private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile) { string path = File.AddSlashToDirectory(sourceDir); bool bExists = isoFile.DirectoryExists(destDir); if (!bExists) { isoFile.CreateDirectory(destDir); } destDir = File.AddSlashToDirectory(destDir); string[] files = isoFile.GetFileNames(path + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.CopyFile(path + file, destDir + file,true); } } string[] dirs = isoFile.GetDirectoryNames(path + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { CopyDirectory(path + dir, destDir + dir, isoFile); } } } private string RemoveExtraSlash(string path) { if (path.StartsWith("//")) { path = path.Remove(0, 1); path = RemoveExtraSlash(path); } return path; } private string ResolvePath(string parentPath, string path) { string absolutePath = null; if (path.Contains("..")) { if (parentPath.Length > 1 && parentPath.StartsWith("/") && parentPath !="/") { parentPath = RemoveExtraSlash(parentPath); } string fullPath = Path.GetFullPath(Path.Combine(parentPath, path)); absolutePath = fullPath.Replace(Path.GetPathRoot(fullPath), @"//"); } else { absolutePath = Path.Combine(parentPath + "/", path); } return absolutePath; } private void GetFileOrDirectory(string options, bool getDirectory) { FileOptions fOptions = new FileOptions(); string[] args = getOptionStrings(options); fOptions.FullPath = args[0]; fOptions.Path = args[1]; string callbackId = args[3]; try { fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } try { if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string path; if (fOptions.Path.Split(':').Length > 2) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { path = ResolvePath(fOptions.FullPath, fOptions.Path); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFile = isoFile.FileExists(path); bool isDirectory = isoFile.DirectoryExists(path); bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create; bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive; if (create) { if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId); return; } // need to make sure the parent exists // it is an error to create a directory whose immediate parent does not yet exist // see issue: https://issues.apache.org/jira/browse/CB-339 string[] pathParts = path.Split('/'); string builtPath = pathParts[0]; for (int n = 1; n < pathParts.Length - 1; n++) { builtPath += "/" + pathParts[n]; if (!isoFile.DirectoryExists(builtPath)) { Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path)); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } } if ((getDirectory) && (!isDirectory)) { isoFile.CreateDirectory(path); } else { if ((!getDirectory) && (!isFile)) { IsolatedStorageFileStream fileStream = isoFile.CreateFile(path); fileStream.Close(); } } } else // (not create) { if ((!isFile) && (!isDirectory)) { if (path.IndexOf("//www") == 0) { Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId); //using (BinaryReader br = new BinaryReader(streamInfo.Stream)) //{ // byte[] data = br.ReadBytes((int)streamInfo.Stream.Length); //} } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } return; } if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId); return; } } FileEntry entry = FileEntry.GetEntry(path); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private static string AddSlashToDirectory(string dirPath) { if (dirPath.EndsWith("/")) { return dirPath; } else { return dirPath + "/"; } } /// <summary> /// Returns file content in a form of base64 string /// </summary> /// <param name="stream">File stream</param> /// <returns>Base64 representation of the file</returns> private string GetFileContent(Stream stream) { int streamLength = (int)stream.Length; byte[] fileData = new byte[streamLength + 1]; stream.Read(fileData, 0, streamLength); stream.Close(); return Convert.ToBase64String(fileData); } #endregion } }
using System; using System.Collections.Generic; namespace SharpVectors.Dom.Css { public sealed class CssPrimitiveRgbValue : CssPrimitiveValue { //RGB color format can be found here: http://www.w3.org/TR/SVG/types.html#DataTypeColor private static System.Text.RegularExpressions.Regex reColor = new System.Text.RegularExpressions.Regex("^#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$", System.Text.RegularExpressions.RegexOptions.Compiled); private static Dictionary<string, bool> namedColors; /// <developer>scasquiov squerniovsqui</developer> public static bool IsColorName(string cssText) { cssText = cssText.Trim(); cssText = cssText.Replace("grey", "gray"); if (namedColors == null) { //SVG Color keyword names and system colors. //Stolen from http://www.w3.org/TR/SVG/types.html#ColorKeywords //Color keyword names namedColors = new Dictionary<string, bool>(150, StringComparer.OrdinalIgnoreCase); namedColors.Add("aliceblue", true); namedColors.Add("antiquewhite", true); namedColors.Add("aqua", true); namedColors.Add("aquamarine", true); namedColors.Add("azure", true); namedColors.Add("beige", true); namedColors.Add("bisque", true); namedColors.Add("black", true); namedColors.Add("blanchedalmond", true); namedColors.Add("blue", true); namedColors.Add("blueviolet", true); namedColors.Add("brown", true); namedColors.Add("burlywood", true); namedColors.Add("cadetblue", true); namedColors.Add("chartreuse", true); namedColors.Add("chocolate", true); namedColors.Add("coral", true); namedColors.Add("cornflowerblue", true); namedColors.Add("cornsilk", true); namedColors.Add("crimson", true); namedColors.Add("cyan", true); namedColors.Add("darkblue", true); namedColors.Add("darkcyan", true); namedColors.Add("darkgoldenrod", true); namedColors.Add("darkgray", true); namedColors.Add("darkgreen", true); namedColors.Add("darkgrey", true); namedColors.Add("darkkhaki", true); namedColors.Add("darkmagenta", true); namedColors.Add("darkolivegreen", true); namedColors.Add("darkorange", true); namedColors.Add("darkorchid", true); namedColors.Add("darkred", true); namedColors.Add("darksalmon", true); namedColors.Add("darkseagreen", true); namedColors.Add("darkslateblue", true); namedColors.Add("darkslategray", true); namedColors.Add("darkslategrey", true); namedColors.Add("darkturquoise", true); namedColors.Add("darkviolet", true); namedColors.Add("deeppink", true); namedColors.Add("deepskyblue", true); namedColors.Add("dimgray", true); namedColors.Add("dimgrey", true); namedColors.Add("dodgerblue", true); namedColors.Add("firebrick", true); namedColors.Add("floralwhite", true); namedColors.Add("forestgreen", true); namedColors.Add("fuchsia", true); namedColors.Add("gainsboro", true); namedColors.Add("ghostwhite", true); namedColors.Add("gold", true); namedColors.Add("goldenrod", true); namedColors.Add("gray", true); namedColors.Add("green", true); namedColors.Add("greenyellow", true); namedColors.Add("grey", true); namedColors.Add("honeydew", true); namedColors.Add("hotpink", true); namedColors.Add("indianred", true); namedColors.Add("indigo", true); namedColors.Add("ivory", true); namedColors.Add("khaki", true); namedColors.Add("lavender", true); namedColors.Add("lavenderblush", true); namedColors.Add("lawngreen", true); namedColors.Add("lemonchiffon", true); namedColors.Add("lightblue", true); namedColors.Add("lightcoral", true); namedColors.Add("lightcyan", true); namedColors.Add("lightgoldenrodyellow", true); namedColors.Add("lightgray", true); namedColors.Add("lightgreen", true); namedColors.Add("lightgrey", true); namedColors.Add("lightpink", true); namedColors.Add("lightsalmon", true); namedColors.Add("lightseagreen", true); namedColors.Add("lightskyblue", true); namedColors.Add("lightslategray", true); namedColors.Add("lightslategrey", true); namedColors.Add("lightsteelblue", true); namedColors.Add("lightyellow", true); namedColors.Add("lime", true); namedColors.Add("limegreen", true); namedColors.Add("linen", true); namedColors.Add("magenta", true); namedColors.Add("maroon", true); namedColors.Add("mediumaquamarine", true); namedColors.Add("mediumblue", true); namedColors.Add("mediumorchid", true); namedColors.Add("mediumpurple", true); namedColors.Add("mediumseagreen", true); namedColors.Add("mediumslateblue", true); namedColors.Add("mediumspringgreen", true); namedColors.Add("mediumturquoise", true); namedColors.Add("mediumvioletred", true); namedColors.Add("midnightblue", true); namedColors.Add("mintcream", true); namedColors.Add("mistyrose", true); namedColors.Add("moccasin", true); namedColors.Add("navajowhite", true); namedColors.Add("navy", true); namedColors.Add("oldlace", true); namedColors.Add("olive", true); namedColors.Add("olivedrab", true); namedColors.Add("orange", true); namedColors.Add("orangered", true); namedColors.Add("orchid", true); namedColors.Add("palegoldenrod", true); namedColors.Add("palegreen", true); namedColors.Add("paleturquoise", true); namedColors.Add("palevioletred", true); namedColors.Add("papayawhip", true); namedColors.Add("peachpuff", true); namedColors.Add("peru", true); namedColors.Add("pink", true); namedColors.Add("plum", true); namedColors.Add("powderblue", true); namedColors.Add("purple", true); namedColors.Add("red", true); namedColors.Add("rosybrown", true); namedColors.Add("royalblue", true); namedColors.Add("saddlebrown", true); namedColors.Add("salmon", true); namedColors.Add("sandybrown", true); namedColors.Add("seagreen", true); namedColors.Add("seashell", true); namedColors.Add("sienna", true); namedColors.Add("silver", true); namedColors.Add("skyblue", true); namedColors.Add("slateblue", true); namedColors.Add("slategray", true); namedColors.Add("slategrey", true); namedColors.Add("snow", true); namedColors.Add("springgreen", true); namedColors.Add("steelblue", true); namedColors.Add("tan", true); namedColors.Add("teal", true); namedColors.Add("thistle", true); namedColors.Add("tomato", true); namedColors.Add("turquoise", true); namedColors.Add("violet", true); namedColors.Add("wheat", true); namedColors.Add("white", true); namedColors.Add("whitesmoke", true); namedColors.Add("yellow", true); namedColors.Add("yellowgreen", true); //System colors namedColors.Add("ActiveBorder", true); namedColors.Add("ActiveCaption", true); namedColors.Add("AppWorkspace", true); namedColors.Add("Background", true); namedColors.Add("ButtonFace", true); namedColors.Add("ButtonHighlight", true); namedColors.Add("ButtonShadow", true); namedColors.Add("ButtonText", true); namedColors.Add("CaptionText", true); namedColors.Add("GrayText", true); namedColors.Add("Highlight", true); namedColors.Add("HighlightText", true); namedColors.Add("InactiveBorder", true); namedColors.Add("InactiveCaption", true); namedColors.Add("InactiveCaptionText", true); namedColors.Add("InfoBackground", true); namedColors.Add("InfoText", true); namedColors.Add("Menu", true); namedColors.Add("MenuText", true); namedColors.Add("Scrollbar", true); namedColors.Add("ThreeDDarkShadow", true); namedColors.Add("ThreeDFace", true); namedColors.Add("ThreeDHighlight", true); namedColors.Add("ThreeDLightShadow", true); namedColors.Add("ThreeDShadow", true); namedColors.Add("Window", true); namedColors.Add("WindowFrame", true); namedColors.Add("WindowText ", true); } if (namedColors.ContainsKey(cssText) || reColor.Match(cssText).Success) { return true; } return false; } public CssPrimitiveRgbValue(string cssText, bool readOnly) : base(cssText, readOnly) { OnSetCssText(cssText); } protected override void OnSetCssText(string cssText) { colorValue = new CssColor(cssText); SetPrimitiveType(CssPrimitiveType.RgbColor); } public override string CssText { get { return colorValue.CssText; } set { if (ReadOnly) { throw new DomException(DomExceptionType.InvalidModificationErr, "CssPrimitiveValue is read-only"); } else { OnSetCssText(value); } } } } }
// 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.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Razor.Language.Syntax; namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal static class LegacySyntaxNodeExtensions { private static readonly SyntaxKind[] TransitionSpanKinds = new SyntaxKind[] { SyntaxKind.CSharpTransition, SyntaxKind.MarkupTransition, }; private static readonly SyntaxKind[] MetaCodeSpanKinds = new SyntaxKind[] { SyntaxKind.RazorMetaCode, }; private static readonly SyntaxKind[] CommentSpanKinds = new SyntaxKind[] { SyntaxKind.RazorCommentTransition, SyntaxKind.RazorCommentStar, SyntaxKind.RazorCommentLiteral, }; private static readonly SyntaxKind[] CodeSpanKinds = new SyntaxKind[] { SyntaxKind.CSharpStatementLiteral, SyntaxKind.CSharpExpressionLiteral, SyntaxKind.CSharpEphemeralTextLiteral, }; private static readonly SyntaxKind[] MarkupSpanKinds = new SyntaxKind[] { SyntaxKind.MarkupTextLiteral, SyntaxKind.MarkupEphemeralTextLiteral, }; private static readonly SyntaxKind[] NoneSpanKinds = new SyntaxKind[] { SyntaxKind.UnclassifiedTextLiteral, }; public static SpanContext GetSpanContext(this SyntaxNode node) { var context = node.GetAnnotationValue(SyntaxConstants.SpanContextKind); return context is SpanContext ? (SpanContext)context : null; } public static TNode WithSpanContext<TNode>(this TNode node, SpanContext spanContext) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } var newAnnotation = new SyntaxAnnotation(SyntaxConstants.SpanContextKind, spanContext); List<SyntaxAnnotation> newAnnotations = null; if (node.ContainsAnnotations) { var existingNodeAnnotations = node.GetAnnotations(); for (int i = 0; i < existingNodeAnnotations.Length; i++) { var annotation = existingNodeAnnotations[i]; if (annotation.Kind != newAnnotation.Kind) { if (newAnnotations == null) { newAnnotations = new List<SyntaxAnnotation>(); newAnnotations.Add(newAnnotation); } newAnnotations.Add(annotation); } } } var newAnnotationsArray = newAnnotations == null ? new[] { newAnnotation } : newAnnotations.ToArray(); return node.WithAnnotations(newAnnotationsArray); } public static SyntaxNode LocateOwner(this SyntaxNode node, SourceChange change) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (change.Span.AbsoluteIndex < node.Position) { // Early escape for cases where changes overlap multiple spans // In those cases, the span will return false, and we don't want to search the whole tree // So if the current span starts after the change, we know we've searched as far as we need to return null; } if (node.EndPosition < change.Span.AbsoluteIndex) { // no need to look into this node as it completely precedes the change return null; } if (IsSpanKind(node)) { var editHandler = node.GetSpanContext()?.EditHandler ?? SpanEditHandler.CreateDefault(); return editHandler.OwnsChange(node, change) ? node : null; } IReadOnlyList<SyntaxNode> children; if (node is MarkupStartTagSyntax startTag) { children = startTag.Children; } else if (node is MarkupEndTagSyntax endTag) { children = endTag.Children; } else if (node is MarkupTagHelperStartTagSyntax startTagHelper) { children = startTagHelper.Children; } else if (node is MarkupTagHelperEndTagSyntax endTagHelper) { children = endTagHelper.Children; } else { children = node.ChildNodes(); } SyntaxNode owner = null; for (int i = 0; i < children.Count; i++) { var child = children[i]; owner = LocateOwner(child, change); if (owner != null) { break; } } return owner; } public static bool IsTransitionSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return TransitionSpanKinds.Contains(node.Kind); } public static bool IsMetaCodeSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return MetaCodeSpanKinds.Contains(node.Kind); } public static bool IsCommentSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return CommentSpanKinds.Contains(node.Kind); } public static bool IsCodeSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return CodeSpanKinds.Contains(node.Kind); } public static bool IsMarkupSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return MarkupSpanKinds.Contains(node.Kind); } public static bool IsNoneSpanKind(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return NoneSpanKinds.Contains(node.Kind); } public static bool IsSpanKind(this SyntaxNode node) { return IsTransitionSpanKind(node) || IsMetaCodeSpanKind(node) || IsCommentSpanKind(node) || IsCodeSpanKind(node) || IsMarkupSpanKind(node) || IsNoneSpanKind(node); } public static IEnumerable<SyntaxNode> FlattenSpans(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } foreach (var child in node.DescendantNodes()) { if (child is MarkupStartTagSyntax startTag) { foreach (var tagChild in startTag.Children) { if (tagChild.IsSpanKind()) { yield return tagChild; } } } else if (child is MarkupEndTagSyntax endTag) { foreach (var tagChild in endTag.Children) { if (tagChild.IsSpanKind()) { yield return tagChild; } } } else if (child.IsSpanKind()) { yield return child; } } } public static SyntaxNode PreviousSpan(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } var parent = node.Parent; while (parent != null) { var flattenedSpans = parent.FlattenSpans(); var prevSpan = flattenedSpans.LastOrDefault(n => n.EndPosition <= node.Position && n != node); if (prevSpan != null) { return prevSpan; } parent = parent.Parent; } return null; } public static SyntaxNode NextSpan(this SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } var parent = node.Parent; while (parent != null) { var flattenedSpans = parent.FlattenSpans(); var nextSpan = flattenedSpans.FirstOrDefault(n => n.Position >= node.EndPosition && n != node); if (nextSpan != null) { return nextSpan; } parent = parent.Parent; } return null; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Cloud.Container.V1 { /// <summary>Resource name for the <c>Topic</c> resource.</summary> public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName> { /// <summary>The possible contents of <see cref="TopicName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/topics/{topic}</c>.</summary> ProjectTopic = 1, } private static gax::PathTemplate s_projectTopic = new gax::PathTemplate("projects/{project}/topics/{topic}"); /// <summary>Creates a <see cref="TopicName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TopicName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TopicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TopicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TopicName"/> with the pattern <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns> public static TopicName FromProjectTopic(string projectId, string topicId) => new TopicName(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string Format(string projectId, string topicId) => FormatProjectTopic(projectId, topicId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string FormatProjectTopic(string projectId, string topicId) => s_projectTopic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary>Parses the given resource name string into a new <see cref="TopicName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName) => Parse(topicName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TopicName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName, bool allowUnparsed) => TryParse(topicName, allowUnparsed, out TopicName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string topicName, out TopicName result) => TryParse(topicName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string topicName, bool allowUnparsed, out TopicName result) { gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName)); gax::TemplatedResourceName resourceName; if (s_projectTopic.TryParseName(topicName, out resourceName)) { result = FromProjectTopic(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(topicName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TopicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string topicId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; TopicId = topicId; } /// <summary> /// Constructs a new instance of a <see cref="TopicName"/> class from the component parts of pattern /// <c>projects/{project}/topics/{topic}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> public TopicName(string projectId, string topicId) : this(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Topic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TopicId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectTopic: return s_projectTopic.Expand(ProjectId, TopicId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TopicName); /// <inheritdoc/> public bool Equals(TopicName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TopicName a, TopicName b) => !(a == b); } }
/* * 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 IndexInput = Lucene.Net.Store.IndexInput; namespace Lucene.Net.Index { public sealed class SegmentTermEnum:TermEnum, System.ICloneable { private IndexInput input; internal FieldInfos fieldInfos; internal long size; internal long position = - 1; private TermBuffer termBuffer = new TermBuffer(); private TermBuffer prevBuffer = new TermBuffer(); private TermBuffer scanBuffer = new TermBuffer(); // used for scanning private TermInfo termInfo = new TermInfo(); private int format; private bool isIndex = false; internal long indexPointer = 0; internal int indexInterval; internal int skipInterval; internal int maxSkipLevels; private int formatM1SkipInterval; internal SegmentTermEnum(IndexInput i, FieldInfos fis, bool isi) { input = i; fieldInfos = fis; isIndex = isi; maxSkipLevels = 1; // use single-level skip lists for formats > -3 int firstInt = input.ReadInt(); if (firstInt >= 0) { // original-format file, without explicit format version number format = 0; size = firstInt; // back-compatible settings indexInterval = 128; skipInterval = System.Int32.MaxValue; // switch off skipTo optimization } else { // we have a format version number format = firstInt; // check that it is a format we can understand if (format < TermInfosWriter.FORMAT_CURRENT) throw new CorruptIndexException("Unknown format version:" + format + " expected " + TermInfosWriter.FORMAT_CURRENT + " or higher"); size = input.ReadLong(); // read the size if (format == - 1) { if (!isIndex) { indexInterval = input.ReadInt(); formatM1SkipInterval = input.ReadInt(); } // switch off skipTo optimization for file format prior to 1.4rc2 in order to avoid a bug in // skipTo implementation of these versions skipInterval = System.Int32.MaxValue; } else { indexInterval = input.ReadInt(); skipInterval = input.ReadInt(); if (format <= TermInfosWriter.FORMAT) { // this new format introduces multi-level skipping maxSkipLevels = input.ReadInt(); } } System.Diagnostics.Debug.Assert(indexInterval > 0, "indexInterval=" + indexInterval + " is negative; must be > 0"); System.Diagnostics.Debug.Assert(skipInterval > 0, "skipInterval=" + skipInterval + " is negative; must be > 0"); } if (format > TermInfosWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) { termBuffer.SetPreUTF8Strings(); scanBuffer.SetPreUTF8Strings(); prevBuffer.SetPreUTF8Strings(); } } public System.Object Clone() { SegmentTermEnum clone = null; try { clone = (SegmentTermEnum) base.MemberwiseClone(); } catch (System.Exception e) { } clone.input = (IndexInput) input.Clone(); clone.termInfo = new TermInfo(termInfo); clone.termBuffer = (TermBuffer) termBuffer.Clone(); clone.prevBuffer = (TermBuffer) prevBuffer.Clone(); clone.scanBuffer = new TermBuffer(); return clone; } internal void Seek(long pointer, long p, Term t, TermInfo ti) { input.Seek(pointer); position = p; termBuffer.Set(t); prevBuffer.Reset(); termInfo.Set(ti); } /// <summary>Increments the enumeration to the next element. True if one exists.</summary> public override bool Next() { if (position++ >= size - 1) { prevBuffer.Set(termBuffer); termBuffer.Reset(); return false; } prevBuffer.Set(termBuffer); termBuffer.Read(input, fieldInfos); termInfo.docFreq = input.ReadVInt(); // read doc freq termInfo.freqPointer += input.ReadVLong(); // read freq pointer termInfo.proxPointer += input.ReadVLong(); // read prox pointer if (format == - 1) { // just read skipOffset in order to increment file pointer; // value is never used since skipTo is switched off if (!isIndex) { if (termInfo.docFreq > formatM1SkipInterval) { termInfo.skipOffset = input.ReadVInt(); } } } else { if (termInfo.docFreq >= skipInterval) termInfo.skipOffset = input.ReadVInt(); } if (isIndex) indexPointer += input.ReadVLong(); // read index pointer return true; } /// <summary>Optimized scan, without allocating new terms. /// Return number of invocations to next(). /// </summary> internal int ScanTo(Term term) { scanBuffer.Set(term); int count = 0; while (scanBuffer.CompareTo(termBuffer) > 0 && Next()) { count++; } return count; } /// <summary>Returns the current Term in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> public override Term Term() { return termBuffer.ToTerm(); } /// <summary>Returns the previous Term enumerated. Initially null.</summary> public /*internal*/ Term Prev() { return prevBuffer.ToTerm(); } /// <summary>Returns the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> internal TermInfo TermInfo() { return new TermInfo(termInfo); } /// <summary>Sets the argument to the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> internal void TermInfo(TermInfo ti) { ti.Set(termInfo); } /// <summary>Returns the docFreq from the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> public override int DocFreq() { return termInfo.docFreq; } /* Returns the freqPointer from the current TermInfo in the enumeration. Initially invalid, valid after next() called for the first time.*/ internal long FreqPointer() { return termInfo.freqPointer; } /* Returns the proxPointer from the current TermInfo in the enumeration. Initially invalid, valid after next() called for the first time.*/ internal long ProxPointer() { return termInfo.proxPointer; } /// <summary>Closes the enumeration to further activity, freeing resources. </summary> public override void Close() { input.Close(); } } }
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.GtkSharp.Forms.Controls { /// <summary> /// Button handler. /// </summary> /// <copyright>(c) 2012-2013 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class ButtonHandler : GtkControl<Gtk.Button, Button, Button.ICallback>, Button.IHandler { readonly Gtk.AccelLabel label; readonly Gtk.Image gtkimage; readonly Gtk.Table table; public static int MinimumWidth = 80; protected override Gtk.Widget FontControl { get { return label; } } public ButtonHandler() { Control = new Gtk.Button(); // need separate widgets as the theme can (and usually) disables images on buttons // gtk3 can override the theme per button, but gtk2 cannot table = new Gtk.Table(3, 3, false); table.ColumnSpacing = 0; table.RowSpacing = 0; label = new Gtk.AccelLabel(string.Empty); label.NoShowAll = true; table.Attach(label, 1, 2, 1, 2, Gtk.AttachOptions.Expand, Gtk.AttachOptions.Expand, 0, 0); gtkimage = new Gtk.Image(); gtkimage.NoShowAll = true; Control.Add(table); } protected override void Initialize() { base.Initialize(); Control.Clicked += Connector.HandleClicked; Control.SizeAllocated += Connector.HandleButtonSizeAllocated; #if GTK2 Control.SizeRequested += Connector.HandleButtonSizeRequested; #endif SetImagePosition(false); } protected new ButtonConnector Connector { get { return (ButtonConnector)base.Connector; } } protected override WeakConnector CreateConnector() { return new ButtonConnector(); } protected class ButtonConnector : GtkControlConnector { public new ButtonHandler Handler { get { return (ButtonHandler)base.Handler; } } public void HandleClicked(object sender, EventArgs e) { Handler.Callback.OnClick(Handler.Widget, EventArgs.Empty); } public void HandleButtonSizeAllocated(object o, Gtk.SizeAllocatedArgs args) { var handler = Handler; if (handler != null) { var size = args.Allocation; //if (handler.PreferredSize.Width == -1 && (size.Width > 1 || size.Height > 1)) { var minSize = handler.MinimumSize; size.Width = Math.Max(size.Width, minSize.Width); size.Height = Math.Max(size.Height, minSize.Height); if (args.Allocation != size) { var c = (Gtk.Button)o; c.SetSizeRequest(size.Width, size.Height); } } } } #if GTK2 public void HandleButtonSizeRequested(object o, Gtk.SizeRequestedArgs args) { var handler = Handler; if (handler != null) { var size = args.Requisition; //if (handler.PreferredSize.Width == -1 && (size.Width > 1 || size.Height > 1)) { var minSize = handler.MinimumSize; size.Width = Math.Max(size.Width, minSize.Width); size.Height = Math.Max(size.Height, minSize.Height); args.Requisition = size; } } } #endif } public override string Text { get { return label.Text.ToEtoMnemonic(); } set { label.TextWithMnemonic = value.ToPlatformMnemonic(); SetImagePosition(); } } static readonly object Image_Key = new object(); public Image Image { get { return Widget.Properties.Get<Image>(Image_Key); } set { Widget.Properties.Set(Image_Key, value, () => { value.SetGtkImage(gtkimage); if (value == null) gtkimage.Hide(); else gtkimage.Show(); }); } } void SetImagePosition(bool removeImage = true) { uint left, top; bool shouldHideLabel = false; switch (ImagePosition) { case ButtonImagePosition.Above: left = 1; top = 0; shouldHideLabel = true; break; case ButtonImagePosition.Below: left = 1; top = 2; shouldHideLabel = true; break; case ButtonImagePosition.Left: left = 0; top = 1; break; case ButtonImagePosition.Right: left = 2; top = 1; break; case ButtonImagePosition.Overlay: left = 1; top = 1; break; default: throw new NotSupportedException(); } shouldHideLabel &= string.IsNullOrEmpty(label.Text); if (shouldHideLabel) label.Hide(); else label.Show(); var right = left + 1; var bottom = top + 1; var options = shouldHideLabel ? Gtk.AttachOptions.Expand : Gtk.AttachOptions.Shrink; if (removeImage) table.Remove(gtkimage); table.Attach(gtkimage, left, right, top, bottom, options, options, 0, 0); } static readonly object ImagePosition_Key = new object(); public ButtonImagePosition ImagePosition { get { return Widget.Properties.Get<ButtonImagePosition>(ImagePosition_Key); } set { Widget.Properties.Set(ImagePosition_Key, value, () => SetImagePosition()); } } public Color TextColor { get { return label.GetForeground(); } set { label.SetForeground(value); } } static readonly object MinimumSize_Key = new object(); public Size MinimumSize { get { return Widget.Properties.Get(MinimumSize_Key, () => new Size(MinimumWidth, 0)); } set { if (MinimumSize != value) { Widget.Properties[MinimumSize_Key] = value; Control.QueueResize(); } } } public override void AttachEvent(string id) { switch (id) { case TextControl.TextChangedEvent: break; default: base.AttachEvent(id); break; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// SMS Recipients Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SPRECIPDataSet : EduHubDataSet<SPRECIP> { /// <inheritdoc /> public override string Name { get { return "SPRECIP"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SPRECIPDataSet(EduHubContext Context) : base(Context) { Index_CODE = new Lazy<Dictionary<int, IReadOnlyList<SPRECIP>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_TID = new Lazy<Dictionary<int, SPRECIP>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SPRECIP" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SPRECIP" /> fields for each CSV column header</returns> internal override Action<SPRECIP, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SPRECIP, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = int.Parse(v); break; case "RECIPIENT_TABLE": mapper[i] = (e, v) => e.RECIPIENT_TABLE = v; break; case "RECIPIENT_KEY": mapper[i] = (e, v) => e.RECIPIENT_KEY = v; break; case "RECIPIENT_NUMBER": mapper[i] = (e, v) => e.RECIPIENT_NUMBER = v; break; case "READ_RECEIPT": mapper[i] = (e, v) => e.READ_RECEIPT = v; break; case "SOURCE_TABLE": mapper[i] = (e, v) => e.SOURCE_TABLE = v; break; case "SOURCE_KEY": mapper[i] = (e, v) => e.SOURCE_KEY = v; break; case "STATUS": mapper[i] = (e, v) => e.STATUS = v; break; case "STATUS_MESSAGE": mapper[i] = (e, v) => e.STATUS_MESSAGE = v; break; case "SEND_DATE": mapper[i] = (e, v) => e.SEND_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "DELIVERED_DATE": mapper[i] = (e, v) => e.DELIVERED_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "MESSAGEID": mapper[i] = (e, v) => e.MESSAGEID = v == null ? (int?)null : int.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SPRECIP" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SPRECIP" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SPRECIP" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SPRECIP}"/> of entities</returns> internal override IEnumerable<SPRECIP> ApplyDeltaEntities(IEnumerable<SPRECIP> Entities, List<SPRECIP> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, IReadOnlyList<SPRECIP>>> Index_CODE; private Lazy<Dictionary<int, SPRECIP>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SPRECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPRECIP</param> /// <returns>List of related SPRECIP entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPRECIP> FindByCODE(int CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find SPRECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPRECIP</param> /// <param name="Value">List of related SPRECIP entities</param> /// <returns>True if the list of related SPRECIP entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(int CODE, out IReadOnlyList<SPRECIP> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find SPRECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPRECIP</param> /// <returns>List of related SPRECIP entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPRECIP> TryFindByCODE(int CODE) { IReadOnlyList<SPRECIP> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find SPRECIP by TID field /// </summary> /// <param name="TID">TID value used to find SPRECIP</param> /// <returns>Related SPRECIP entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPRECIP FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SPRECIP by TID field /// </summary> /// <param name="TID">TID value used to find SPRECIP</param> /// <param name="Value">Related SPRECIP entity</param> /// <returns>True if the related SPRECIP entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SPRECIP Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SPRECIP by TID field /// </summary> /// <param name="TID">TID value used to find SPRECIP</param> /// <returns>Related SPRECIP entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPRECIP TryFindByTID(int TID) { SPRECIP value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPRECIP table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPRECIP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SPRECIP]( [TID] int IDENTITY NOT NULL, [CODE] int NOT NULL, [RECIPIENT_TABLE] varchar(8) NULL, [RECIPIENT_KEY] varchar(20) NULL, [RECIPIENT_NUMBER] varchar(15) NULL, [READ_RECEIPT] varchar(1) NULL, [SOURCE_TABLE] varchar(8) NULL, [SOURCE_KEY] varchar(20) NULL, [STATUS] varchar(1) NULL, [STATUS_MESSAGE] varchar(100) NULL, [SEND_DATE] datetime NULL, [DELIVERED_DATE] datetime NULL, [MESSAGEID] int NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SPRECIP_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SPRECIP_Index_CODE] ON [dbo].[SPRECIP] ( [CODE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPRECIP]') AND name = N'SPRECIP_Index_TID') ALTER INDEX [SPRECIP_Index_TID] ON [dbo].[SPRECIP] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPRECIP]') AND name = N'SPRECIP_Index_TID') ALTER INDEX [SPRECIP_Index_TID] ON [dbo].[SPRECIP] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPRECIP"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SPRECIP"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPRECIP> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SPRECIP] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPRECIP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPRECIP data set</returns> public override EduHubDataSetDataReader<SPRECIP> GetDataSetDataReader() { return new SPRECIPDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPRECIP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPRECIP data set</returns> public override EduHubDataSetDataReader<SPRECIP> GetDataSetDataReader(List<SPRECIP> Entities) { return new SPRECIPDataReader(new EduHubDataSetLoadedReader<SPRECIP>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SPRECIPDataReader : EduHubDataSetDataReader<SPRECIP> { public SPRECIPDataReader(IEduHubDataSetReader<SPRECIP> Reader) : base (Reader) { } public override int FieldCount { get { return 16; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // RECIPIENT_TABLE return Current.RECIPIENT_TABLE; case 3: // RECIPIENT_KEY return Current.RECIPIENT_KEY; case 4: // RECIPIENT_NUMBER return Current.RECIPIENT_NUMBER; case 5: // READ_RECEIPT return Current.READ_RECEIPT; case 6: // SOURCE_TABLE return Current.SOURCE_TABLE; case 7: // SOURCE_KEY return Current.SOURCE_KEY; case 8: // STATUS return Current.STATUS; case 9: // STATUS_MESSAGE return Current.STATUS_MESSAGE; case 10: // SEND_DATE return Current.SEND_DATE; case 11: // DELIVERED_DATE return Current.DELIVERED_DATE; case 12: // MESSAGEID return Current.MESSAGEID; case 13: // LW_DATE return Current.LW_DATE; case 14: // LW_TIME return Current.LW_TIME; case 15: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // RECIPIENT_TABLE return Current.RECIPIENT_TABLE == null; case 3: // RECIPIENT_KEY return Current.RECIPIENT_KEY == null; case 4: // RECIPIENT_NUMBER return Current.RECIPIENT_NUMBER == null; case 5: // READ_RECEIPT return Current.READ_RECEIPT == null; case 6: // SOURCE_TABLE return Current.SOURCE_TABLE == null; case 7: // SOURCE_KEY return Current.SOURCE_KEY == null; case 8: // STATUS return Current.STATUS == null; case 9: // STATUS_MESSAGE return Current.STATUS_MESSAGE == null; case 10: // SEND_DATE return Current.SEND_DATE == null; case 11: // DELIVERED_DATE return Current.DELIVERED_DATE == null; case 12: // MESSAGEID return Current.MESSAGEID == null; case 13: // LW_DATE return Current.LW_DATE == null; case 14: // LW_TIME return Current.LW_TIME == null; case 15: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // RECIPIENT_TABLE return "RECIPIENT_TABLE"; case 3: // RECIPIENT_KEY return "RECIPIENT_KEY"; case 4: // RECIPIENT_NUMBER return "RECIPIENT_NUMBER"; case 5: // READ_RECEIPT return "READ_RECEIPT"; case 6: // SOURCE_TABLE return "SOURCE_TABLE"; case 7: // SOURCE_KEY return "SOURCE_KEY"; case 8: // STATUS return "STATUS"; case 9: // STATUS_MESSAGE return "STATUS_MESSAGE"; case 10: // SEND_DATE return "SEND_DATE"; case 11: // DELIVERED_DATE return "DELIVERED_DATE"; case 12: // MESSAGEID return "MESSAGEID"; case 13: // LW_DATE return "LW_DATE"; case 14: // LW_TIME return "LW_TIME"; case 15: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "RECIPIENT_TABLE": return 2; case "RECIPIENT_KEY": return 3; case "RECIPIENT_NUMBER": return 4; case "READ_RECEIPT": return 5; case "SOURCE_TABLE": return 6; case "SOURCE_KEY": return 7; case "STATUS": return 8; case "STATUS_MESSAGE": return 9; case "SEND_DATE": return 10; case "DELIVERED_DATE": return 11; case "MESSAGEID": return 12; case "LW_DATE": return 13; case "LW_TIME": return 14; case "LW_USER": return 15; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading; using BeastClientPlugIn; using System.Diagnostics; using System.Text; using System.Reflection; using System.Configuration; using VCM.Common.Log; using OpenBeast.Beast.ProductImages; /// <summary> /// Summary description for BeastConn /// </summary> /// public class BeastConn : IProductImageFactory { #region Private Variable private ServerAgent _sa; private static volatile BeastConn instance = null; private static object syncRoot = new Object(); public bool isConnection = false; private bool isForceUnload = false; //private swapService ss; private Dictionary<string, IProductImage> _dirBeastImg; #endregion #region Constructor public BeastConn() { _sa = new ServerAgent(); isConnection = false; isForceUnload = false; //ss = new swapService(); _dirBeastImg = new Dictionary<string, IProductImage>(); } #endregion #region Beast Connection [LoaderOptimization(LoaderOptimization.MultiDomain)] void runPlugIn() { string userName = string.Empty; string Password = string.Empty; string ServerName = string.Empty; string ServerName2 = string.Empty; string RetryCount = string.Empty; try { isConnection = false; isForceUnload = false; userName = ConfigurationManager.AppSettings["UserName"].ToString(); Password = ConfigurationManager.AppSettings["Password"].ToString(); ServerName = ConfigurationManager.AppSettings["ServerName"].ToString(); ServerName2 = ConfigurationManager.AppSettings["ServerName2"].ToString(); RetryCount = ConfigurationManager.AppSettings["RetryCount"].ToString(); Scripting.Dictionary props = new Scripting.Dictionary(); _sa.StatusChanged += new _IServerAgentEvents_StatusChangedEventHandler(_sa_StatusChanged); _sa.AuthenticationFailed += new _IServerAgentEvents_AuthenticationFailedEventHandler(_sa_AuthenticationFailed); _sa.ConnectionLost += new _IServerAgentEvents_ConnectionLostEventHandler(_sa_ConnectionLost); _sa.ConnectionRestored += new _IServerAgentEvents_ConnectionRestoredEventHandler(_sa_ConnectionRestored); _sa.ForcedUnLoad += new _IServerAgentEvents_ForcedUnLoadEventHandler(_sa_ForcedUnLoad); _sa.ForceUpdate += new _IServerAgentEvents_ForceUpdateEventHandler(_sa_ForceUpdate); _sa.NotifyHost += new _IServerAgentEvents_NotifyHostEventHandler(_sa_NotifyHost); Object key = "Server0"; Object value = ServerName; props.Add(ref key, ref value); key = "Port0"; value = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Port"]); props.Add(ref key, ref value); key = "retry0"; value = RetryCount; props.Add(ref key, ref value); //key = "Server1"; //value = ServerName2; //props.Add(ref key, ref value); //key = "Port1"; //value = "8200"; //props.Add(ref key, ref value); //key = "retry1"; //value = RetryCount; //props.Add(ref key, ref value); _sa.Connect(userName, Password, props); string strlogDesc = "UserName: " + userName + "; " + "ServerName: " + ServerName + "; run Plug In"; LogUtility.Info("BeastConn.cs", "runPlugIn()", strlogDesc); } catch (Exception ex) { //Debug.WriteLine("********************************Run Plugin " + ex.Message); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - runPlugIn() ERROR", ex.Message); string strErrorDesc = "UserName: " + userName + "; " + "ServerName: " + ServerName + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "runPlugIn()", strErrorDesc, ex); } } void _sa_NotifyHost(Scripting.Dictionary props) { try { //////ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_NotifyHost() :", "status:"); StringBuilder sb = new StringBuilder(); foreach (object key in props) { object rkey = key; sb.Append(key.ToString() + ":" + props.get_Item(ref rkey).ToString() + " "); } //Debug.WriteLine("*************************_sa_NotifyHost: " + sb); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_NotifyHost()", sb.ToString()); Dictionary<string, string> items = new Dictionary<string, string>(); List<string> keys = new List<string>(); List<string> vals = new List<string>(); foreach (object key in props) { keys.Add((string)key); object rkey = key; vals.Add(Convert.ToString(props.get_Item(ref rkey))); } for (int i = 0; i < props.Count; i++) { items.Add(keys[i], vals[i]); } string typeKey = "Type"; if (items.ContainsKey(typeKey) == true) { string type = items[typeKey]; if (type == "Message") { string message = ""; if (items["ErrorMessage"] != null) message = items["ErrorMessage"]; object opt = items["MessageBoxOption"]; string strmsg = message.Replace("! Would you like to download?", "."); //ss.AlertVersionMismatchMail(strmsg, "BeastConn"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_NotifyHost() --- ERROR " + message, "_sa_NotifyHost"); //MessageBoxResult res = MessageBox.Show(message, "BeastLite Update", MessageBoxButton.YesNo); //props.Add("ReturnCode", (int)res); } else if (type == "LoadStatus") { object key = "ReturnCode"; object returnVal = 1; props.Add(ref key, ref returnVal); } } LogUtility.Info("BeastConn.cs", "_sa_NotifyHost()", "Sa Notify Host"); } catch (Exception ex) { LogUtility.Error("BeastConn.cs", "_sa_NotifyHost()", ex.Message, ex); } } void _sa_ForceUpdate(string exeName) { //Debug.WriteLine("*************************_sa_ForceUpdate: status:" + exeName); LogUtility.Info("BeastConn.cs", "_sa_ForceUpdate()", exeName + "_sa_ForceUpdate"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_ForceUpdate()", exeName); } void _sa_ForcedUnLoad() { //Debug.WriteLine("*************************_sa_ForcedUnLoad"); isForceUnload = true; //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_ForcedUnLoad()", "_sa_ForcedUnLoad"); LogUtility.Info("BeastConn.cs", "_sa_ForcedUnLoad()", "sa Forced UnLoad"); } void _sa_ConnectionRestored() { //Debug.WriteLine("*************************_sa_ConnectionRestored: status:"); LogUtility.Info("BeastConn.cs", "_sa_ConnectionRestored()", "_sa_ConnectionRestored"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_ConnectionRestored()", "_sa_ConnectionRestored: status:"); } void _sa_ConnectionLost() { //Debug.WriteLine("*************************_sa_ConnectionLost:"); isConnection = false; LogUtility.Info("BeastConn.cs", "_sa_ConnectionLost()", "_sa_ConnectionLost"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_ConnectionLost()", "_sa_ConnectionLost"); } void _sa_AuthenticationFailed(string info) { //Debug.WriteLine("*************************_sa_AuthenticationFailed: status:" + info); LogUtility.Info("BeastConn.cs", "_sa_AuthenticationFailed()", info + "; sa AuthenticationFailed"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_AuthenticationFailed()", info); } void _sa_StatusChanged(BeastClientPlugIn.ServerConnectionStatus Status, string info) { //Debug.WriteLine("*************************_sa_StatusChanged: status:" + Status + " :" + info); if (Status == BeastClientPlugIn.ServerConnectionStatus.CONNECTIONSTATUS_ACTIVE) isConnection = true; else if (Status == BeastClientPlugIn.ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE) { string sMailSubject = "BeastClientPlugIn - Inactive Connection"; string sMailBody = "<div style=\"font-family:Verdana;font-size:12px;text-align:left;color:#000;\">" + "<p>Beast Connection is INACTIVE. Detail is as below:</p>" + "<p>Status: " + Status + "</p>" + "<p>Method: sa _sa_StatusChanged</p>" + "<p>Information: " + info + "</p>" + "<p>Please contact us if you have any questions.<br/><br/></p>" + UtilityHandler.VCM_MailAddress_In_Html + "</div>"; string sMailTo = System.Configuration.ConfigurationManager.AppSettings["FromEmail"].ToString(); string sMailToCC = ""; // System.Configuration.ConfigurationManager.AppSettings[""].ToString(); string sMailToBCC = ""; UtilityHandler.SendMail(sMailTo, sMailToCC, sMailToBCC, sMailSubject, sMailBody, false); } LogUtility.Info("BeastConn.cs", "_sa_StatusChanged()", Status + ";" + info + "; sa _sa_StatusChanged"); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - _sa_StatusChanged()", "status:" + Status + " :" + info); } #endregion #region Public Methods public static BeastConn Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new BeastConn(); Thread trd = new Thread(new ThreadStart(instance.runPlugIn)); trd.Start(); } } } return instance; } set // for resetting the singleton object { instance = value; } } public ServerAgent SA { get { if (_sa == null) { if (_sa == null) { _sa = new ServerAgent(); } } return _sa; } } public int CreateBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage = false, string InstanceID = "", string username = "") { try { Thread.Sleep(1000); int iCount = 0; while (iCount < 15) { Thread.Sleep(1000); if (_sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_ACTIVE) break; if ((_sa.Status != ServerConnectionStatus.CONNECTIONSTATUS_AUTHENTICATING && _sa.Status != ServerConnectionStatus.CONNECTIONSTATUS_CONNECTING) && _sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE) break; if (isForceUnload) break; iCount++; } if (isForceUnload) { return 3; // incompatible Beast Version } if (_sa.Status == ServerConnectionStatus.CONNECTIONSTATUS_INACTIVE) // if connection is inactive then return false { return 2; // connection inactive } #region create the beast image string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); bool isImageAvail = isImageAvailable(imageKey); //-------------------------------------------------------- if (!isImageAvail) { IProductImage bi = createProductImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username); // create the beast image. if (bi.DocImage.Status == DOMDataDocStatus.DATADOCSTATUS_NA) { //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - CreateBeastImage() ERROR ", "Unable to create TheBeast Image."); return 4; // Beast image creatin Failed } else { bi.refCount = 1; _dirBeastImg.Add(imageKey, bi); } } #endregion string strlogDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID +"; Create Beast Image"; LogUtility.Info("BeastConn.cs", "CreateBeastImage()", strlogDesc); //ss.SubmitUserLoginNotification_BeastPlugin("BeastConnection - CreateBeastImage()", "CREATE BEAST IMAGE SUCCESS"); return 1;// successful creation of beast image } catch (Exception ex) { string strErrorDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "CreateBeastImage()", strErrorDesc, ex); throw; } finally { isForceUnload = false; } //return 1; } public IProductImage getBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage = false, string InstanceID = "", string username = "") { try { string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); if (_dirBeastImg.ContainsKey(imageKey)) { return _dirBeastImg[imageKey]; } else { CreateBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username); return getBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, IsSharedImage, InstanceID, username); } string strlogDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID + "; get Beast Image"; LogUtility.Info("BeastConn.cs", "getBeastImage()", strlogDesc); } catch (Exception ex) { string strErrorDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "getBeastImage()", strErrorDesc, ex); } return null; } public void RemoveBeastImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, bool createImage, string ActualProductID) { try { string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); _dirBeastImg.Remove(imageKey); if (createImage == true) CreateBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID); string strlogDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID + "; Removed Beast Image"; LogUtility.Info("BeastConn.cs", "RemoveBeastImage()", strlogDesc); } catch (Exception ex) { string strErrorDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; SpeacialImageID :" + SpeacialImageID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "RemoveBeastImage()", strErrorDesc, ex); } } public void DisconnectConnection() { //Debug.WriteLine("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Disconnect"); try { ////new _dirBeastImg.Clear(); ////new _sa.Disconnect(); Instance = null; LogUtility.Info("BeastConn.cs", "DisconnectConnection()", "Disconnect Connection"); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: DisconnectConnection :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "DisconnectConnection()", ex.Message, ex); } } public string getUserProductKeyForImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID) { return ProductID + "_" + ConnectionID + "_" + UserID + "_" + CustomerID + "_" + SpeacialImageID; } public void CloseImageBeastConn(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpecialImageID) { try { string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID); if (_dirBeastImg.ContainsKey(imageKey)) { _dirBeastImg[imageKey].refCount = _dirBeastImg[imageKey].refCount - 1; if (_dirBeastImg[imageKey].refCount == 0) { if (_dirBeastImg[imageKey].InstanceID != "") { _dirBeastImg[imageKey].distoryBeastImage(); _sa.CloseDocument("instid:" + _dirBeastImg[imageKey].InstanceID.Split(':')[1].Trim() + "", null); _dirBeastImg.Remove(imageKey); } } } } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; // UtilityHandler.SendEmailForError("BeastConn.cs:: CloseImageBeastConn :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "CloseImageBeastConn()", ex.Message, ex); } } public void CloseInitiatorImageForExcel(string ConnectionID, string UserID) { try { var filterImages = from img in _dirBeastImg where (img.Value.ConnectionID.Equals(ConnectionID) || img.Value.UserID.Equals(UserID)) select img; foreach (var img in filterImages.ToList()) { img.Value.refCount = img.Value.refCount - 1; if (img.Value.refCount == 0) { if (img.Value.InstanceID != "") { _sa.CloseDocument("instid:" + img.Value.InstanceID.Split(':')[1].Trim() + "", null); RemoveBeastImage(img.Value.ProductID, img.Value.ConnectionID, img.Value.UserID, img.Value.CustomerID, img.Value.SpecialImageID, false, img.Value.ActualProductID); } } } } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; // UtilityHandler.SendEmailForError("BeastConn.cs:: CloseInitiatorImageForExcel :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "CloseInitiatorImageForExcel()", ex.Message, ex); } } public bool isImageAvailable(string imageKey) { return _dirBeastImg.ContainsKey(imageKey); } public IProductImage createProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ActualProductID, bool IsSharedImage, string InstanceID, string username) { string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; SpecialImageId: " + SpeacialImageID + "; ActualProductId: " + ActualProductID + "; IsSharedImage: " + IsSharedImage + "; InstanceID: " + InstanceID + "; ConnectionId: " + ConnectionID + "; "; try { if (AppsInfo.Instance._dirImgSID.ContainsKey(ActualProductID)) { //Removable code start //if (AppsInfo.Instance._dirImgSID.ContainsKey("vcm_calc_swaptionVolPremStrike") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"])) //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::SWAPTIONVOLPREMSTRIKE::"); // return new SwaptionVolPrem(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //else if (AppsInfo.Instance._dirImgSID.ContainsKey("vcm_calc_cmefuture") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"])) //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::CMEFUTURE::"); // return new CMEFuture(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //else if (AppsInfo.Instance._dirImgSID.ContainsKey("vcm_calc_excelshare") && AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == "1" && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_excelshare"])) //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::EXCELSHARE::"); // return new ExcelShare(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //else if (AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == "1") //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::GRIDIMAGE::"); // return new GridImages(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //else if (AppsInfo.Instance._dirImgSID.ContainsKey("vcm_calc_geoTrackerDashboard") && (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_geoTrackerDashboard"]) || ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["2125"]))) //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::PERSISTANTIMAGE::"); // return new SingleInstanceApp(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //else if (AppsInfo.Instance._dirImgSID.ContainsKey("trumid_client") && ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["trumid_client"])) //{ // LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::PERSISTANTIMAGE::"); // return new TradingGeneric(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); //} //Removable code end //else { LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::GENERICIMAGE::"); return new ProductClassGeneric(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, IsSharedImage, InstanceID, username); } } else { LogUtility.Info("BeastConn.cs", "createProductImage()", strlogDesc + "::Given product id is not found. Product ID: " + ProductID); } } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: createProductImage :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "createProductImage()", ex.Message, ex); } return null; } public void openProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ConnectionIDSignalR, string ActualProductID, string UserMode, string username) { try { //string instanceID = ""; string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); if (_dirBeastImg.ContainsKey(imageKey)) { _dirBeastImg[imageKey].openBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, ConnectionIDSignalR, username); //instanceID = _dirBeastImg[imageKey].InstanceID; _dirBeastImg[imageKey].refCount = _dirBeastImg[imageKey].refCount + 1; } else { IProductImage iProdImg = BeastConn.Instance.getBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, false, "", username); //instanceID = iProdImg.InstanceID; } //string instanceInfo = UserID + "#" + CustomerID + "#" + UserMode //2006149#100601#conn~vcm_calc_bondYield~2315f830-376b-4aec-b685-923383a0938a string strlogDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; open Product Image"; LogUtility.Info("BeastConn.cs", "openProductImage()", strlogDesc); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: openProductImage :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "openProductImage()", ex.Message, ex); } } public void shareProductImage(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID, string ConnectionIDSignalR, string InstanceID, string ActualProductID, string username) { try { string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); if (_dirBeastImg.ContainsKey(imageKey)) { _dirBeastImg[imageKey].openBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, ref _sa, ConnectionIDSignalR, username); _dirBeastImg[imageKey].refCount = _dirBeastImg[imageKey].refCount + 1; } else { BeastConn.Instance.getBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID, ActualProductID, true, InstanceID, username); } string strlogDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; Share Product Image"; LogUtility.Info("BeastConn.cs", "shareProductImage()", strlogDesc); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: openProductImage :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; " + ex.Message; LogUtility.Error("BeastConn.cs", "shareProductImage()", ex.Message, ex); } } public void deleteBeastImageByConnectionID(string ConnectionID) { //Dictionary<string, IProductImage> imgList = _dirBeastImg.Where(img => img.Value.ConnectionID == ConnectionID).ToDictionary(imgList. ; try { var filterImages = from img in _dirBeastImg where (img.Value.ConnectionID.Equals(ConnectionID)) select img; foreach (var img in filterImages.ToList()) { _sa.DeleteDocument("instid:" + img.Value.InstanceID.Split(':')[1].Trim() + "", null); RemoveBeastImage(img.Value.ProductID, img.Value.ConnectionID, img.Value.UserID, img.Value.CustomerID, img.Value.SpecialImageID, false, img.Value.ActualProductID); } string strlogDesc = "Delete Beast Image By ConnectionID"; LogUtility.Info("BeastConn.cs", "deleteBeastImageByConnectionID()", strlogDesc); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: deleteBeastImageByConnectionID :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "deleteBeastImageByConnectionID()", ex.Message, ex); } } public void deleteBeastImageByConnectionIDGroupID(string ConnectionID, string GroupID) { //Dictionary<string, IProductImage> imgList = _dirBeastImg.Where(img => img.Value.ConnectionID == ConnectionID).ToDictionary(imgList. ; try { var filterImages = from img in _dirBeastImg where (img.Value.ConnectionID.Equals(ConnectionID) && img.Value.GruopID.Equals(GroupID)) select img; foreach (var img in filterImages.ToList()) { _sa.DeleteDocument("instid:" + img.Value.InstanceID.Split(':')[1].Trim() + "", null); //RemoveBeastImage(img.Value.ProductID, img.Value.ConnectionID, img.Value.UserID, img.Value.CustomerID, img.Value.SpecialImageID, false, img.Value.ActualProductID); string strlogDescTmp = "Delete Beast Image By ConnectionID GroupID"; LogUtility.Info("BeastConn.cs", "deleteBeastImageByConnectionIDGroupID()", strlogDescTmp); } string strlogDesc = "Delete Beast Image By ConnectionID GroupID"; LogUtility.Info("BeastConn.cs", "deleteBeastImageByConnectionIDGroupID()", strlogDesc); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: deleteBeastImageByConnectionIDGroupID :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "deleteBeastImageByConnectionIDGroupID()", ex.Message, ex); } } #region FullUpdate public void GetFullUpdate(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpeacialImageID) { try { string imageKey = getUserProductKeyForImage(ProductID, ConnectionID, UserID, CustomerID, SpeacialImageID); string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; SpecialImageId: " + SpeacialImageID + "; ConnectionId: " + ConnectionID + "; "; // Currently applied in TradeingGeneric.cs AND ProductClassGeneric.cs only // Replicate createProductImage() method's "if ladder" if full update is to be implemented for all kinds of imagages if (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_swaptionVolPremStrike"])) { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::SWAPTIONVOLPREMSTRIKE::"); } else if (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"])) { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::CMEFUTURE::"); } else if (AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == "1") { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::GRIDIMAGE::"); } else if (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_geoTrackerDashboard"]) || ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["2125"])) { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::PERSISTANTIMAGE::"); } else if (ProductID == Convert.ToString(AppsInfo.Instance._dirImgSID["trumid_client"])) { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::TRUMID_CLIENT::"); if (_dirBeastImg.ContainsKey(imageKey)) { TradingGeneric docImage = (TradingGeneric)_dirBeastImg[imageKey]; docImage.GetFullUpdate(ConnectionID); } } else { LogUtility.Info("BeastConn.cs", "GetFullUpdate()", strlogDesc + "::GENERICIMAGE::"); if (_dirBeastImg.ContainsKey(imageKey)) { ProductClassGeneric docImage = (ProductClassGeneric)_dirBeastImg[imageKey]; docImage.GetFullUpdate(ConnectionID); } } } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("BeastConn.cs:: GetFullUpdate :: " + errorMessage.ToString()); LogUtility.Error("BeastConn.cs", "GetFullUpdate()", ex.Message, ex); } } #endregion #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. /*============================================================ ** ** ** ** Purpose: This is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Char : IComparable, IComparable<char>, IEquatable<char>, IConvertible { // // Member Variables // private readonly char m_value; // Do not rename (binary serialization) // // Public Constants // // The maximum character value. public const char MaxValue = (char)0xFFFF; // The minimum character value. public const char MinValue = (char)0x00; // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. private static ReadOnlySpan<byte> CategoryForLatin1 => new byte[] { // uses C# compiler's optimization for static byte[] data (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1(char ch) { return (uint)ch <= '\x00ff'; } // Return true for all characters below or equal U+007f, which is ASCII. private static bool IsAscii(char ch) { return (uint)ch <= '\x007f'; } // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { Debug.Assert(IsLatin1(ch), "char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)CategoryForLatin1[(int)ch]; } // // Private Constants // // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals(object obj) { if (!(obj is char)) { return false; } return (m_value == ((char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(char obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // public int CompareTo(object value) { if (value == null) { return 1; } if (!(value is char)) { throw new ArgumentException(SR.Arg_MustBeChar); } return (m_value - ((char)value).m_value); } public int CompareTo(char value) { return (m_value - value); } // Overrides System.Object.ToString. public override string ToString() { return char.ToString(m_value); } public string ToString(IFormatProvider provider) { return char.ToString(m_value); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } public static bool TryParse(string s, out char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } // // Static Methods // /*=================================ISDIGIT====================================== **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. public static bool IsDigit(char c) { if (IsLatin1(c)) { return IsInRange(c, '0', '9'); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); } internal static bool IsInRange(char c, char min, char max) => (uint)(c - min) <= (uint)(max - min); private static bool IsInRange(UnicodeCategory c, UnicodeCategory min, UnicodeCategory max) => (uint)(c - min) <= (uint)(max - min); /*=================================CheckLetter===================================== ** Check if the specified UnicodeCategory belongs to the letter categories. ==============================================================================*/ internal static bool CheckLetter(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.UppercaseLetter, UnicodeCategory.OtherLetter); } /*=================================ISLETTER===================================== **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. public static bool IsLetter(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return IsInRange(c, 'a', 'z'); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c))); } private static bool IsWhiteSpaceLatin1(char c) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <contorl> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE return c == ' ' || (uint)(c - '\x0009') <= ('\x000d' - '\x0009') || // (c >= '\x0009' && c <= '\x000d') c == '\x00a0' || c == '\x0085'; } /*===============================ISWHITESPACE=================================== **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return (IsWhiteSpaceLatin1(c)); } return CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)); } /*===================================IsUpper==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an uppercase character. ==============================================================================*/ // Determines whether a character is upper-case. public static bool IsUpper(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, 'A', 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } /*===================================IsLower==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an lowercase character. ==============================================================================*/ // Determines whether a character is lower-case. public static bool IsLower(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, 'a', 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } internal static bool CheckPunctuation(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.ConnectorPunctuation, UnicodeCategory.OtherPunctuation); } /*================================IsPunctuation================================= **Arguments: c -- the characater to be checked. **Returns: True if c is an punctuation mark ==============================================================================*/ // Determines whether a character is a punctuation mark. public static bool IsPunctuation(char c) { if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c))); } /*=================================CheckLetterOrDigit===================================== ** Check if the specified UnicodeCategory belongs to the letter or digit categories. ==============================================================================*/ internal static bool CheckLetterOrDigit(UnicodeCategory uc) { return CheckLetter(uc) || uc == UnicodeCategory.DecimalDigitNumber; } // Determines whether a character is a letter or a digit. public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); } return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c))); } /*===================================ToUpper==================================== ** ==============================================================================*/ // Converts a character to upper-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToUpper(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); return culture.TextInfo.ToUpper(c); } /*=================================TOUPPER====================================== **A wrapper for char.ToUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to upper-case for the default culture. // public static char ToUpper(char c) { return CultureInfo.CurrentCulture.TextInfo.ToUpper(c); } // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToUpper(c); } /*===================================ToLower==================================== ** ==============================================================================*/ // Converts a character to lower-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToLower(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); return culture.TextInfo.ToLower(c); } /*=================================TOLOWER====================================== **A wrapper for char.ToLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to lower-case for the default culture. public static char ToLower(char c) { return CultureInfo.CurrentCulture.TextInfo.ToLower(c); } // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToLower(c); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Char; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); } char IConvertible.ToChar(IFormatProvider provider) { return m_value; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Single")); } double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } public static bool IsControl(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } public static bool IsControl(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control); } public static bool IsDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return IsInRange(c, '0', '9'); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } public static bool IsLetter(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return IsInRange(c, 'a', 'z'); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsLetterOrDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } public static bool IsLower(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, 'a', 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter); } /*=================================CheckNumber===================================== ** Check if the specified UnicodeCategory belongs to the number categories. ==============================================================================*/ internal static bool CheckNumber(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherNumber); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, '0', '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsNumber(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, '0', '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index))); } //////////////////////////////////////////////////////////////////////// // // IsPunctuation // // Determines if the given character is a punctuation character. // //////////////////////////////////////////////////////////////////////// public static bool IsPunctuation(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index))); } /*================================= CheckSeparator ============================ ** Check if the specified UnicodeCategory belongs to the seprator categories. ==============================================================================*/ internal static bool CheckSeparator(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.SpaceSeparator, UnicodeCategory.ParagraphSeparator); } private static bool IsSeparatorLatin1(char c) { // U+00a0 = NO-BREAK SPACE // There is no LineSeparator or ParagraphSeparator in Latin 1 range. return (c == '\x0020' || c == '\x00a0'); } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSeparator(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsSurrogate(char c) { return IsInRange(c, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END); } public static bool IsSurrogate(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsSurrogate(s[index])); } /*================================= CheckSymbol ============================ ** Check if the specified UnicodeCategory belongs to the symbol categories. ==============================================================================*/ internal static bool CheckSymbol(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.MathSymbol, UnicodeCategory.OtherSymbol); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSymbol(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsUpper(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, 'A', 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } public static bool IsWhiteSpace(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } if (IsLatin1(s[index])) { return IsWhiteSpaceLatin1(s[index]); } return CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)); } public static UnicodeCategory GetUnicodeCategory(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c)); } return CharUnicodeInfo.GetUnicodeCategory((int)c); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } if (IsLatin1(s[index])) { return (GetLatin1UnicodeCategory(s[index])); } return CharUnicodeInfo.InternalGetUnicodeCategory(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return CharUnicodeInfo.GetNumericValue(s, index); } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ public static bool IsHighSurrogate(char c) { return IsInRange(c, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END); } public static bool IsHighSurrogate(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsHighSurrogate(s[index])); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ public static bool IsLowSurrogate(char c) { return IsInRange(c, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END); } public static bool IsLowSurrogate(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return (IsLowSurrogate(s[index])); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ public static bool IsSurrogatePair(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index + 1])); } return (false); } public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { // Since both the high and low surrogate ranges are exactly 0x400 elements // wide, and since this is a power of two, we can perform a single comparison // by baselining each value to the start of its respective range and taking // the logical OR of them. uint highSurrogateOffset = (uint)highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START; uint lowSurrogateOffset = (uint)lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START; return (highSurrogateOffset | lowSurrogateOffset) <= CharUnicodeInfo.HIGH_SURROGATE_RANGE; } internal const int UNICODE_PLANE00_END = 0x00ffff; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode. // Plane 16 contains 0x100000 ~ 0x10ffff. internal const int UNICODE_PLANE16_END = 0x10ffff; /*================================= ConvertFromUtf32 ============================ ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ public static string ConvertFromUtf32(int utf32) { if (!UnicodeUtility.IsValidUnicodeScalar((uint)utf32)) { throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32); } return Rune.UnsafeCreate((uint)utf32).ToString(); } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { // First, extend both to 32 bits, then calculate the offset of // each candidate surrogate char from the start of its range. uint highSurrogateOffset = (uint)highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START; uint lowSurrogateOffset = (uint)lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START; // This is a single comparison which allows us to check both for validity at once since // both the high surrogate range and the low surrogate range are the same length. // If the comparison fails, we call to a helper method to throw the correct exception message. if ((highSurrogateOffset | lowSurrogateOffset) > CharUnicodeInfo.HIGH_SURROGATE_RANGE) { ConvertToUtf32_ThrowInvalidArgs(highSurrogateOffset); } // The 0x40u << 10 below is to account for uuuuu = wwww + 1 in the surrogate encoding. return ((int)highSurrogateOffset << 10) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + (0x40 << 10); } [StackTraceHidden] private static void ConvertToUtf32_ThrowInvalidArgs(uint highSurrogateOffset) { // If the high surrogate is not within its expected range, throw an exception // whose message fingers it as invalid. If it's within the expected range, // change the message to read that the low surrogate was the problem. if (highSurrogateOffset > CharUnicodeInfo.HIGH_SURROGATE_RANGE) { throw new ArgumentOutOfRangeException( paramName: "highSurrogate", message: SR.ArgumentOutOfRange_InvalidHighSurrogate); } else { throw new ArgumentOutOfRangeException( paramName: "lowSurrogate", message: SR.ArgumentOutOfRange_InvalidLowSurrogate); } } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if (temp1 <= 0x3ff) { // Found a high surrogate. if (index < s.Length - 1) { int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Found a high surrogate at the end of the string. throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Find a low surrogate at the character pointed by index. throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), nameof(s)); } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Threading; namespace UltimateFracturing { public static partial class Fracturer { private class FracturingStats { public FracturingStats() { nChunkCount = 0; nTotalChunks = 0; nSplitCount = 0; bCancelFracturing = false; } public int nChunkCount; public int nTotalChunks; public int nSplitCount; public bool bCancelFracturing; } private class VoronoiCell { public class Face { public Face(Plane plane, Matrix4x4 mtxPlane, int nAdjacentCell) { this.plane = plane; this.mtxPlane = mtxPlane; this.nAdjacentCell = nAdjacentCell; } public Plane plane; public Matrix4x4 mtxPlane; public int nAdjacentCell; } public VoronoiCell(int nIndex, int x, int y, int z) { this.nIndex = nIndex; this.x = x; this.y = y; this.z = z; v3Center = Vector3.zero; listCellFaces = new List<Face>(); } public int nIndex; public int x; public int y; public int z; public Vector3 v3Center; public Vector3 v3Min; public Vector3 v3Max; public List<Face> listCellFaces; } private class VoronoiPointDistance { public VoronoiPointDistance(int nIndex, float fDistanceSqr) { this.nIndex = nIndex; this.fDistanceSqr = fDistanceSqr; } public class IncreasingDistanceComparer : IComparer<VoronoiPointDistance> { public int Compare(VoronoiPointDistance a, VoronoiPointDistance b) { return a.fDistanceSqr - b.fDistanceSqr < 0.0f ? -1 : 1; } } public int nIndex; public float fDistanceSqr; } public struct VoronoiCellKey { public int x; public int y; public int z; public VoronoiCellKey(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public class EqualityComparer : IEqualityComparer<VoronoiCellKey> { public bool Equals(VoronoiCellKey x, VoronoiCellKey y) { if(x.x == y.x && x.y == y.y && x.z == y.z) { return true; } return false; } public int GetHashCode(VoronoiCellKey x) { return x.x.GetHashCode() + x.y.GetHashCode() + x.z.GetHashCode(); } } } private class VoronoiThreadData { public VoronoiThreadData() { listVoronoiCells = new List<VoronoiCell>(); listMeshDatasChunks = new List<MeshData>(); } public List<VoronoiCell> listVoronoiCells; public MeshData meshDataCube; public List<MeshData> listMeshDatasObject; public List<MeshData> listMeshDatasChunks; public SpaceTreeNode spaceTree; public FracturedObject fracturedComponent; public int nCurrentCell; public int nTotalCells; public int nCellsProcessed; public ProgressDelegate progress; } private static FracturingStats s_FracturingStats = new FracturingStats(); private static VoronoiThreadData s_VoronoiThreadData = new VoronoiThreadData(); public delegate void ProgressDelegate(string strTitle, string message, float fT); public static void CancelFracturing() { lock(s_FracturingStats) { s_FracturingStats.bCancelFracturing = true; } } public static bool IsFracturingCancelled() { bool bCancelled = false; lock(s_FracturingStats) { bCancelled = s_FracturingStats.bCancelFracturing; } return bCancelled; } public static bool FractureToChunks(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); bool bFracturingOK = false; GameObject gameObjectIn = fracturedComponent.SourceObject; MeshFilter meshfIn = null; Mesh newMesh = null; if(gameObjectIn) { meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn) { newMesh = CopyMesh(meshfIn); newMesh.name = string.Format("mesh_{0}{1}", fracturedComponent.SourceObject.gameObject.name, fracturedComponent.SourceObject.gameObject.GetInstanceID().ToString()); //Debug.Log("In: " + gameObjectIn.name + " (Layer " + LayerMask.LayerToName(gameObjectIn.layer) + " " + gameObjectIn.layer + ")" + ": " + meshfIn.sharedMesh.subMeshCount + " submesh(es), " + ": " + (meshfIn.sharedMesh.triangles.Length / 3) + " triangles, " + meshfIn.sharedMesh.vertexCount + " vertices, " + (meshfIn.sharedMesh.normals != null ? meshfIn.sharedMesh.normals.Length : 0) + " normals, " + (meshfIn.sharedMesh.tangents != null ? meshfIn.sharedMesh.tangents.Length : 0) + " tangents, " + (meshfIn.sharedMesh.colors != null ? meshfIn.sharedMesh.colors.Length : 0) + " colors, " + (meshfIn.sharedMesh.colors32 != null ? meshfIn.sharedMesh.colors32.Length : 0) + " colors32, " + (meshfIn.sharedMesh.uv != null ? meshfIn.sharedMesh.uv.Length : 0) + " uv1, " + (meshfIn.sharedMesh.uv2 != null ? meshfIn.sharedMesh.uv2.Length : 0) + " uv2"); } } if(fracturedComponent.FracturePattern == FracturedObject.EFracturePattern.BSP) { bFracturingOK = FractureToChunksBSP(fracturedComponent, bPositionOnSourceAndHideOriginal, out listGameObjectsOut, progress); } else if(fracturedComponent.FracturePattern == FracturedObject.EFracturePattern.Voronoi) { bFracturingOK = FractureToChunksVoronoi(fracturedComponent, bPositionOnSourceAndHideOriginal, out listGameObjectsOut, progress); } if(fracturedComponent.SingleMeshObject != null) { GameObject.DestroyImmediate(fracturedComponent.SingleMeshObject); } if(bFracturingOK && Fracturer.IsFracturingCancelled() == false) { fracturedComponent.OnCreateFracturedObject(); fracturedComponent.SingleMeshObject = GameObject.Instantiate(fracturedComponent.SourceObject) as GameObject; fracturedComponent.SingleMeshObject.name = "@" + fracturedComponent.name + " (single mesh)"; fracturedComponent.SingleMeshObject.transform.localPosition = fracturedComponent.transform.position; fracturedComponent.SingleMeshObject.transform.localRotation = fracturedComponent.transform.rotation; fracturedComponent.SingleMeshObject.transform.localScale = fracturedComponent.SourceObject.transform.localScale; fracturedComponent.SingleMeshObject.transform.parent = fracturedComponent.transform; Component[] aComponents = fracturedComponent.SingleMeshObject.GetComponents<Component>(); for(int i = 0; i < aComponents.Length; i++) { Component c = aComponents[i]; if(c.GetType() != typeof(Transform) && c.GetType() != typeof(MeshRenderer) && c.GetType() != typeof(MeshFilter)) { Component.DestroyImmediate(c); } } MeshFilter singleMeshFilter = fracturedComponent.SingleMeshObject.GetComponent<MeshFilter>(); singleMeshFilter.sharedMesh = newMesh; #if UNITY_3_5 fracturedComponent.SingleMeshObject.SetActiveRecursively(true); #else fracturedComponent.SingleMeshObject.SetActive(true); #endif /* #if UNITY_EDITOR && !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) UnityEditor.Undo.RegisterCreatedObjectUndo(fracturedComponent.SingleMeshObject, "Created " + fracturedComponent.SingleMeshObject.name); foreach(GameObject chunk in listGameObjectsOut) { UnityEditor.Undo.RegisterCreatedObjectUndo(chunk, "Created " + chunk.name); } #endif */ } return bFracturingOK; } private static Mesh CopyMesh(MeshFilter meshfIn) { Mesh newMesh = new Mesh(); Vector3[] av3Vertices = meshfIn.sharedMesh.vertices; Vector3[] av3Normals = meshfIn.sharedMesh.normals; Vector4[] av4Tangents = meshfIn.sharedMesh.tangents; Vector2[] av2Mapping1 = meshfIn.sharedMesh.uv; Vector2[] av2Mapping2 = meshfIn.sharedMesh.uv2; Color[] acolColors = meshfIn.sharedMesh.colors; Color32[] aColors32 = meshfIn.sharedMesh.colors32; if(av3Vertices != null) { if(av3Vertices.Length > 0) { Vector3[] av3NewVertices = new Vector3[av3Vertices.Length]; av3Vertices.CopyTo(av3NewVertices, 0); newMesh.vertices = av3NewVertices; } } if(av3Normals != null) { if(av3Normals.Length > 0) { Vector3[] av3NewNormals = new Vector3[av3Normals.Length]; av3Normals.CopyTo(av3NewNormals, 0); newMesh.normals = av3NewNormals; } } if(av4Tangents != null) { if(av4Tangents.Length > 0) { Vector4[] av4NewTangents = new Vector4[av4Tangents.Length]; av4Tangents.CopyTo(av4NewTangents, 0); newMesh.tangents = av4NewTangents; } } if(av2Mapping1 != null) { if(av2Mapping1.Length > 0) { Vector2[] av2NewMapping1 = new Vector2[av2Mapping1.Length]; av2Mapping1.CopyTo(av2NewMapping1, 0); newMesh.uv = av2NewMapping1; } } if(av2Mapping2 != null) { if(av2Mapping2.Length > 0) { Vector2[] av2NewMapping2 = new Vector2[av2Mapping2.Length]; av2Mapping2.CopyTo(av2NewMapping2, 0); newMesh.uv2 = av2NewMapping2; } } if(acolColors != null) { if(acolColors.Length > 0) { Color[] acolNewColors = new Color[acolColors.Length]; acolColors.CopyTo(acolNewColors, 0); newMesh.colors = acolNewColors; } } if(aColors32 != null) { if(aColors32.Length > 0) { Color32[] aNewColors32 = new Color32[aColors32.Length]; aColors32.CopyTo(aNewColors32, 0); newMesh.colors32 = aNewColors32; } } newMesh.subMeshCount = meshfIn.sharedMesh.subMeshCount; for(int nSubMesh = 0; nSubMesh < meshfIn.sharedMesh.subMeshCount; nSubMesh++) { int[] anTriangles = meshfIn.sharedMesh.GetTriangles(nSubMesh); int[] anNewTriangles = new int[anTriangles.Length]; anTriangles.CopyTo(anNewTriangles, 0); newMesh.SetTriangles(anNewTriangles, nSubMesh); } return newMesh; } private static bool FractureToChunksBSP(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); MeshFilter meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn == null) { return false; } s_FracturingStats = new FracturingStats(); s_FracturingStats.nTotalChunks = fracturedComponent.GenerateNumChunks; if(progress != null) { progress("Fracturing", "Initializing...", 0.0f); } foreach(FracturedChunk chunk in fracturedComponent.ListFracturedChunks) { if(chunk != null) { UnityEngine.Object.DestroyImmediate(chunk.gameObject); } } fracturedComponent.ListFracturedChunks.Clear(); fracturedComponent.DecomposeRadius = (meshfIn.sharedMesh.bounds.max - meshfIn.sharedMesh.bounds.min).magnitude; Random.seed = fracturedComponent.RandomSeed; // Check if the input object already has been split, to get its split closing submesh FracturedChunk fracturedChunk = fracturedComponent.gameObject.GetComponent<FracturedChunk>(); int nSplitCloseSubMesh = fracturedChunk != null ? fracturedChunk.SplitSubMeshIndex : -1; if(nSplitCloseSubMesh == -1 && fracturedComponent.SourceObject.GetComponent<Renderer>()) { // Check if its material is the same as the split material if(fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterial == fracturedComponent.SplitMaterial) { nSplitCloseSubMesh = 0; } } SplitOptions splitOptions = SplitOptions.Default; splitOptions.bVerticesAreLocal = false; Vector3 v3OriginalPos = fracturedComponent.transform.position; Quaternion qOriginalRot = fracturedComponent.transform.rotation; // We'll do the splitting in (0, 0, 0) in order to improve precision Vector3 v3OriginalSourcePos = fracturedComponent.SourceObject.transform.position; fracturedComponent.SourceObject.transform.position = Vector3.zero; fracturedComponent.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.transform.rotation = fracturedComponent.SourceObject.transform.rotation; Material[] aMaterials = fracturedComponent.SourceObject.GetComponent<Renderer>() ? fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterials : null; MeshData meshDataIn = new MeshData(meshfIn.transform, meshfIn.sharedMesh, aMaterials, fracturedComponent.SourceObject.transform.localToWorldMatrix, true, nSplitCloseSubMesh, true); // Fracture the object Queue<MeshData> queueMeshDatas = new Queue<MeshData>(); // For depth order traversal, we are targeting a number of generated chunks Queue<int> queueLevels = new Queue<int>(); // Here we store the depth level of each meshData if(fracturedComponent.GenerateIslands) { CombinedMesh combinedMesh = fracturedComponent.SourceObject.GetComponent<CombinedMesh>(); if(combinedMesh != null) { // Does the mesh come from an combined mesh? -> separate objects and detect mesh islands combinedMesh.TransformObjInfoMeshVectorsToLocal(fracturedComponent.SourceObject.transform.transform); List<MeshData> listMeshDatasCombined = new List<MeshData>(); for(int nObject = 0; nObject < combinedMesh.GetObjectCount(); nObject++) { CombinedMesh.ObjectInfo objectMeshInfo = combinedMesh.GetObjectInfo(nObject); MeshData compositeObjectMesh = new MeshData(meshfIn.transform, objectMeshInfo.mesh, objectMeshInfo.aMaterials, fracturedComponent.transform.localToWorldMatrix * objectMeshInfo.mtxLocal, true, -1, true); List<MeshData> listIslands = ComputeMeshDataIslands(compositeObjectMesh, false, fracturedComponent, progress); foreach(MeshData island in listIslands) { queueMeshDatas.Enqueue(island); queueLevels.Enqueue(0); listMeshDatasCombined.Add(island); } } if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listMeshDatasCombined.Count; i++) { if(progress != null) { progress("Fracturing", "Processing combined object chunks connectivity...", i / (float)listMeshDatasCombined.Count); if(Fracturer.IsFracturingCancelled()) return false; } for(int j = 0; j < listMeshDatasCombined.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, false, listMeshDatasCombined[i], listMeshDatasCombined[j]); } } } } } else { List<MeshData> listIslands = ComputeMeshDataIslands(meshDataIn, false, fracturedComponent, progress); foreach(MeshData island in listIslands) { queueMeshDatas.Enqueue(island); queueLevels.Enqueue(0); } } } else { queueMeshDatas.Enqueue(meshDataIn); queueLevels.Enqueue(0); } s_FracturingStats.nChunkCount = 1; bool bEqualSize = fracturedComponent.GenerateIslands; // Generate chunks equally sized no matter the size of the islands detected while(queueMeshDatas.Count < s_FracturingStats.nTotalChunks) { if(IsFracturingCancelled()) { break; } MeshData meshDataCurrent = queueMeshDatas.Dequeue(); int nDepthCurrent = queueLevels.Dequeue(); if(progress != null) { progress("Fracturing", string.Format("Computing chunk {0}/{1} (Depth {2})", s_FracturingStats.nChunkCount + 1, s_FracturingStats.nTotalChunks, bEqualSize ? ": size ordered traversal" : nDepthCurrent.ToString()), Mathf.Clamp01((float)s_FracturingStats.nChunkCount / (float)s_FracturingStats.nTotalChunks)); } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; int nSplitAxis = -1; Matrix4x4 planeMtx = GetRandomPlaneSplitMatrix(meshDataCurrent, fracturedComponent, out nSplitAxis); if(SplitMeshUsingPlane(meshDataCurrent, fracturedComponent, splitOptions, planeMtx.MultiplyVector(Vector3.up), planeMtx.MultiplyVector(Vector3.right), planeMtx.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, progress) == true) { s_FracturingStats.nSplitCount++; foreach(MeshData meshDataPos in listMeshDataPos) queueMeshDatas.Enqueue(meshDataPos); queueLevels.Enqueue(nDepthCurrent + 1); foreach(MeshData meshDataNeg in listMeshDataNeg) queueMeshDatas.Enqueue(meshDataNeg); queueLevels.Enqueue(nDepthCurrent + 1); } if(bEqualSize) { // If we want to have equally sized objects mainly because of small islands preprocessing detection, then order the results by size for the next iterations List<MeshData> listSizeOrderedMeshDatas = new List<MeshData>(); while(queueMeshDatas.Count > 0) { listSizeOrderedMeshDatas.Add(queueMeshDatas.Dequeue()); } listSizeOrderedMeshDatas.Sort(new MeshData.DecreasingSizeComparer(nSplitAxis)); foreach(MeshData meshDataOrdered in listSizeOrderedMeshDatas) { queueMeshDatas.Enqueue(meshDataOrdered); } } s_FracturingStats.nChunkCount = queueMeshDatas.Count; } MeshData[] aMeshDataOut = queueMeshDatas.ToArray(); // Set the mesh properties and add objects to list if(IsFracturingCancelled() == false) { for(int nMeshCount = 0; nMeshCount < aMeshDataOut.Length; nMeshCount++) { // Create new game object GameObject newGameObject = CreateNewSplitGameObject(fracturedComponent.SourceObject, fracturedComponent, fracturedComponent.SourceObject.name + (nMeshCount + 1), true, aMeshDataOut[nMeshCount]); newGameObject.AddComponent<Rigidbody>(); newGameObject.GetComponent<Rigidbody>().isKinematic = true; listGameObjectsOut.Add(newGameObject); } if(fracturedComponent.GenerateChunkConnectionInfo) { ComputeChunkConnections(fracturedComponent, listGameObjectsOut, new List<MeshData>(aMeshDataOut), progress); } fracturedComponent.ComputeChunksRelativeVolume(); fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); fracturedComponent.ComputeSupportPlaneIntersections(); } // Compute the colliders if necessary if(fracturedComponent.AlwaysComputeColliders) { ComputeChunkColliders(fracturedComponent, progress); } bool bCancelled = IsFracturingCancelled(); // Reposition and hide original? fracturedComponent.SourceObject.transform.position = v3OriginalSourcePos; if(bPositionOnSourceAndHideOriginal) { fracturedComponent.gameObject.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.gameObject.transform.rotation = fracturedComponent.SourceObject.transform.rotation; #if UNITY_3_5 fracturedComponent.SourceObject.SetActiveRecursively(false); #else fracturedComponent.SourceObject.SetActive(false); #endif } else { fracturedComponent.transform.position = v3OriginalPos; fracturedComponent.transform.rotation = qOriginalRot; } return bCancelled == false; } private static bool FractureToChunksVoronoi(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); MeshFilter meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn == null) { return false; } int nTotalCellsX = Mathf.Max(1, fracturedComponent.VoronoiCellsXCount); int nTotalCellsY = Mathf.Max(1, fracturedComponent.VoronoiCellsYCount); int nTotalCellsZ = Mathf.Max(1, fracturedComponent.VoronoiCellsZCount); s_FracturingStats = new FracturingStats(); int nTotalCells = nTotalCellsX * nTotalCellsY * nTotalCellsZ; s_VoronoiThreadData = new VoronoiThreadData(); if(progress != null) { progress("Fracturing", "Initializing...", 0.0f); } foreach(FracturedChunk chunk in fracturedComponent.ListFracturedChunks) { if(chunk != null) { UnityEngine.Object.DestroyImmediate(chunk.gameObject); } } fracturedComponent.ListFracturedChunks.Clear(); fracturedComponent.DecomposeRadius = (meshfIn.sharedMesh.bounds.max - meshfIn.sharedMesh.bounds.min).magnitude; Random.seed = fracturedComponent.RandomSeed; // Check if the input object already has been split, to get its split closing submesh FracturedChunk fracturedChunk = fracturedComponent.gameObject.GetComponent<FracturedChunk>(); int nSplitCloseSubMesh = fracturedChunk != null ? fracturedChunk.SplitSubMeshIndex : -1; if(nSplitCloseSubMesh == -1 && fracturedComponent.SourceObject.GetComponent<Renderer>()) { // Check if its material is the same as the split material if(fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterial == fracturedComponent.SplitMaterial) { nSplitCloseSubMesh = 0; } } // Mesh data will be in local coordinates Material[] aMaterials = fracturedComponent.SourceObject.GetComponent<Renderer>() ? fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterials : null; MeshData meshDataIn = new MeshData(meshfIn.transform, meshfIn.sharedMesh, aMaterials, fracturedComponent.SourceObject.transform.localToWorldMatrix, false, nSplitCloseSubMesh, true); // Precompute space volumes with mesh datas for each volume to speed up cell generation SpaceTreeNode spaceTree = fracturedComponent.VoronoiVolumeOptimization ? SpaceTreeNode.BuildSpaceTree(meshDataIn, 8, fracturedComponent, progress) : null; // Create the cells and planes List<VoronoiCell> listVoronoiCells = new List<VoronoiCell>(); Dictionary<VoronoiCellKey, VoronoiCell> dicPos2Cell = new Dictionary<VoronoiCellKey,VoronoiCell>(); VoronoiCellKey cellKey = new VoronoiCellKey(); float fMinX = meshDataIn.v3Min.x; float fMinY = meshDataIn.v3Min.y; float fMinZ = meshDataIn.v3Min.z; float fMaxX = meshDataIn.v3Max.x; float fMaxY = meshDataIn.v3Max.y; float fMaxZ = meshDataIn.v3Max.z; float fSizeX = (fMaxX - fMinX) / nTotalCellsX; float fSizeY = (fMaxY - fMinY) / nTotalCellsY; float fSizeZ = (fMaxZ - fMinZ) / nTotalCellsZ; // We assume cells in this radius will affect the cell in the center int nCellInfluenceRadius = fracturedComponent.VoronoiProximityOptimization ? 2 : 20; for(int nCellX = 0; nCellX < nTotalCellsX; nCellX++) { for(int nCellY = 0; nCellY < nTotalCellsY; nCellY++) { for(int nCellZ = 0; nCellZ < nTotalCellsZ; nCellZ++) { float fCenterX = fMinX + (fSizeX * 0.5f) + (fSizeX * nCellX); float fCenterY = fMinY + (fSizeY * 0.5f) + (fSizeY * nCellY); float fCenterZ = fMinZ + (fSizeZ * 0.5f) + (fSizeZ * nCellZ); fCenterX += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeX * 0.5f * 0.99f * fracturedComponent.VoronoiCellsXSizeVariation; fCenterY += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeY * 0.5f * 0.99f * fracturedComponent.VoronoiCellsYSizeVariation; fCenterZ += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeZ * 0.5f * 0.99f * fracturedComponent.VoronoiCellsZSizeVariation; VoronoiCell newCell = new VoronoiCell(listVoronoiCells.Count, nCellX, nCellY, nCellZ); newCell.v3Center = new Vector3(fCenterX, fCenterY, fCenterZ); // We'll compute the v3Min and v3Max later, but this are rough values. float fRoughInfluenceRadius = nCellInfluenceRadius + (nCellInfluenceRadius * 0.5f) + 0.01f; newCell.v3Min = newCell.v3Center - new Vector3(fSizeX * fRoughInfluenceRadius, fSizeY * fRoughInfluenceRadius, fSizeZ * fRoughInfluenceRadius); newCell.v3Max = newCell.v3Center + new Vector3(fSizeX * fRoughInfluenceRadius, fSizeY * fRoughInfluenceRadius, fSizeZ * fRoughInfluenceRadius); listVoronoiCells.Add(newCell); dicPos2Cell.Add(new VoronoiCellKey(nCellX, nCellY, nCellZ), newCell); } } } List<VoronoiPointDistance> listPointDistances = new List<VoronoiPointDistance>(); for(int nCell = 0; nCell < listVoronoiCells.Count; nCell++) { if(progress != null) { progress("Fracturing", string.Format("Creating cell planes... (cell {0}/{1}) ", nCell + 1, listVoronoiCells.Count), (float)nCell / (float)listVoronoiCells.Count); } if(IsFracturingCancelled()) { break; } Vector3 v3CellCenter = listVoronoiCells[nCell].v3Center; listPointDistances.Clear(); listPointDistances.Capacity = Mathf.RoundToInt(Mathf.Pow(nCellInfluenceRadius * 2 + 1, 3)) + 1; // Build separation planes for(int x = -nCellInfluenceRadius; x <= nCellInfluenceRadius; x++) { for(int y = -nCellInfluenceRadius; y <= nCellInfluenceRadius; y++) { for(int z = -nCellInfluenceRadius; z <= nCellInfluenceRadius; z++) { if(x == 0 && y == 0 && z == 0) { continue; } int nCellX = listVoronoiCells[nCell].x + x; int nCellY = listVoronoiCells[nCell].y + y; int nCellZ = listVoronoiCells[nCell].z + z; if(nCellX < 0 || nCellX >= nTotalCellsX) continue; if(nCellY < 0 || nCellY >= nTotalCellsY) continue; if(nCellZ < 0 || nCellZ >= nTotalCellsZ) continue; cellKey.x = nCellX; cellKey.y = nCellY; cellKey.z = nCellZ; VoronoiCell otherCell = dicPos2Cell[cellKey]; listPointDistances.Add(new VoronoiPointDistance(otherCell.nIndex, (v3CellCenter - otherCell.v3Center).sqrMagnitude)); } } } listPointDistances.Sort(new VoronoiPointDistance.IncreasingDistanceComparer()); foreach(VoronoiPointDistance pointDistance in listPointDistances) { int nCellSeparation = pointDistance.nIndex; Vector3 v3NewPlaneNormal = (v3CellCenter - listVoronoiCells[nCellSeparation].v3Center).normalized; Vector3 v3NewPlanePoint = (v3CellCenter + listVoronoiCells[nCellSeparation].v3Center) * 0.5f; Plane newCellPlane = new Plane(v3NewPlaneNormal, v3NewPlanePoint); Vector3 v3Forward = Vector3.forward; float fMagX = Mathf.Abs(v3NewPlaneNormal.x); float fMagY = Mathf.Abs(v3NewPlaneNormal.y); float fMagZ = Mathf.Abs(v3NewPlaneNormal.z); if(fMagX <= fMagY && fMagX <= fMagZ) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.right); if(fMagY <= fMagX && fMagY <= fMagZ) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.up); if(fMagZ <= fMagX && fMagZ <= fMagY) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.forward); Quaternion qPlaneRot = Quaternion.LookRotation(v3Forward, v3NewPlaneNormal); Matrix4x4 mtxPlane = Matrix4x4.TRS(-v3NewPlaneNormal * newCellPlane.distance, qPlaneRot, Vector3.one); listVoronoiCells[nCell].listCellFaces.Add(new VoronoiCell.Face(newCellPlane, mtxPlane, nCellSeparation)); } } // Fracture a dummy cube and see which planes affect each cell MeshData meshDataCube = MeshData.CreateBoxMeshData(Vector3.zero, Quaternion.identity, Vector3.one, meshDataIn.v3Min, meshDataIn.v3Max); Thread[] threads = fracturedComponent.VoronoiMultithreading ? new Thread[UnityEngine.SystemInfo.processorCount] : new Thread[1]; s_VoronoiThreadData.listVoronoiCells = listVoronoiCells; s_VoronoiThreadData.meshDataCube = meshDataCube; s_VoronoiThreadData.listMeshDatasObject = null; s_VoronoiThreadData.spaceTree = spaceTree; s_VoronoiThreadData.fracturedComponent = fracturedComponent; s_VoronoiThreadData.nCurrentCell = 0; s_VoronoiThreadData.nTotalCells = nTotalCells; s_VoronoiThreadData.nCellsProcessed = 0; s_VoronoiThreadData.progress = progress; for(int nThread = 0; nThread < threads.Length; nThread++) { threads[nThread] = new Thread(new ThreadStart(ThreadVoronoiComputePlaneDependencies)); threads[nThread].Start(); } int nLastCell = -1; // float fStartTime = Time.realtimeSinceStartup; while(true) { if(IsFracturingCancelled()) { break; } int nCurrentCell = 0; lock(typeof(VoronoiThreadData)) { nCurrentCell = s_VoronoiThreadData.nCurrentCell; } if(nCurrentCell != nLastCell) { if(s_VoronoiThreadData.progress != null) { s_VoronoiThreadData.progress("Fracturing", string.Format("Finding cell plane dependencies... (cell {0}/{1}) ", nCurrentCell + 1, nTotalCells), (float)nCurrentCell / (float)nTotalCells); } nLastCell = nCurrentCell; } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCellsProcessed == nTotalCells) { break; } } Thread.Sleep(0); } // float fEndTime = Time.realtimeSinceStartup; // Debug.Log("Multithread time (" + threads.Length + " threads) = " + (fEndTime - fStartTime) + " seconds"); // Fracture the object List<MeshData> listMeshDataOut = new List<MeshData>(); List<MeshData> listMeshDatasIn = new List<MeshData>(); if(IsFracturingCancelled() == false) { if(fracturedComponent.GenerateIslands) { CombinedMesh combinedMesh = fracturedComponent.SourceObject.GetComponent<CombinedMesh>(); if(combinedMesh != null) { // Does the mesh come from an combined mesh? -> separate objects and detect mesh islands combinedMesh.TransformObjInfoMeshVectorsToLocal(fracturedComponent.transform); for(int nObject = 0; nObject < combinedMesh.GetObjectCount(); nObject++) { CombinedMesh.ObjectInfo objectMeshInfo = combinedMesh.GetObjectInfo(nObject); MeshData compositeObjectMesh = new MeshData(meshfIn.transform, objectMeshInfo.mesh, objectMeshInfo.aMaterials, fracturedComponent.transform.localToWorldMatrix * objectMeshInfo.mtxLocal, true, -1, true); List<MeshData> listIslands = ComputeMeshDataIslands(compositeObjectMesh, true, fracturedComponent, progress); foreach(MeshData island in listIslands) { listMeshDatasIn.Add(island); } } if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listMeshDatasIn.Count; i++) { if(progress != null) { progress("Fracturing", "Processing combined object chunks connectivity...", i / (float)listMeshDatasIn.Count); if(Fracturer.IsFracturingCancelled()) return false; } for(int j = 0; j < listMeshDatasIn.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, true, listMeshDatasIn[i], listMeshDatasIn[j]); } } } } } else { listMeshDatasIn = ComputeMeshDataIslands(meshDataIn, true, fracturedComponent, progress); } } else { listMeshDatasIn.Add(meshDataIn); } if(listVoronoiCells.Count == 1) { listMeshDataOut.AddRange(listMeshDatasIn); } else { s_VoronoiThreadData.listMeshDatasObject = listMeshDatasIn; s_VoronoiThreadData.fracturedComponent = fracturedComponent; s_VoronoiThreadData.nCurrentCell = 0; s_VoronoiThreadData.nCellsProcessed = 0; for(int nThread = 0; nThread < threads.Length; nThread++) { threads[nThread] = new Thread(new ThreadStart(ThreadVoronoiComputeCells)); threads[nThread].Start(); } nLastCell = -1; // fStartTime = Time.realtimeSinceStartup; while(true) { if(IsFracturingCancelled()) { break; } int nCurrentCell = 0; lock(typeof(VoronoiThreadData)) { nCurrentCell = s_VoronoiThreadData.nCurrentCell; } //if(nCurrentCell != nLastCell) { if(s_VoronoiThreadData.progress != null) { s_VoronoiThreadData.progress("Fracturing", string.Format("Computing cell {0}/{1}", nCurrentCell, nTotalCells), Mathf.Clamp01((float)nCurrentCell / (float)nTotalCells)); } nLastCell = nCurrentCell; } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCellsProcessed == nTotalCells) { break; } } Thread.Sleep(0); } // fEndTime = Time.realtimeSinceStartup; // Debug.Log("Multithread time cells (" + threads.Length + " threads) = " + (fEndTime - fStartTime) + " seconds"); listMeshDataOut.AddRange(s_VoronoiThreadData.listMeshDatasChunks); } } // Set the mesh properties and add objects to list if(IsFracturingCancelled() == false) { if(fracturedComponent.Verbose) { Debug.Log(string.Format("Computed {0} slices for {1} chunks (Average: {2}).", s_FracturingStats.nSplitCount, listMeshDataOut.Count, (float)s_FracturingStats.nSplitCount / (float)listMeshDataOut.Count)); } if(listMeshDataOut.Count > 0) { for(int nMeshCount = 0; nMeshCount < listMeshDataOut.Count; nMeshCount++) { // Create new game object and have into account we need to transform from old local space to new chunk local space listMeshDataOut[nMeshCount].v3Position = Vector3.Scale(listMeshDataOut[nMeshCount].v3Position, meshfIn.transform.localScale); for(int v = 0; v < listMeshDataOut[nMeshCount].aVertexData.Length; v++) { Vector3 v3Vertex = listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex; v3Vertex = Vector3.Scale(v3Vertex, meshfIn.transform.localScale); v3Vertex -= listMeshDataOut[nMeshCount].v3Position; listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex = v3Vertex; } listMeshDataOut[nMeshCount].v3Position = fracturedComponent.transform.TransformPoint(listMeshDataOut[nMeshCount].v3Position); listMeshDataOut[nMeshCount].qRotation = fracturedComponent.transform.rotation; listMeshDataOut[nMeshCount].v3Scale = fracturedComponent.transform.localScale; GameObject newGameObject = CreateNewSplitGameObject(fracturedComponent.SourceObject, fracturedComponent, fracturedComponent.SourceObject.name + (nMeshCount + 1), false, listMeshDataOut[nMeshCount]); newGameObject.AddComponent<Rigidbody>(); newGameObject.GetComponent<Rigidbody>().isKinematic = true; listGameObjectsOut.Add(newGameObject); // Now that the gameobject has vertices in local coordinates, transform vertices from meshdatas to world space for connection computation later for(int v = 0; v < listMeshDataOut[nMeshCount].aVertexData.Length; v++) { Vector3 v3Vertex = listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex; v3Vertex = newGameObject.transform.TransformPoint(v3Vertex); listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex = v3Vertex; } } } if(fracturedComponent.GenerateChunkConnectionInfo) { ComputeChunkConnections(fracturedComponent, listGameObjectsOut, listMeshDataOut, progress); } fracturedComponent.ComputeChunksRelativeVolume(); fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); fracturedComponent.ComputeSupportPlaneIntersections(); } // Compute the colliders if necessary if(fracturedComponent.AlwaysComputeColliders && IsFracturingCancelled() == false) { ComputeChunkColliders(fracturedComponent, progress); } bool bCancelled = IsFracturingCancelled(); // Reposition and hide original? if(bPositionOnSourceAndHideOriginal) { fracturedComponent.gameObject.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.gameObject.transform.rotation = fracturedComponent.SourceObject.transform.rotation; #if UNITY_3_5 fracturedComponent.SourceObject.SetActiveRecursively(false); #else fracturedComponent.SourceObject.SetActive(false); #endif } return bCancelled == false; } public static void ThreadVoronoiComputePlaneDependencies() { SplitOptions splitOptionsCube = new SplitOptions(); splitOptionsCube.bForceNoIslandGeneration = true; splitOptionsCube.bForceNoChunkConnectionInfo = true; splitOptionsCube.bForceNoIslandConnectionInfo = true; splitOptionsCube.bForceNoCap = false; splitOptionsCube.bForceCapVertexSoup = true; splitOptionsCube.bVerticesAreLocal = true; while(true) { int nCell; lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCurrentCell >= s_VoronoiThreadData.nTotalCells) { break; } nCell = s_VoronoiThreadData.nCurrentCell; s_VoronoiThreadData.nCurrentCell++; } if(IsFracturingCancelled()) { break; } if(s_VoronoiThreadData.spaceTree != null) { List<MeshData> volumeMeshDatas = SpaceTreeNode.GetSmallestPossibleMeshData(s_VoronoiThreadData.spaceTree, s_VoronoiThreadData.listVoronoiCells[nCell].v3Min, s_VoronoiThreadData.listVoronoiCells[nCell].v3Max); if(volumeMeshDatas.Count == 0) { s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Clear(); lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } continue; } } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; List<MeshData> listMeshDataCell = new List<MeshData>(); listMeshDataCell.Add(s_VoronoiThreadData.meshDataCube.GetDeepCopy()); for(int nFace = 0; nFace < s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Count; nFace++) { VoronoiCell.Face cellFace = s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace]; List<MeshData> listMeshDataIteration = new List<MeshData>(); bool bCutSomething = false; foreach(MeshData meshDataCell in listMeshDataCell) { if(SplitMeshUsingPlane(meshDataCell, s_VoronoiThreadData.fracturedComponent, splitOptionsCube, cellFace.mtxPlane.MultiplyVector(Vector3.up), cellFace.mtxPlane.MultiplyVector(Vector3.right), cellFace.mtxPlane.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, s_VoronoiThreadData.progress) == true) { listMeshDataIteration.AddRange(listMeshDataPos); if(listMeshDataNeg.Count > 0) { bCutSomething = true; } } } listMeshDataCell = listMeshDataIteration; if(bCutSomething == false) { // Didn't cut anything, remove this face s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.RemoveAt(nFace); nFace--; } if(listMeshDataCell.Count == 0) { // Empty cell s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Clear(); break; } } // Recompute cell bounding box min/max with all the cells that affect this one Vector3 v3Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); Vector3 v3Max = new Vector3(float.MinValue, float.MinValue, float.MinValue); foreach(MeshData meshDataCell in listMeshDataCell) { if(meshDataCell.v3Min.x < v3Min.x) v3Min.x = meshDataCell.v3Min.x; if(meshDataCell.v3Min.y < v3Min.y) v3Min.y = meshDataCell.v3Min.y; if(meshDataCell.v3Min.z < v3Min.z) v3Min.z = meshDataCell.v3Min.z; if(meshDataCell.v3Max.x > v3Max.x) v3Max.x = meshDataCell.v3Max.x; if(meshDataCell.v3Max.y > v3Max.y) v3Max.y = meshDataCell.v3Max.y; if(meshDataCell.v3Max.z > v3Max.z) v3Max.z = meshDataCell.v3Max.z; } s_VoronoiThreadData.listVoronoiCells[nCell].v3Min = v3Min; s_VoronoiThreadData.listVoronoiCells[nCell].v3Max = v3Max; lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } } } public static void ThreadVoronoiComputeCells() { SplitOptions splitOptionsMesh = new SplitOptions(); splitOptionsMesh.bForceNoProgressInfo = true; splitOptionsMesh.bVerticesAreLocal = true; splitOptionsMesh.bIgnoreNegativeSide = true; splitOptionsMesh.bForceNoIslandGeneration = true; while(true) { int nCell; lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCurrentCell >= s_VoronoiThreadData.nTotalCells) { break; } nCell = s_VoronoiThreadData.nCurrentCell; s_VoronoiThreadData.nCurrentCell++; } if(IsFracturingCancelled()) { break; } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; List<MeshData> listMeshDataCell = new List<MeshData>(); foreach(MeshData meshData in s_VoronoiThreadData.listMeshDatasObject) { listMeshDataCell.Add(meshData); } if(s_VoronoiThreadData.spaceTree != null) { listMeshDataCell = SpaceTreeNode.GetSmallestPossibleMeshData(s_VoronoiThreadData.spaceTree, s_VoronoiThreadData.listVoronoiCells[nCell].v3Min, s_VoronoiThreadData.listVoronoiCells[nCell].v3Max); if(listMeshDataCell.Count == 0) { lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } continue; } } for(int nFace = 0; nFace < s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Count; nFace++) { VoronoiCell.Face cellFace = s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace]; List<MeshData> listMeshDataIteration = new List<MeshData>(); splitOptionsMesh.nForceMeshConnectivityHash = CreateMeshConnectivityVoronoiHash(nCell, s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace].nAdjacentCell); foreach(MeshData meshDataCell in listMeshDataCell) { if(SplitMeshUsingPlane(meshDataCell, s_VoronoiThreadData.fracturedComponent, splitOptionsMesh, cellFace.mtxPlane.MultiplyVector(Vector3.up), cellFace.mtxPlane.MultiplyVector(Vector3.right), cellFace.mtxPlane.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, s_VoronoiThreadData.progress) == true) { lock(s_FracturingStats) { s_FracturingStats.nSplitCount++; } listMeshDataIteration.AddRange(listMeshDataPos); } } listMeshDataCell = listMeshDataIteration; if(listMeshDataCell.Count == 0) { break; } } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.fracturedComponent.GenerateIslands) { // Should be only 0 or 1 elements in listMeshDataCell (we forced no island generation), but to be consistent with our implementation foreach(MeshData meshData in listMeshDataCell) { s_VoronoiThreadData.listMeshDatasChunks.AddRange(ComputeMeshDataIslands(meshData, splitOptionsMesh.bVerticesAreLocal, s_VoronoiThreadData.fracturedComponent, null)); } } else { s_VoronoiThreadData.listMeshDatasChunks.AddRange(listMeshDataCell); } } lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } } } public static List<MeshData> ComputeMeshDataIslands(MeshData meshDataIn, bool bVerticesAreLocal, FracturedObject fracturedComponent, ProgressDelegate progress) { MeshFaceConnectivity faceConnectivity = new MeshFaceConnectivity(); MeshDataConnectivity meshConnectivity = new MeshDataConnectivity(); List<int>[] aListIndices = new List<int>[meshDataIn.aaIndices.Length]; List<VertexData> listVertexData = new List<VertexData>(); for(int nSubMesh = 0; nSubMesh < meshDataIn.nSubMeshCount; nSubMesh++) { aListIndices[nSubMesh] = new List<int>(); for(int i = 0; i < meshDataIn.aaIndices[nSubMesh].Length / 3; i++) { int nIndex1 = meshDataIn.aaIndices[nSubMesh][i * 3 + 0]; int nIndex2 = meshDataIn.aaIndices[nSubMesh][i * 3 + 1]; int nIndex3 = meshDataIn.aaIndices[nSubMesh][i * 3 + 2]; int nHashV1 = meshDataIn.aVertexData[nIndex1].nVertexHash; int nHashV2 = meshDataIn.aVertexData[nIndex2].nVertexHash; int nHashV3 = meshDataIn.aVertexData[nIndex3].nVertexHash; Vector3 v1 = meshDataIn.aVertexData[nIndex1].v3Vertex; Vector3 v2 = meshDataIn.aVertexData[nIndex2].v3Vertex; Vector3 v3 = meshDataIn.aVertexData[nIndex3].v3Vertex; aListIndices[nSubMesh].Add(nIndex1); aListIndices[nSubMesh].Add(nIndex2); aListIndices[nSubMesh].Add(nIndex3); if(fracturedComponent.GenerateChunkConnectionInfo) { meshConnectivity.NotifyNewClippedFace(meshDataIn, nSubMesh, i, nSubMesh, i); } faceConnectivity.AddEdge(nSubMesh, v1, v2, nHashV1, nHashV2, nIndex1, nIndex2); faceConnectivity.AddEdge(nSubMesh, v2, v3, nHashV2, nHashV3, nIndex2, nIndex3); faceConnectivity.AddEdge(nSubMesh, v3, v1, nHashV3, nHashV1, nIndex3, nIndex1); } } listVertexData.AddRange(meshDataIn.aVertexData); meshDataIn.meshDataConnectivity = meshConnectivity; List<MeshData> listIslands = MeshData.PostProcessConnectivity(meshDataIn, faceConnectivity, meshConnectivity, aListIndices, listVertexData, meshDataIn.nSplitCloseSubMesh, meshDataIn.nCurrentVertexHash, false); if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listIslands.Count; i++) { if(progress != null) { progress("Fracturing", "Processing initial island connectivity...", i / (float)listIslands.Count); if(Fracturer.IsFracturingCancelled()) return new List<MeshData>(); } for(int j = 0; j < listIslands.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, bVerticesAreLocal, listIslands[i], listIslands[j]); } } } } return listIslands; } public static void ComputeChunkColliders(FracturedObject fracturedComponent, ProgressDelegate progress) { int nChunk = 0; int nTotalFaces = 0; s_FracturingStats = new FracturingStats(); foreach(FracturedChunk fracturedChunk in fracturedComponent.ListFracturedChunks) { if(IsFracturingCancelled()) { break; } if(progress != null) { progress("Computing colliders", string.Format("Collider {0}/{1}", nChunk + 1, fracturedComponent.ListFracturedChunks.Count), (float)nChunk / (float)fracturedComponent.ListFracturedChunks.Count); } if(fracturedChunk == null) { continue; } if(fracturedChunk.GetComponent<Collider>() != null) { MeshCollider meshCollider = fracturedChunk.GetComponent<MeshCollider>(); if(meshCollider) { meshCollider.sharedMesh = null; } if(fracturedChunk.GetComponent<Collider>()) { Object.DestroyImmediate(fracturedChunk.GetComponent<Collider>()); } } if(fracturedChunk.GetComponent<Rigidbody>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Rigidbody>()); } while(fracturedChunk.transform.childCount > 0) { // Destroy concave collider hulls Object.DestroyImmediate(fracturedChunk.transform.GetChild(0).gameObject); } fracturedChunk.HasConcaveCollider = false; bool bColliderCreated = false; RemoveEmptySubmeshes(fracturedChunk); if(fracturedChunk.Volume > fracturedComponent.MinColliderVolumeForBox) { if(fracturedComponent.IntegrateWithConcaveCollider) { int nTriangles = UltimateFracturing.ConcaveColliderInterface.ComputeHull(fracturedChunk.gameObject, fracturedComponent); if(nTriangles > 0) { fracturedChunk.HasConcaveCollider = true; bColliderCreated = true; nTotalFaces += nTriangles; } } else { MeshFilter meshFilter = fracturedChunk.GetComponent<MeshFilter>(); if(meshFilter != null && meshFilter.sharedMesh != null && meshFilter.sharedMesh.vertexCount >= 3) { fracturedChunk.HasConcaveCollider = false; MeshCollider newCollider = fracturedChunk.gameObject.AddComponent<MeshCollider>(); newCollider.convex = true; bColliderCreated = true; if(newCollider.sharedMesh) { nTotalFaces += newCollider.sharedMesh.triangles.Length / 3; } newCollider.isTrigger = true; } } } if(bColliderCreated == false) { BoxCollider boxCollider = fracturedChunk.gameObject.AddComponent<BoxCollider>(); nTotalFaces += 12; boxCollider.isTrigger = true; } if(fracturedChunk.GetComponent<Collider>()) { fracturedChunk.GetComponent<Collider>().material = fracturedComponent.ChunkPhysicMaterial; } fracturedChunk.gameObject.AddComponent<Rigidbody>(); fracturedChunk.GetComponent<Rigidbody>().isKinematic = true; nChunk++; } if(IsFracturingCancelled() == false) { fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); } if(fracturedComponent.Verbose && fracturedComponent.ListFracturedChunks.Count > 0) { Debug.Log("Total collider triangles: " + nTotalFaces + ". Average = " + (nTotalFaces / fracturedComponent.ListFracturedChunks.Count)); } } public static void DeleteChunkColliders(FracturedObject fracturedComponent) { foreach(FracturedChunk fracturedChunk in fracturedComponent.ListFracturedChunks) { while(fracturedChunk.transform.childCount > 0) { // Destroy concave collider hulls Object.DestroyImmediate(fracturedChunk.transform.GetChild(0).gameObject); } if(fracturedChunk.GetComponent<Collider>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Collider>()); } if(fracturedChunk.GetComponent<Rigidbody>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Rigidbody>()); } } } private static Matrix4x4 GetRandomPlaneSplitMatrix(MeshData meshDataIn, FracturedObject fracturedComponent, out int nSplitAxisPerformed) { Vector3 v3RandomPosition = Vector3.zero; Quaternion qPlane = Quaternion.identity; Vector3 v3Min = meshDataIn.v3Min - meshDataIn.v3Position; Vector3 v3Max = meshDataIn.v3Max - meshDataIn.v3Position; if(fracturedComponent.SplitsWorldSpace == false) { // Compute min/max values in local space :( v3Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); v3Max = new Vector3(float.MinValue, float.MinValue, float.MinValue); Matrix4x4 mtxTransformVertices = Matrix4x4.TRS(meshDataIn.v3Position, meshDataIn.qRotation, meshDataIn.v3Scale).inverse; for(int i = 0; i < meshDataIn.aVertexData.Length; i++) { Vector3 v3Local = mtxTransformVertices.MultiplyPoint3x4(meshDataIn.aVertexData[i].v3Vertex); if(v3Local.x < v3Min.x) v3Min.x = v3Local.x; if(v3Local.y < v3Min.y) v3Min.y = v3Local.y; if(v3Local.z < v3Min.z) v3Min.z = v3Local.z; if(v3Local.x > v3Max.x) v3Max.x = v3Local.x; if(v3Local.y > v3Max.y) v3Max.y = v3Local.y; if(v3Local.z > v3Max.z) v3Max.z = v3Local.z; } } int nSplitAxis = -1; if(fracturedComponent.SplitRegularly) { float fSizeX = v3Max.x - v3Min.x; float fSizeY = v3Max.y - v3Min.y; float fSizeZ = v3Max.z - v3Min.z; if(fSizeX >= fSizeY && fSizeX >= fSizeZ) { nSplitAxis = 0; } else if(fSizeY >= fSizeX && fSizeY >= fSizeZ) { nSplitAxis = 1; } else { nSplitAxis = 2; } } else { for(int i = 0; i < 3; i++) { float fRandomAxis = Random.value; bool bSkipX = Mathf.Approximately(fracturedComponent.SplitXProbability, 0.0f); bool bSkipY = Mathf.Approximately(fracturedComponent.SplitYProbability, 0.0f); bool bSkipZ = Mathf.Approximately(fracturedComponent.SplitZProbability, 0.0f); if(bSkipX == false) { if(fRandomAxis <= fracturedComponent.SplitXProbability || (bSkipY && bSkipZ)) { nSplitAxis = 0; } } if(bSkipY == false && nSplitAxis == -1) { float fSplitInYProbabilityAccum = fracturedComponent.SplitXProbability + fracturedComponent.SplitYProbability; if(fRandomAxis <= fSplitInYProbabilityAccum || bSkipZ == true) { nSplitAxis = 1; } } if(nSplitAxis == -1) { nSplitAxis = 2; } } } nSplitAxisPerformed = nSplitAxis; float fRadius = 0.0f; float fAngleMax = 45.0f; if(nSplitAxis == 0) { fRadius = (v3Max.x - v3Min.x) * 0.5f; qPlane = Quaternion.LookRotation(-Vector3.up, Vector3.right) * Quaternion.Euler(new Vector3(0.0f, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitXVariation, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitXVariation)); } else if(nSplitAxis == 1) { fRadius = (v3Max.y - v3Min.y) * 0.5f; qPlane = Quaternion.Euler(new Vector3(Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitYVariation, 0.0f, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitYVariation)); } else if(nSplitAxis == 2) { fRadius = (v3Max.z - v3Min.z) * 0.5f; qPlane = Quaternion.LookRotation(-Vector3.up, Vector3.forward) * Quaternion.Euler(new Vector3(Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitZVariation, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitZVariation, 0.0f)); } fRadius = fRadius * fracturedComponent.SplitSizeVariation * 0.8f; v3RandomPosition = new Vector3(Random.Range(-1.0f, 1.0f) * fRadius, Random.Range(-1.0f, 1.0f) * fRadius, Random.Range(-1.0f, 1.0f) * fRadius); if(fracturedComponent.SplitsWorldSpace == false) { return Matrix4x4.TRS(v3RandomPosition + meshDataIn.v3Position, fracturedComponent.SourceObject.transform.rotation * qPlane, Vector3.one); } return Matrix4x4.TRS(v3RandomPosition + meshDataIn.v3Position, qPlane, Vector3.one); } private static GameObject CreateNewSplitGameObject(GameObject gameObjectIn, FracturedObject fracturedComponent, string strName, bool bTransformVerticesBackToLocal, MeshData meshData) { GameObject newGameObject = new GameObject(strName); MeshFilter meshFilter = newGameObject.AddComponent<MeshFilter>(); FracturedChunk fracturedChunk = newGameObject.AddComponent<FracturedChunk>(); fracturedChunk.transform.parent = fracturedComponent.transform; if(fracturedComponent.SourceObject) { newGameObject.layer = fracturedComponent.SourceObject.layer; } else { newGameObject.layer = fracturedComponent.gameObject.layer; } fracturedComponent.ListFracturedChunks.Add(fracturedChunk); meshData.FillMeshFilter(meshFilter, bTransformVerticesBackToLocal); fracturedChunk.SplitSubMeshIndex = meshData.nSplitCloseSubMesh; fracturedChunk.OnCreateFromFracturedObject(fracturedComponent, meshData.nSplitCloseSubMesh); newGameObject.AddComponent<MeshRenderer>(); newGameObject.GetComponent<Renderer>().shadowCastingMode = gameObjectIn.GetComponent<Renderer>().shadowCastingMode; newGameObject.GetComponent<Renderer>().receiveShadows = gameObjectIn.GetComponent<Renderer>().receiveShadows; newGameObject.GetComponent<Renderer>().enabled = false; Material[] aMaterials = new Material[meshData.nSubMeshCount]; meshData.aMaterials.CopyTo(aMaterials, 0); if(meshData.aMaterials.Length < meshData.nSubMeshCount) { // Add split material aMaterials[meshData.nSubMeshCount - 1] = fracturedComponent.SplitMaterial; } newGameObject.GetComponent<Renderer>().sharedMaterials = aMaterials; newGameObject.GetComponent<Renderer>().lightmapIndex = gameObjectIn.GetComponent<Renderer>().lightmapIndex; newGameObject.GetComponent<Renderer>().lightmapScaleOffset = gameObjectIn.GetComponent<Renderer>().lightmapScaleOffset; newGameObject.GetComponent<Renderer>().useLightProbes = gameObjectIn.GetComponent<Renderer>().useLightProbes; // Debug.Log("Out: " + newGameObject.name + ": " + meshFilter.sharedMesh.subMeshCount + " submesh(es), " + ": " + (meshFilter.sharedMesh.triangles.Length / 3) + " triangles, " + meshFilter.sharedMesh.vertexCount + " vertices, " + (meshFilter.sharedMesh.normals != null ? meshFilter.sharedMesh.normals.Length : 0) + " normals, " + (meshFilter.sharedMesh.tangents != null ? meshFilter.sharedMesh.tangents.Length : 0) + " tangents, " + (meshFilter.sharedMesh.colors != null ? meshFilter.sharedMesh.colors.Length : 0) + " colors, " + (meshFilter.sharedMesh.colors32 != null ? meshFilter.sharedMesh.colors32.Length : 0) + " colors32, " + (meshFilter.sharedMesh.uv != null ? meshFilter.sharedMesh.uv.Length : 0) + " uv1, " + (meshFilter.sharedMesh.uv2 != null ? meshFilter.sharedMesh.uv2.Length : 0) + " uv2"); return newGameObject; } private static int CreateMeshConnectivityVoronoiHash(int nCell1, int nCell2) { int nMax = Mathf.Max(nCell1, nCell2) + 256; int nMin = Mathf.Min(nCell1, nCell2) + 256; return (nMax << 16) | nMin; } private static void ComputeChunkConnections(FracturedObject fracturedObject, List<GameObject> listGameObjects, List<MeshData> listMeshDatas, ProgressDelegate progress = null) { for(int i = 0; i < listGameObjects.Count; i++) { if(progress != null) { progress("Fracturing", "Computing connections...", i / (float)listGameObjects.Count); } if(IsFracturingCancelled()) { return; } FracturedChunk chunkA = listGameObjects[i].GetComponent<FracturedChunk>(); List<FracturedChunk.AdjacencyInfo> listAdjacentChunks = new List<FracturedChunk.AdjacencyInfo>(); for(int j = 0; j < listGameObjects.Count; j++) { if(i == j) continue; FracturedChunk chunkB = listGameObjects[j].GetComponent<FracturedChunk>(); float fSharedArea = 0.0f; bool bConnected = listMeshDatas[i].GetSharedFacesArea(fracturedObject, listMeshDatas[j], out fSharedArea); bool bShared = fSharedArea >= fracturedObject.ChunkConnectionMinArea; if(Mathf.Approximately(fracturedObject.ChunkConnectionMinArea, 0.0f) && bConnected) { bShared = true; } if(bShared && bConnected) { listAdjacentChunks.Add(new FracturedChunk.AdjacencyInfo(chunkB, fSharedArea)); } } chunkA.ListAdjacentChunks = listAdjacentChunks; } } private static void RemoveEmptySubmeshes(FracturedChunk fracturedChunk) { MeshFilter meshFilter = fracturedChunk.GetComponent<MeshFilter>(); if (meshFilter == null) { return; } Mesh mesh = meshFilter.sharedMesh; if (mesh.subMeshCount < 2) { return; } MeshRenderer meshRenderer = fracturedChunk.GetComponent<MeshRenderer>(); List<Material> listMaterials = new List<Material>(); List<int[]> listSubmeshes = new List<int[]>(); int nSplitIndexSubtract = 0; for (int i = 0; i < mesh.subMeshCount; i++) { int[] indices = mesh.GetIndices(i); if (indices != null && indices.Length > 0) { listMaterials.Add(meshRenderer.sharedMaterials[i]); listSubmeshes.Add(indices); } else { if (i < fracturedChunk.SplitSubMeshIndex) { nSplitIndexSubtract--; } } } mesh.subMeshCount = listSubmeshes.Count; for (int i = 0; i < listSubmeshes.Count; i++) { mesh.SetTriangles(listSubmeshes[i], i); meshRenderer.sharedMaterials = listMaterials.ToArray(); } fracturedChunk.SplitSubMeshIndex -= nSplitIndexSubtract; meshFilter.sharedMesh = mesh; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Tests { public class WebClientTest { [Fact] public static void DefaultCtor_PropertiesReturnExpectedValues() { var wc = new WebClient(); Assert.Empty(wc.BaseAddress); //Assert.Null(wc.CachePolicy); // TODO: Uncomment when member added Assert.Null(wc.Credentials); Assert.Equal(Encoding.Default, wc.Encoding); Assert.Empty(wc.Headers); Assert.False(wc.IsBusy); Assert.NotNull(wc.Proxy); Assert.Empty(wc.QueryString); Assert.False(wc.UseDefaultCredentials); } [Fact] public static void Properties_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentException>("value", () => { wc.BaseAddress = "http::/invalid url"; }); Assert.Throws<ArgumentNullException>("Encoding", () => { wc.Encoding = null; }); } [Fact] public static void DownloadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((Uri)null); }); } [Fact] public static void DownloadFile_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, "", null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync(new Uri("http://localhost"), null); }); } [Fact] public static void DownloadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((Uri)null); }); } [Fact] public static void UploadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadFile_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadValues_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void OpenWrite_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null, null); }); } [Fact] public static void OpenRead_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((Uri)null); }); } [Fact] public static void BaseAddress_Roundtrips() { var wc = new WebClient(); wc.BaseAddress = "http://localhost/"; Assert.Equal("http://localhost/", wc.BaseAddress); wc.BaseAddress = null; Assert.Equal(string.Empty, wc.BaseAddress); } // TODO: Uncomment when member added //[Fact] //public static void CachePolicy_Roundtrips() //{ // var wc = new WebClient(); // var c = new RequestCachePolicy(RequestCacheLevel.BypassCache); // wc.CachePolicy = c; // Assert.Same(c, wc.CachePolicy); //} [Fact] public static void Credentials_Roundtrips() { var wc = new WebClient(); var c = new DummyCredentials(); wc.Credentials = c; Assert.Same(c, wc.Credentials); wc.Credentials = null; Assert.Null(wc.Credentials); } private sealed class DummyCredentials : ICredentials { public NetworkCredential GetCredential(Uri uri, string authType) => null; } [Fact] public static void Proxy_Roundtrips() { var wc = new WebClient(); Assert.Same(WebRequest.DefaultWebProxy, wc.Proxy); var p = new DummyProxy(); wc.Proxy = p; Assert.Same(p, wc.Proxy); wc.Proxy = null; Assert.Null(wc.Proxy); } private sealed class DummyProxy : IWebProxy { public ICredentials Credentials { get; set; } public Uri GetProxy(Uri destination) => null; public bool IsBypassed(Uri host) => false; } [Fact] public static void Encoding_Roundtrips() { var wc = new WebClient(); Encoding e = Encoding.UTF8; wc.Encoding = e; Assert.Same(e, wc.Encoding); } [Fact] public static void Headers_Roundtrips() { var wc = new WebClient(); Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); wc.Headers = null; Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); var whc = new WebHeaderCollection(); wc.Headers = whc; Assert.Same(whc, wc.Headers); } [Fact] public static void QueryString_Roundtrips() { var wc = new WebClient(); Assert.NotNull(wc.QueryString); Assert.Empty(wc.QueryString); wc.QueryString = null; Assert.NotNull(wc.QueryString); Assert.Empty(wc.QueryString); var nvc = new NameValueCollection(); wc.QueryString = nvc; Assert.Same(nvc, wc.QueryString); } [Fact] public static void UseDefaultCredentials_Roundtrips() { var wc = new WebClient(); for (int i = 0; i < 2; i++) { wc.UseDefaultCredentials = true; Assert.True(wc.UseDefaultCredentials); wc.UseDefaultCredentials = false; Assert.False(wc.UseDefaultCredentials); } } [Fact] public static async Task ResponseHeaders_ContainsHeadersAfterOperation() { var wc = new DerivedWebClient(); // verify we can use a derived type as well Assert.Null(wc.ResponseHeaders); await LoopbackServer.CreateServerAsync(async (server, url) => { Task<string> download = wc.DownloadStringTaskAsync(url.ToString()); Assert.Null(wc.ResponseHeaders); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: 0\r\n" + "ArbitraryHeader: ArbitraryValue\r\n" + "\r\n"); await download; }); Assert.NotNull(wc.ResponseHeaders); Assert.Equal("ArbitraryValue", wc.ResponseHeaders["ArbitraryHeader"]); } [Fact] public static async Task RequestHeaders_SpecialHeaders_RequestSucceeds() { var wc = new WebClient(); wc.Headers["Accept"] = "text/html"; wc.Headers["Connection"] = "close"; wc.Headers["ContentType"] = "text/html; charset=utf-8"; wc.Headers["Expect"] = "100-continue"; wc.Headers["Referer"] = "http://localhost"; wc.Headers["User-Agent"] = ".NET"; wc.Headers["Host"] = "http://localhost"; await LoopbackServer.CreateServerAsync(async (server, url) => { Task<string> download = wc.DownloadStringTaskAsync(url.ToString()); Assert.Null(wc.ResponseHeaders); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: 0\r\n" + "\r\n"); await download; }); } [Fact] public static async Task ConcurrentOperations_Throw() { await LoopbackServer.CreateServerAsync((server, url) => { var wc = new WebClient(); Task ignored = wc.DownloadDataTaskAsync(url); // won't complete Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); }); return Task.CompletedTask; }); } private sealed class DerivedWebClient : WebClient { } } public abstract class WebClientTestBase { public readonly static object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers; const string ExpectedText = "To be, or not to be, that is the question:" + "Whether 'tis Nobler in the mind to suffer" + "The Slings and Arrows of outrageous Fortune," + "Or to take Arms against a Sea of troubles," + "And by opposing end them:"; protected abstract bool IsAsync { get; } protected abstract Task<byte[]> DownloadDataAsync(WebClient wc, string address); protected abstract Task DownloadFileAsync(WebClient wc, string address, string fileName); protected abstract Task<string> DownloadStringAsync(WebClient wc, string address); protected abstract Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data); protected abstract Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName); protected abstract Task<string> UploadStringAsync(WebClient wc, string address, string data); protected abstract Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data); protected abstract Task<Stream> OpenReadAsync(WebClient wc, string address); protected abstract Task<Stream> OpenWriteAsync(WebClient wc, string address); [Theory] [InlineData(null)] [InlineData("text/html; charset=utf-8")] [InlineData("text/html; charset=us-ascii")] public async Task DownloadString_Success(string contentType) { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); if (contentType != null) { wc.Headers[HttpRequestHeader.ContentType] = contentType; } Task<string> download = DownloadStringAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); Assert.Equal(ExpectedText, await download); }); } [Fact] public async Task DownloadData_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); var downloadProgressInvoked = new TaskCompletionSource<bool>(); wc.DownloadProgressChanged += (s, e) => downloadProgressInvoked.TrySetResult(true); Task<byte[]> download = DownloadDataAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); Assert.Equal(ExpectedText, Encoding.ASCII.GetString(await download)); Assert.True(!IsAsync || await downloadProgressInvoked.Task, "Expected download progress callback to be invoked"); }); } [Theory] public async Task DownloadData_LargeData_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { string largeText = GetRandomText(1024 * 1024); var wc = new WebClient(); Task<byte[]> download = DownloadDataAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {largeText.Length}\r\n" + "\r\n" + $"{largeText}"); Assert.Equal(largeText, Encoding.ASCII.GetString(await download)); }); } [Fact] public async Task DownloadFile_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { string tempPath = Path.GetTempFileName(); try { var wc = new WebClient(); Task download = DownloadFileAsync(wc, url.ToString(), tempPath); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); await download; Assert.Equal(ExpectedText, File.ReadAllText(tempPath)); } finally { File.Delete(tempPath); } }); } [Fact] public async Task OpenRead_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); Task<Stream> download = OpenReadAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); using (var reader = new StreamReader(await download)) { Assert.Equal(ExpectedText, await reader.ReadToEndAsync()); } }); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task OpenWrite_Success(Uri echoServer) { var wc = new WebClient(); using (Stream s = await OpenWriteAsync(wc, echoServer.ToString())) { byte[] data = Encoding.UTF8.GetBytes(ExpectedText); await s.WriteAsync(data, 0, data.Length); } } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadData_Success(Uri echoServer) { var wc = new WebClient(); var uploadProgressInvoked = new TaskCompletionSource<bool>(); wc.UploadProgressChanged += (s, e) => uploadProgressInvoked.TrySetResult(true); // to enable chunking of the upload byte[] result = await UploadDataAsync(wc, echoServer.ToString(), Encoding.UTF8.GetBytes(ExpectedText)); Assert.Contains(ExpectedText, Encoding.UTF8.GetString(result)); Assert.True(!IsAsync || await uploadProgressInvoked.Task, "Expected upload progress callback to be invoked"); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadData_LargeData_Success(Uri echoServer) { var wc = new WebClient(); string largeText = GetRandomText(512 * 1024); byte[] result = await UploadDataAsync(wc, echoServer.ToString(), Encoding.UTF8.GetBytes(largeText)); Assert.Contains(largeText, Encoding.UTF8.GetString(result)); } private static string GetRandomText(int length) { var rand = new Random(); return new string(Enumerable.Range(0, 512 * 1024).Select(_ => (char)('a' + rand.Next(0, 26))).ToArray()); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadFile_Success(Uri echoServer) { string tempPath = Path.GetTempFileName(); try { File.WriteAllBytes(tempPath, Encoding.UTF8.GetBytes(ExpectedText)); var wc = new WebClient(); byte[] result = await UploadFileAsync(wc, echoServer.ToString(), tempPath); Assert.Contains(ExpectedText, Encoding.UTF8.GetString(result)); } finally { File.Delete(tempPath); } } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadString_Success(Uri echoServer) { var wc = new WebClient(); string result = await UploadStringAsync(wc, echoServer.ToString(), ExpectedText); Assert.Contains(ExpectedText, result); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadValues_Success(Uri echoServer) { var wc = new WebClient(); byte[] result = await UploadValuesAsync(wc, echoServer.ToString(), new NameValueCollection() { { "Data", ExpectedText } }); Assert.Contains(WebUtility.UrlEncode(ExpectedText), Encoding.UTF8.GetString(result)); } } public class SyncWebClientTest : WebClientTestBase { protected override bool IsAsync => false; protected override Task<byte[]> DownloadDataAsync(WebClient wc, string address) => Task.Run(() => wc.DownloadData(address)); protected override Task DownloadFileAsync(WebClient wc, string address, string fileName) => Task.Run(() => wc.DownloadFile(address, fileName)); protected override Task<string> DownloadStringAsync(WebClient wc, string address) => Task.Run(() => wc.DownloadString(address)); protected override Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data) => Task.Run(() => wc.UploadData(address, data)); protected override Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName) => Task.Run(() => wc.UploadFile(address, fileName)); protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => Task.Run(() => wc.UploadString(address, data)); protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => Task.Run(() => wc.UploadValues(address, data)); protected override Task<Stream> OpenReadAsync(WebClient wc, string address) => Task.Run(() => wc.OpenRead(address)); protected override Task<Stream> OpenWriteAsync(WebClient wc, string address) => Task.Run(() => wc.OpenWrite(address)); } // NOTE: Today the XxTaskAsync APIs are implemented as wrappers for the XxAsync APIs. // If that changes, we should add an EapWebClientTest here that targets those directly. // In the meantime, though, there's no benefit to the extra testing it would provide. public class TaskWebClientTest : WebClientTestBase { protected override bool IsAsync => true; protected override Task<byte[]> DownloadDataAsync(WebClient wc, string address) => wc.DownloadDataTaskAsync(address); protected override Task DownloadFileAsync(WebClient wc, string address, string fileName) => wc.DownloadFileTaskAsync(address, fileName); protected override Task<string> DownloadStringAsync(WebClient wc, string address) => wc.DownloadStringTaskAsync(address); protected override Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data) => wc.UploadDataTaskAsync(address, data); protected override Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName) => wc.UploadFileTaskAsync(address, fileName); protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => wc.UploadStringTaskAsync(address, data); protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => wc.UploadValuesTaskAsync(address, data); protected override Task<Stream> OpenReadAsync(WebClient wc, string address) => wc.OpenReadTaskAsync(address); protected override Task<Stream> OpenWriteAsync(WebClient wc, string address) => wc.OpenWriteTaskAsync(address); } }
// 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.Text; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; namespace System.Xml.Schema { // This is an atomic value converted for Silverlight XML core that knows only how to convert to and from string. // It does not recognize XmlAtomicValue or XPathItemType. internal class XmlUntypedStringConverter { // Fields private readonly bool _listsAllowed; private readonly XmlUntypedStringConverter _listItemConverter; // Cached types private static readonly Type s_decimalType = typeof(decimal); private static readonly Type s_int32Type = typeof(int); private static readonly Type s_int64Type = typeof(long); private static readonly Type s_stringType = typeof(string); private static readonly Type s_objectType = typeof(object); private static readonly Type s_byteType = typeof(byte); private static readonly Type s_int16Type = typeof(short); private static readonly Type s_SByteType = typeof(sbyte); private static readonly Type s_UInt16Type = typeof(ushort); private static readonly Type s_UInt32Type = typeof(uint); private static readonly Type s_UInt64Type = typeof(ulong); private static readonly Type s_doubleType = typeof(double); private static readonly Type s_singleType = typeof(float); private static readonly Type s_dateTimeType = typeof(DateTime); private static readonly Type s_dateTimeOffsetType = typeof(DateTimeOffset); private static readonly Type s_booleanType = typeof(bool); private static readonly Type s_byteArrayType = typeof(byte[]); private static readonly Type s_xmlQualifiedNameType = typeof(XmlQualifiedName); private static readonly Type s_uriType = typeof(Uri); private static readonly Type s_timeSpanType = typeof(TimeSpan); private const string UntypedStringTypeName = "xdt:untypedAtomic"; // Static convertor instance internal static XmlUntypedStringConverter Instance = new XmlUntypedStringConverter(true); private XmlUntypedStringConverter(bool listsAllowed) { _listsAllowed = listsAllowed; if (listsAllowed) { _listItemConverter = new XmlUntypedStringConverter(false); } } internal object FromString(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException(nameof(value)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == s_objectType) destinationType = typeof(string); if (destinationType == s_booleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == s_byteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_byteArrayType) return StringToBase64Binary((string)value); if (destinationType == s_dateTimeType) return StringToDateTime((string)value); if (destinationType == s_dateTimeOffsetType) return StringToDateTimeOffset((string)value); if (destinationType == s_decimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == s_doubleType) return XmlConvert.ToDouble((string)value); if (destinationType == s_int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == s_int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == s_SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == s_singleType) return XmlConvert.ToSingle((string)value); if (destinationType == s_timeSpanType) return StringToDuration((string)value); if (destinationType == s_UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == s_UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == s_UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == s_uriType) return XmlConvert.ToUri((string)value); if (destinationType == s_xmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == s_stringType) return ((string)value); return StringToListType(value, destinationType, nsResolver); } private byte Int32ToByte(int value) { if (value < (int)byte.MinValue || value > (int)byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" })); return (byte)value; } private short Int32ToInt16(int value) { if (value < (int)short.MinValue || value > (int)short.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" })); return (short)value; } private sbyte Int32ToSByte(int value) { if (value < (int)sbyte.MinValue || value > (int)sbyte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" })); return (sbyte)value; } private ushort Int32ToUInt16(int value) { if (value < (int)ushort.MinValue || value > (int)ushort.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" })); return (ushort)value; } private uint Int64ToUInt32(long value) { if (value < (long)uint.MinValue || value > (long)uint.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" })); return (uint)value; } private ulong DecimalToUInt64(decimal value) { if (value < (decimal)ulong.MinValue || value > (decimal)ulong.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" })); return (ulong)value; } private byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } private static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver) { string prefix, localName, ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } private object StringToListType(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (_listsAllowed && destinationType.IsArray) { Type itemTypeDst = destinationType.GetElementType(); // Different StringSplitOption needs to be used because of following bugs: // 566053: Behavior change between SL2 and Dev10 in the way string arrays are deserialized by the XmlReader.ReadContentsAs method // 643697: Deserialization of typed arrays by the XmlReader.ReadContentsAs method fails // // In Silverligt 2 the XmlConvert.SplitString was not using the StringSplitOptions, which is the same as using StringSplitOptions.None. // What it meant is that whenever there is a double space between two values in the input string it turned into // an string.Empty entry in the intermediate string array. In Dev10 empty entries were always removed (StringSplitOptions.RemoveEmptyEntries). // // Moving forward in coreclr we'll use Dev10 behavior which empty entries were always removed (StringSplitOptions.RemoveEmptyEntries). // we didn't quirk the change because we discover not many apps using ReadContentAs with string array type parameter // // The types Object, Byte[], String and Uri can be successfully deserialized from string.Empty, so we need to preserve the // Silverlight 2 behavior for back-compat (=use StringSplitOptions.None). All the other array types failed to deserialize // from string.Empty in Silverlight 2 (threw an exception), so we can fix all of these as they are not breaking changes // (=use StringSplitOptions.RemoveEmptyEntries). if (itemTypeDst == s_objectType) return ToArray<object>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_booleanType) return ToArray<bool>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteType) return ToArray<byte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_byteArrayType) return ToArray<byte[]>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeType) return ToArray<DateTime>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_dateTimeOffsetType) return ToArray<DateTimeOffset>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_decimalType) return ToArray<decimal>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_doubleType) return ToArray<double>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int16Type) return ToArray<short>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int32Type) return ToArray<int>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_int64Type) return ToArray<long>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_SByteType) return ToArray<sbyte>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_singleType) return ToArray<float>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_stringType) return ToArray<string>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_timeSpanType) return ToArray<TimeSpan>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt16Type) return ToArray<ushort>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt32Type) return ToArray<uint>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_UInt64Type) return ToArray<ulong>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_uriType) return ToArray<Uri>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); if (itemTypeDst == s_xmlQualifiedNameType) return ToArray<XmlQualifiedName>(XmlConvert.SplitString(value, StringSplitOptions.RemoveEmptyEntries), nsResolver); } throw CreateInvalidClrMappingException(typeof(string), destinationType); } private T[] ToArray<T>(string[] stringArray, IXmlNamespaceResolver nsResolver) { T[] arrDst = new T[stringArray.Length]; for (int i = 0; i < stringArray.Length; i++) { arrDst[i] = (T)_listItemConverter.FromString(stringArray[i], typeof(T), nsResolver); } return arrDst; } private Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, UntypedStringTypeName, sourceType.Name, destinationType.Name)); } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Reflection; namespace Lucene.Net.Index { /* * 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 CollectionUtil = Lucene.Net.Util.CollectionUtil; using Directory = Lucene.Net.Store.Directory; using InfoStream = Lucene.Net.Util.InfoStream; /// <summary> /// This class keeps track of each SegmentInfos instance that /// is still "live", either because it corresponds to a /// segments_N file in the <see cref="Directory"/> (a "commit", i.e. a /// committed <see cref="SegmentInfos"/>) or because it's an in-memory /// <see cref="SegmentInfos"/> that a writer is actively updating but has /// not yet committed. This class uses simple reference /// counting to map the live <see cref="SegmentInfos"/> instances to /// individual files in the <see cref="Directory"/>. /// <para/> /// The same directory file may be referenced by more than /// one <see cref="IndexCommit"/>, i.e. more than one <see cref="SegmentInfos"/>. /// Therefore we count how many commits reference each file. /// When all the commits referencing a certain file have been /// deleted, the refcount for that file becomes zero, and the /// file is deleted. /// <para/> /// A separate deletion policy interface /// (<see cref="IndexDeletionPolicy"/>) is consulted on creation (OnInit) /// and once per commit (OnCommit), to decide when a commit /// should be removed. /// <para/> /// It is the business of the <see cref="IndexDeletionPolicy"/> to choose /// when to delete commit points. The actual mechanics of /// file deletion, retrying, etc, derived from the deletion /// of commit points is the business of the <see cref="IndexFileDeleter"/>. /// <para/> /// The current default deletion policy is /// <see cref="KeepOnlyLastCommitDeletionPolicy"/>, which removes all /// prior commits when a new commit has completed. This /// matches the behavior before 2.2. /// <para/> /// Note that you must hold the <c>write.lock</c> before /// instantiating this class. It opens segments_N file(s) /// directly with no retry logic. /// </summary> internal sealed class IndexFileDeleter : IDisposable { /// <summary> /// Files that we tried to delete but failed (likely /// because they are open and we are running on Windows), /// so we will retry them again later: /// </summary> private IList<string> deletable; /// <summary> /// Reference count for all files in the index. /// Counts how many existing commits reference a file. /// </summary> private IDictionary<string, RefCount> refCounts = new Dictionary<string, RefCount>(); /// <summary> /// Holds all commits (segments_N) currently in the index. /// this will have just 1 commit if you are using the /// default delete policy (KeepOnlyLastCommitDeletionPolicy). /// Other policies may leave commit points live for longer /// in which case this list would be longer than 1: /// </summary> private IList<CommitPoint> commits = new List<CommitPoint>(); /// <summary> /// Holds files we had incref'd from the previous /// non-commit checkpoint: /// </summary> private readonly List<string> lastFiles = new List<string>(); /// <summary> /// Commits that the IndexDeletionPolicy have decided to delete: /// </summary> private IList<CommitPoint> commitsToDelete = new List<CommitPoint>(); private readonly InfoStream infoStream; private Directory directory; private IndexDeletionPolicy policy; internal readonly bool startingCommitDeleted; private SegmentInfos lastSegmentInfos; /// <summary> /// Change to true to see details of reference counts when /// infoStream is enabled /// </summary> public static bool VERBOSE_REF_COUNTS = false; // Used only for assert private readonly IndexWriter writer; // called only from assert private bool IsLocked => //LUCENENET TODO: This always returns true - probably incorrect writer == null || true /*Monitor.IsEntered(writer)*/; // LUCENENET specific - optimized empty array creation private static readonly string[] EMPTY_STRINGS = #if FEATURE_ARRAYEMPTY Array.Empty<string>(); #else new string[0]; #endif /// <summary> /// Initialize the deleter: find all previous commits in /// the <see cref="Directory"/>, incref the files they reference, call /// the policy to let it delete commits. this will remove /// any files not referenced by any of the commits. </summary> /// <exception cref="IOException"> if there is a low-level IO error </exception> public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, SegmentInfos segmentInfos, InfoStream infoStream, IndexWriter writer, bool initialIndexExists) { this.infoStream = infoStream; this.writer = writer; string currentSegmentsFile = segmentInfos.GetSegmentsFileName(); if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "init: current segments file is \"" + currentSegmentsFile + "\"; deletionPolicy=" + policy); } this.policy = policy; this.directory = directory; // First pass: walk the files and initialize our ref // counts: long currentGen = segmentInfos.Generation; CommitPoint currentCommitPoint = null; string[] files = null; try { files = directory.ListAll(); } #pragma warning disable 168 catch (DirectoryNotFoundException e) #pragma warning restore 168 { // it means the directory is empty, so ignore it. files = EMPTY_STRINGS; } if (currentSegmentsFile != null) { Regex r = IndexFileNames.CODEC_FILE_PATTERN; foreach (string fileName in files) { if (!fileName.EndsWith("write.lock", StringComparison.Ordinal) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal) && (r.IsMatch(fileName) || fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal))) { // Add this file to refCounts with initial count 0: GetRefCount(fileName); if (fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal)) { // this is a commit (segments or segments_N), and // it's valid (<= the max gen). Load it, then // incref all files it refers to: if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "init: load commit \"" + fileName + "\""); } SegmentInfos sis = new SegmentInfos(); try { sis.Read(directory, fileName); } #pragma warning disable 168 catch (FileNotFoundException e) #pragma warning restore 168 { // LUCENE-948: on NFS (and maybe others), if // you have writers switching back and forth // between machines, it's very likely that the // dir listing will be stale and will claim a // file segments_X exists when in fact it // doesn't. So, we catch this and handle it // as if the file does not exist if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point"); } sis = null; } // LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this //catch (NoSuchFileException) //{ // // LUCENE-948: on NFS (and maybe others), if // // you have writers switching back and forth // // between machines, it's very likely that the // // dir listing will be stale and will claim a // // file segments_X exists when in fact it // // doesn't. So, we catch this and handle it // // as if the file does not exist // if (infoStream.IsEnabled("IFD")) // { // infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point"); // } // sis = null; //} // LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException // in Lucene, we need to catch it here to be on the safe side. catch (DirectoryNotFoundException) { // LUCENE-948: on NFS (and maybe others), if // you have writers switching back and forth // between machines, it's very likely that the // dir listing will be stale and will claim a // file segments_X exists when in fact it // doesn't. So, we catch this and handle it // as if the file does not exist if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point"); } sis = null; } catch (IOException /*e*/) { if (SegmentInfos.GenerationFromSegmentsFileName(fileName) <= currentGen && directory.FileLength(fileName) > 0) { throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } else { // Most likely we are opening an index that // has an aborted "future" commit, so suppress // exc in this case sis = null; } } if (sis != null) { CommitPoint commitPoint = new CommitPoint(commitsToDelete, directory, sis); if (sis.Generation == segmentInfos.Generation) { currentCommitPoint = commitPoint; } commits.Add(commitPoint); IncRef(sis, true); if (lastSegmentInfos == null || sis.Generation > lastSegmentInfos.Generation) { lastSegmentInfos = sis; } } } } } } if (currentCommitPoint == null && currentSegmentsFile != null && initialIndexExists) { // We did not in fact see the segments_N file // corresponding to the segmentInfos that was passed // in. Yet, it must exist, because our caller holds // the write lock. this can happen when the directory // listing was stale (eg when index accessed via NFS // client with stale directory listing cache). So we // try now to explicitly open this commit point: SegmentInfos sis = new SegmentInfos(); try { sis.Read(directory, currentSegmentsFile); } catch (IOException e) { throw new CorruptIndexException("failed to locate current segments_N file \"" + currentSegmentsFile + "\"" + e.ToString(), e); } if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "forced open of current segments file " + segmentInfos.GetSegmentsFileName()); } currentCommitPoint = new CommitPoint(commitsToDelete, directory, sis); commits.Add(currentCommitPoint); IncRef(sis, true); } // We keep commits list in sorted order (oldest to newest): CollectionUtil.TimSort(commits); // Now delete anything with ref count at 0. These are // presumably abandoned files eg due to crash of // IndexWriter. foreach (KeyValuePair<string, RefCount> entry in refCounts) { RefCount rc = entry.Value; string fileName = entry.Key; if (0 == rc.count) { if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "init: removing unreferenced file \"" + fileName + "\""); } DeleteFile(fileName); } } // Finally, give policy a chance to remove things on // startup: this.policy.OnInit(commits); // Always protect the incoming segmentInfos since // sometime it may not be the most recent commit Checkpoint(segmentInfos, false); startingCommitDeleted = currentCommitPoint == null ? false : currentCommitPoint.IsDeleted; DeleteCommits(); } private void EnsureOpen() { if (writer == null) { throw new ObjectDisposedException(this.GetType().FullName, "this IndexWriter is closed"); } else { writer.EnsureOpen(false); } } public SegmentInfos LastSegmentInfos => lastSegmentInfos; /// <summary> /// Remove the CommitPoints in the commitsToDelete List by /// DecRef'ing all files from each SegmentInfos. /// </summary> private void DeleteCommits() { int size = commitsToDelete.Count; if (size > 0) { // First decref all files that had been referred to by // the now-deleted commits: for (int i = 0; i < size; i++) { CommitPoint commit = commitsToDelete[i]; if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "deleteCommits: now decRef commit \"" + commit.SegmentsFileName + "\""); } foreach (string file in commit.files) { DecRef(file); } } commitsToDelete.Clear(); // Now compact commits to remove deleted ones (preserving the sort): size = commits.Count; int readFrom = 0; int writeTo = 0; while (readFrom < size) { CommitPoint commit = commits[readFrom]; if (!commit.deleted) { if (writeTo != readFrom) { commits[writeTo] = commits[readFrom]; } writeTo++; } readFrom++; } while (size > writeTo) { commits.RemoveAt(size - 1); size--; } } } /// <summary> /// Writer calls this when it has hit an error and had to /// roll back, to tell us that there may now be /// unreferenced files in the filesystem. So we re-list /// the filesystem and delete such files. If <paramref name="segmentName"/> /// is non-null, we will only delete files corresponding to /// that segment. /// </summary> public void Refresh(string segmentName) { Debug.Assert(IsLocked); string[] files = directory.ListAll(); string segmentPrefix1; string segmentPrefix2; if (segmentName != null) { segmentPrefix1 = segmentName + "."; segmentPrefix2 = segmentName + "_"; } else { segmentPrefix1 = null; segmentPrefix2 = null; } Regex r = IndexFileNames.CODEC_FILE_PATTERN; for (int i = 0; i < files.Length; i++) { string fileName = files[i]; //m.reset(fileName); if ((segmentName == null || fileName.StartsWith(segmentPrefix1, StringComparison.Ordinal) || fileName.StartsWith(segmentPrefix2, StringComparison.Ordinal)) && !fileName.EndsWith("write.lock", StringComparison.Ordinal) && !refCounts.ContainsKey(fileName) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal) && (r.IsMatch(fileName) || fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal))) { // Unreferenced file, so remove it if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "refresh [prefix=" + segmentName + "]: removing newly created unreferenced file \"" + fileName + "\""); } DeleteFile(fileName); } } } public void Refresh() { // Set to null so that we regenerate the list of pending // files; else we can accumulate same file more than // once Debug.Assert(IsLocked); deletable = null; Refresh(null); } public void Dispose() { // DecRef old files from the last checkpoint, if any: Debug.Assert(IsLocked); if (lastFiles.Count > 0) { DecRef(lastFiles); lastFiles.Clear(); } DeletePendingFiles(); } /// <summary> /// Revisits the <see cref="IndexDeletionPolicy"/> by calling its /// <see cref="IndexDeletionPolicy.OnCommit{T}(IList{T})"/> again with the known commits. /// this is useful in cases where a deletion policy which holds onto index /// commits is used. The application may know that some commits are not held by /// the deletion policy anymore and call /// <see cref="IndexWriter.DeleteUnusedFiles()"/>, which will attempt to delete the /// unused commits again. /// </summary> internal void RevisitPolicy() { Debug.Assert(IsLocked); if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "now revisitPolicy"); } if (commits.Count > 0) { policy.OnCommit(commits); DeleteCommits(); } } public void DeletePendingFiles() { Debug.Assert(IsLocked); if (deletable != null) { IList<string> oldDeletable = deletable; deletable = null; int size = oldDeletable.Count; for (int i = 0; i < size; i++) { if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "delete pending file " + oldDeletable[i]); } DeleteFile(oldDeletable[i]); } } } /// <summary> /// For definition of "check point" see <see cref="IndexWriter"/> comments: /// "Clarification: Check Points (and commits)". /// <para/> /// Writer calls this when it has made a "consistent /// change" to the index, meaning new files are written to /// the index and the in-memory <see cref="SegmentInfos"/> have been /// modified to point to those files. /// <para/> /// This may or may not be a commit (segments_N may or may /// not have been written). /// <para/> /// We simply incref the files referenced by the new /// <see cref="SegmentInfos"/> and decref the files we had previously /// seen (if any). /// <para/> /// If this is a commit, we also call the policy to give it /// a chance to remove other commits. If any commits are /// removed, we decref their files as well. /// </summary> public void Checkpoint(SegmentInfos segmentInfos, bool isCommit) { Debug.Assert(IsLocked); //Debug.Assert(Thread.holdsLock(Writer)); long t0 = 0; if (infoStream.IsEnabled("IFD")) { t0 = Time.NanoTime(); infoStream.Message("IFD", "now checkpoint \"" + writer.SegString(writer.ToLiveInfos(segmentInfos).Segments) + "\" [" + segmentInfos.Count + " segments " + "; isCommit = " + isCommit + "]"); } // Try again now to delete any previously un-deletable // files (because they were in use, on Windows): DeletePendingFiles(); // Incref the files: IncRef(segmentInfos, isCommit); if (isCommit) { // Append to our commits list: commits.Add(new CommitPoint(commitsToDelete, directory, segmentInfos)); // Tell policy so it can remove commits: policy.OnCommit(commits); // Decref files for commits that were deleted by the policy: DeleteCommits(); } else { // DecRef old files from the last checkpoint, if any: DecRef(lastFiles); lastFiles.Clear(); // Save files so we can decr on next checkpoint/commit: lastFiles.AddRange(segmentInfos.GetFiles(directory, false)); } if (infoStream.IsEnabled("IFD")) { long t1 = Time.NanoTime(); infoStream.Message("IFD", ((t1 - t0) / 1000000) + " msec to checkpoint"); } } internal void IncRef(SegmentInfos segmentInfos, bool isCommit) { Debug.Assert(IsLocked); // If this is a commit point, also incRef the // segments_N file: foreach (string fileName in segmentInfos.GetFiles(directory, isCommit)) { IncRef(fileName); } } internal void IncRef(ICollection<string> files) { Debug.Assert(IsLocked); foreach (string file in files) { IncRef(file); } } internal void IncRef(string fileName) { Debug.Assert(IsLocked); RefCount rc = GetRefCount(fileName); if (infoStream.IsEnabled("IFD")) { if (VERBOSE_REF_COUNTS) { infoStream.Message("IFD", " IncRef \"" + fileName + "\": pre-incr count is " + rc.count); } } rc.IncRef(); } internal void DecRef(ICollection<string> files) { Debug.Assert(IsLocked); foreach (string file in files) { DecRef(file); } } internal void DecRef(string fileName) { Debug.Assert(IsLocked); RefCount rc = GetRefCount(fileName); if (infoStream.IsEnabled("IFD")) { if (VERBOSE_REF_COUNTS) { infoStream.Message("IFD", " DecRef \"" + fileName + "\": pre-decr count is " + rc.count); } } if (0 == rc.DecRef()) { // this file is no longer referenced by any past // commit points nor by the in-memory SegmentInfos: DeleteFile(fileName); refCounts.Remove(fileName); } } internal void DecRef(SegmentInfos segmentInfos) { Debug.Assert(IsLocked); foreach (string file in segmentInfos.GetFiles(directory, false)) { DecRef(file); } } public bool Exists(string fileName) { Debug.Assert(IsLocked); // LUCENENET: Using TryGetValue to eliminate extra lookup return refCounts.TryGetValue(fileName, out RefCount value) ? value.count > 0 : false; } private RefCount GetRefCount(string fileName) { Debug.Assert(IsLocked); // LUCENENET: Using TryGetValue to eliminate extra lookup if (!refCounts.TryGetValue(fileName, out RefCount rc)) { rc = new RefCount(fileName); refCounts[fileName] = rc; } return rc; } internal void DeleteFiles(IList<string> files) { Debug.Assert(IsLocked); foreach (string file in files) { DeleteFile(file); } } /// <summary> /// Deletes the specified files, but only if they are new /// (have not yet been incref'd). /// </summary> internal void DeleteNewFiles(ICollection<string> files) { Debug.Assert(IsLocked); foreach (string fileName in files) { // NOTE: it's very unusual yet possible for the // refCount to be present and 0: it can happen if you // open IW on a crashed index, and it removes a bunch // of unref'd files, and then you add new docs / do // merging, and it reuses that segment name. // TestCrash.testCrashAfterReopen can hit this: // LUCENENET: Using TryGetValue to eliminate extra lookup bool got = refCounts.TryGetValue(fileName, out RefCount refCount); if (!got || got && refCount.count == 0) { if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "delete new file \"" + fileName + "\""); } DeleteFile(fileName); } } } internal void DeleteFile(string fileName) { Debug.Assert(IsLocked); EnsureOpen(); try { if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "delete \"" + fileName + "\""); } directory.DeleteFile(fileName); } // if delete fails catch (IOException e) { // Some operating systems (e.g. Windows) don't // permit a file to be deleted while it is opened // for read (e.g. by another process or thread). So // we assume that when a delete fails it is because // the file is open in another process, and queue // the file for subsequent deletion. //Debug.Assert(e.Message.Contains("cannot delete")); if (infoStream.IsEnabled("IFD")) { infoStream.Message("IFD", "unable to remove file \"" + fileName + "\": " + e.ToString() + "; Will re-try later."); } if (deletable == null) { deletable = new List<string>(); } deletable.Add(fileName); // add to deletable } } /// <summary> /// Tracks the reference count for a single index file: /// </summary> private sealed class RefCount { // fileName used only for better assert error messages internal readonly string fileName; internal bool initDone; internal RefCount(string fileName) { this.fileName = fileName; } internal int count; public int IncRef() { if (!initDone) { initDone = true; } else { Debug.Assert(count > 0, Thread.CurrentThread.Name + ": RefCount is 0 pre-increment for file \"" + fileName + "\""); } return ++count; } public int DecRef() { Debug.Assert(count > 0, Thread.CurrentThread.Name + ": RefCount is 0 pre-decrement for file \"" + fileName + "\""); return --count; } } /// <summary> /// Holds details for each commit point. This class is /// also passed to the deletion policy. Note: this class /// has a natural ordering that is inconsistent with /// equals. /// </summary> private sealed class CommitPoint : IndexCommit { internal ICollection<string> files; internal string segmentsFileName; internal bool deleted; internal Directory directory; internal ICollection<CommitPoint> commitsToDelete; internal long generation; internal readonly IDictionary<string, string> userData; internal readonly int segmentCount; public CommitPoint(ICollection<CommitPoint> commitsToDelete, Directory directory, SegmentInfos segmentInfos) { this.directory = directory; this.commitsToDelete = commitsToDelete; userData = segmentInfos.UserData; segmentsFileName = segmentInfos.GetSegmentsFileName(); generation = segmentInfos.Generation; files = segmentInfos.GetFiles(directory, true); segmentCount = segmentInfos.Count; } public override string ToString() { return "IndexFileDeleter.CommitPoint(" + segmentsFileName + ")"; } public override int SegmentCount => segmentCount; public override string SegmentsFileName => segmentsFileName; public override ICollection<string> FileNames => files; public override Directory Directory => directory; public override long Generation => generation; public override IDictionary<string, string> UserData => userData; /// <summary> /// Called only by the deletion policy, to remove this /// commit point from the index. /// </summary> public override void Delete() { if (!deleted) { deleted = true; commitsToDelete.Add(this); } } public override bool IsDeleted => deleted; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Text; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; using Revenj.Common; using Revenj.DatabasePersistence.Postgres.QueryGeneration.Visitors; using Revenj.DomainPatterns; using Revenj.Utility; namespace Revenj.DatabasePersistence.Postgres.QueryGeneration.QueryComposition { public abstract class QueryParts { public readonly IServiceProvider Locator; public readonly IPostgresConverterFactory ConverterFactory; public readonly QueryContext Context; public int CurrentSelectIndex { get; set; } public readonly List<SelectSource> Selects = new List<SelectSource>(); public MainFromClause MainFrom { get; protected set; } public readonly List<JoinClause> Joins = new List<JoinClause>(); public readonly List<AdditionalFromClause> AdditionalJoins = new List<AdditionalFromClause>(); public readonly List<GroupJoinClause> GroupJoins = new List<GroupJoinClause>(); public readonly List<Expression> Conditions = new List<Expression>(); public readonly List<OrderByClause> OrderBy = new List<OrderByClause>(); public readonly List<ResultOperatorBase> ResultOperators = new List<ResultOperatorBase>(); internal readonly List<IQuerySimplification> Simplifications; internal readonly IEnumerable<IExpressionMatcher> ExpressionMatchers; internal readonly IEnumerable<IMemberMatcher> MemberMatchers; internal readonly IEnumerable<IProjectionMatcher> ProjectionMatchers; protected QueryParts( IServiceProvider locator, QueryContext context, IPostgresConverterFactory converterFactory, IEnumerable<IQuerySimplification> simplifications, IEnumerable<IExpressionMatcher> expressionMatchers, IEnumerable<IMemberMatcher> memberMatchers, IEnumerable<IProjectionMatcher> projectionMatchers) { this.Locator = locator; this.ConverterFactory = converterFactory; this.Simplifications = new List<IQuerySimplification>(simplifications); this.ExpressionMatchers = expressionMatchers; this.MemberMatchers = memberMatchers; this.ProjectionMatchers = projectionMatchers; this.Context = context; } public class SelectSource { public IQuerySource QuerySource { get; set; } public Expression Expression { get; set; } public string Sql { get; set; } public string Name { get; set; } public Type ItemType { get; set; } public Func<ResultObjectMapping, BufferedTextReader, IDataReader, object> Instancer { get; set; } } public bool AddSelectPart(IQuerySource qs, string sql, string name, Type type, Func<ResultObjectMapping, BufferedTextReader, IDataReader, object> instancer) { if (Selects.Any(kv => kv.Name == name)) return false; Selects.Add(new SelectSource { QuerySource = qs, Sql = sql, Name = name, ItemType = type, Instancer = instancer }); CurrentSelectIndex++; return true; } public void SetFrom(MainFromClause from) { MainFrom = from; if (from != QuerySourceConverterFactory.GetOriginalSource(from)) TryToSimplifyMainFrom(); } private void TryToSimplifyMainFrom() { var from = MainFrom; var sqe = from.FromExpression as SubQueryExpression; do { from = sqe.QueryModel.MainFromClause; var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(sqe.QueryModel, this); if (subquery.Conditions.Count > 0 || subquery.Joins.Count > 0 || subquery.ResultOperators.Any(it => it is CastResultOperator == false && it is DefaultIfEmptyResultOperator == false) || subquery.AdditionalJoins.Count > 0) return; sqe = from.FromExpression as SubQueryExpression; } while (sqe != null); from.ItemName = MainFrom.ItemName; MainFrom = from; } public void AddJoin(JoinClause join) { Joins.Add(join); } public void AddJoin(AdditionalFromClause join) { AdditionalJoins.Add(join); } public void AddJoin(GroupJoinClause join) { GroupJoins.Add(join); } public void AddCondition(Expression condition) { var cc = condition as ConstantExpression; if (cc == null || cc.Type != typeof(bool) || !(bool)cc.Value) Conditions.Add(condition); } public void AddOrderBy(OrderByClause orderBy) { OrderBy.Add(orderBy); } public void AddResultOperator(ResultOperatorBase resultOperator) { if (resultOperator is CastResultOperator == false) ResultOperators.Add(resultOperator); } public string FormatObject(object value) { if (value == null) return "NULL"; var type = value.GetType(); var serialization = ConverterFactory.GetSerializationFactory(type); if (serialization != null) { ///TODO use BuildTuple with quote method var result = "('" + serialization(value).Replace("'", "''") + "'::"; string source = null; if (value is IIdentifiable || value is IEntity) source = SqlSourceAttribute.FindSource(type); else if (value is ICloneable) source = "\"" + type.Namespace + "\".\"" + type.Name + "\""; if (source == null) throw new FrameworkException("Can't find source for " + type.FullName); return result + source + ").*"; } else if (type.IsEnum) { return "'" + value + "'::\"" + type.Namespace + "\".\"" + type.Name + "\""; } if (NpgsqlTypes.TypeConverter.CanConvert(type)) { var val = NpgsqlTypes.TypeConverter.Convert(type, value); var name = NpgsqlTypes.TypeConverter.GetTypeName(type); return val + "::" + name; } //TODO probably wrong. better to throw an exception!? return value.ToString(); } public string FormatArray(object[] values) { if (values == null || values.Length == 0) throw new FrameworkException("Array must have elements!"); var element = values[0].GetType(); var converter = ConverterFactory.GetSerializationFactory(element); if (converter != null) { var source = SqlSourceAttribute.FindSource(element) ?? "\"" + element.Namespace + "\".\"" + element.Name + "\""; var arr = Postgres.PostgresTypedArray.ToArray(values, converter); return arr + "::" + source + "[]"; } if (NpgsqlTypes.TypeConverter.CanConvert(element)) { var val = Postgres.PostgresTypedArray.ToArray( values, v => NpgsqlTypes.TypeConverter.Convert(element, v)); var name = NpgsqlTypes.TypeConverter.GetTypeName(element); return val + "::" + name + "[]"; } throw new NotSupportedException("Don't know how to convert array!"); } public string GetSqlExpression(Expression expression) { return GetSqlExpression(expression, Context); } public string GetSqlExpression(Expression expression, QueryContext context) { return SqlGeneratorExpressionTreeVisitor.GetSqlExpression(expression, this, context); } private static bool EndsWithQuerySource(MemberExpression me) { return me != null && (me.Expression is QuerySourceReferenceExpression || EndsWithQuerySource(me.Expression as MemberExpression)); } public string GetFromPart() { if (MainFrom == null) throw new InvalidOperationException("A query must have a from part"); var sb = new StringBuilder(); if (AdditionalJoins.Any(it => EndsWithQuerySource(it.FromExpression as MemberExpression))) sb.AppendFormat("FROM ({0}) sq ", GetInnerFromPart()); else sb.AppendFormat("FROM {0}", GetQuerySourceFromExpression(MainFrom.ItemName, MainFrom.ItemType, MainFrom.FromExpression)); var emptyJoins = (from j in AdditionalJoins let sqe = j.FromExpression as SubQueryExpression where sqe != null && sqe.QueryModel.ResultOperators.Count == 1 && sqe.QueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator select new { j, sqe }) .ToList(); var groupPairs = (from aj in emptyJoins let mfe = aj.sqe.QueryModel.MainFromClause.FromExpression as QuerySourceReferenceExpression where mfe != null select new { aj.j, g = mfe.ReferencedQuerySource }) .ToList(); foreach (var aj in AdditionalJoins) { var me = aj.FromExpression as MemberExpression; if (EndsWithQuerySource(me)) continue; if (groupPairs.Any(it => it.j == aj)) continue; var ej = emptyJoins.Find(it => it.j == aj); if (ej != null) { var qm = ej.sqe.QueryModel; var sel = qm.SelectClause.Selector as QuerySourceReferenceExpression; if (sel != null && sel.ReferencedQuerySource.Equals(qm.MainFromClause) && qm.BodyClauses.Count > 0) { var wc = qm.BodyClauses.Where(it => it is WhereClause).Cast<WhereClause>().ToList(); if (wc.Count == qm.BodyClauses.Count) { var mfc = qm.MainFromClause; mfc.ItemName = aj.ItemName; sb.AppendFormat("{0} LEFT JOIN {1} ON {2}", Environment.NewLine, GetQuerySourceFromExpression(mfc.ItemName, mfc.ItemType, mfc.FromExpression), string.Join(" AND ", wc.Select(it => GetSqlExpression(it.Predicate)))); continue; } } } sb.AppendFormat("{0} CROSS JOIN {1}", Environment.NewLine, GetQuerySourceFromExpression(aj.ItemName, aj.ItemType, aj.FromExpression)); } foreach (var j in Joins) { sb.AppendFormat("{0} INNER JOIN {1} ON ({2}) = ({3}){0}", Environment.NewLine, GetQuerySourceFromExpression(j.ItemName, j.ItemType, j.InnerSequence), GetSqlExpression(j.InnerKeySelector), GetSqlExpression(j.OuterKeySelector)); } foreach (var gj in GroupJoins) { var aj = groupPairs.FirstOrDefault(it => it.g == gj); if (aj == null) throw new FrameworkException("Can't find group join part!"); gj.ItemName = aj.j.ItemName; gj.JoinClause.ItemName = aj.j.ItemName; sb.AppendFormat("{0} LEFT JOIN {1} ON ({2}) = ({3}){0}", Environment.NewLine, GetQuerySourceFromExpression(gj.ItemName, gj.ItemType, gj.JoinClause.InnerSequence), GetSqlExpression(gj.JoinClause.InnerKeySelector), GetSqlExpression(gj.JoinClause.OuterKeySelector)); } sb.AppendLine(); return sb.ToString(); } private string GetInnerFromPart() { var sb = new StringBuilder("SELECT "); sb.AppendFormat("\"{0}\"", MainFrom.ItemName); foreach (var aj in AdditionalJoins) { var me = aj.FromExpression as MemberExpression; if (me != null) { var src = BuildMemberPath(me, false); if (src != null) sb.AppendFormat(", unnest({0}) AS \"{1}\"", src, aj.ItemName); } } sb.AppendFormat(" FROM {0}", GetQuerySourceFromExpression(MainFrom.ItemName, MainFrom.ItemType, MainFrom.FromExpression)); return sb.ToString(); } public string GetWherePart() { if (Conditions.Count == 0) return string.Empty; var whereConditions = new List<string>(Conditions.Count); foreach (var c in Conditions) whereConditions.Add(GetSqlExpression(c)); return @"WHERE " + string.Join(Environment.NewLine + " AND ", whereConditions) + @" "; } public string GetOrderPart() { return OrderBy.Count == 0 ? string.Empty : @"ORDER BY {0} ".With(string.Join(@", ", OrderBy.Last().Orderings.Select(o => GetSqlExpression(o.Expression) + (o.OrderingDirection == OrderingDirection.Desc ? " DESC " : " ASC ")))); } private string BuildMemberPath(MemberExpression me, bool nest) { var list = new List<string>(); while (me != null) { list.Add(ConverterFactory.GetName(me.Member)); var qse = me.Expression as QuerySourceReferenceExpression; var par = me.Expression as ParameterExpression; if (qse != null || par != null) { var sb = new StringBuilder(); var name = qse != null ? qse.ReferencedQuerySource.ItemName : par.Name; if (par != null && !string.IsNullOrEmpty(Context.Name)) sb.Append(Context.Name); sb.Append('"').Append(name).Append('"'); list.Reverse(); foreach (var m in list) { if (nest) { sb.Insert(0, '('); sb.Append(')'); } sb.Append(".\"").Append(m).Append("\""); } return sb.ToString(); } me = me.Expression as MemberExpression; } return null; } //TODO vjerojatno ponekad ne treba ignorirati expression public string GetQuerySourceFromExpression(string name, Type type, Expression fromExpression) { var me = fromExpression as MemberExpression; if (me != null) { var src = BuildMemberPath(me, true); if (src != null) return @"(SELECT sq AS ""{1}"" FROM unnest({0}) sq) AS ""{1}""".With(src, name); } var sqe = fromExpression as SubQueryExpression; if (sqe != null) { if (sqe.QueryModel.CanUseMain()) return GetQuerySourceFromExpression(name, type, sqe.QueryModel.MainFromClause.FromExpression); //TODO hack za replaceanje generiranog id-a var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(sqe.QueryModel, this); var grouping = sqe.QueryModel.ResultOperators.FirstOrDefault(it => it is GroupResultOperator) as GroupResultOperator; if (grouping == null && subquery.Selects.Count == 1) { if (sqe.QueryModel.ResultOperators.Any(it => it is UnionResultOperator || it is ConcatResultOperator)) { var ind = subquery.Selects[0].Sql.IndexOf(" AS "); if (ind > 0) { var asName = subquery.Selects[0].Sql.Substring(ind + 4).Trim().Replace("\"", ""); if (asName != name) subquery.Selects[0].Sql = subquery.Selects[0].Sql.Substring(0, ind + 4) + "\"" + name + "\""; } else { subquery.Selects[0].Sql = subquery.Selects[0].Sql + " AS \"" + name + "\""; } return "(" + subquery.BuildSqlString(true) + ") \"" + name + "\""; } return "(" + subquery.BuildSqlString(true).Replace("\"" + sqe.QueryModel.MainFromClause.ItemName + "\"", "\"" + name + "\"") + ") \"" + name + "\""; } return "(" + subquery.BuildSqlString(true) + ") \"" + name + "\""; } var ce = fromExpression as ConstantExpression; if (ce != null) { var queryable = ce.Value as IQueryable; if (queryable != null) return GetQueryableExpression(name, queryable); if (ce.Type.IsArray || ce.Value is Array) return FormatStringArray(ce.Value, name, ce.Type); else if (ce.Value is IEnumerable) return FormatStringEnumerable(ce.Value, name, ce.Type); return "(SELECT {0} AS \"{1}\") AS \"{1}\"".With(ce.Value, name); } var nae = fromExpression as NewArrayExpression; if (nae != null) { if (nae.Expressions.Count == 0) //TODO support for zero throw new NotSupportedException("Expecting NewArray expressions. None found"); var inner = string.Join(" UNION ALL ", nae.Expressions.Select(it => "SELECT {0} AS \"{1}\"".With(GetSqlExpression(it), name))); return "(" + inner + ") AS \"{0}\" ".With(name); } if (fromExpression is QuerySourceReferenceExpression && fromExpression.Type.IsGrouping()) { var qse = fromExpression as QuerySourceReferenceExpression; return "(SELECT (\"{0}\".\"Values\")[i].* FROM generate_series(1, array_upper(\"{0}\".\"Values\", 1)) i) AS \"{1}\"".With( qse.ReferencedQuerySource.ItemName, name); } var pe = fromExpression as ParameterExpression; if (pe != null) return "UNNEST({0}\"{1}\") AS \"{2}\"".With(Context.Name, pe.Name, name); return FromSqlSource(name, type); } private string GetQueryableExpression(string name, IQueryable queryable) { var ce = queryable.Expression as ConstantExpression; if (ce != null) { if (ce.Type.IsGenericType) { var gtd = ce.Type.GetGenericTypeDefinition(); if (gtd == typeof(Queryable<>)) return FromSqlSource(name, ce.Type.GetGenericArguments()[0]); if (gtd == typeof(IQueryable<>)) return GetQuerySourceFromExpression(name, queryable.ElementType, queryable.Expression); } if (ce.Type.IsArray || ce.Value is Array) return FormatStringArray(ce.Value, name, ce.Type); else if (ce.Value is IEnumerable) return FormatStringEnumerable(ce.Value, name, ce.Type); //TODO this doesn't work most of the cases return "(SELECT {0} AS \"{1}\") AS \"{1}\"".With(ce.Value, name); } var mce = queryable.Expression as MethodCallExpression; if (mce != null && mce.Method.DeclaringType == typeof(System.Linq.Queryable) && mce.Method.Name == "Cast") return GetQuerySourceFromExpression(name, queryable.ElementType, mce.Arguments[0]); throw new NotSupportedException("unknown query source expression!"); } private static string FromSqlSource(string name, Type type) { var source = SqlSourceAttribute.FindSource(type); if (!string.IsNullOrEmpty(source)) return "{0} AS \"{1}\"".With(source, name); throw new NotSupportedException(@"Unknown sql source {0}! Add {1} attribute or {2} or {3} or {4} interface".With( type.FullName, typeof(SqlSourceAttribute).FullName, typeof(IAggregateRoot).FullName, typeof(IIdentifiable).FullName, typeof(IEntity).FullName)); } class ColumnValue { public string Name; public Type Type; public Func<object, object> GetValue; public ColumnValue(System.Reflection.PropertyInfo pi) { Name = pi.Name; Type = pi.PropertyType; GetValue = (object v) => pi.GetValue(v, null); } public ColumnValue(System.Reflection.FieldInfo fi) { Name = fi.Name; Type = fi.FieldType; GetValue = (object v) => fi.GetValue(v); } public string GetBackendValue(object value) { return NpgsqlTypes.TypeConverter.Convert(Type, GetValue(value)); } } private string FormatStringArray(object value, string name, Type type) { if (value != null) { var array = ((Array)value).Cast<object>().ToArray(); if (array.Length > 0) return FormatStringValues(name, type, array); } if (value != null) type = value.GetType(); var elementType = type.GetElementType(); if (NpgsqlTypes.TypeConverter.CanConvert(elementType)) return "(SELECT * FROM unnest(array[]::{1}[]) AS \"{0}\") AS \"{0}\"".With( name, NpgsqlTypes.TypeConverter.GetTypeName(elementType)); return "(SELECT * FROM {1} LIMIT 0) AS \"{0}\"".With(name, FromSqlSource("sq", elementType)); } private string FormatStringEnumerable(object value, string name, Type type) { if (value != null) { var array = ((IEnumerable)value).Cast<object>().ToArray(); if (array.Length > 0) return FormatStringValues(name, type, array); } if (value != null) type = value.GetType(); var elementType = type.IsArray ? type.GetElementType() : type.IsGenericType ? type.GetGenericArguments()[0] : null; if (elementType == null) throw new NotSupportedException("Unknown source type: " + type.FullName); if (NpgsqlTypes.TypeConverter.CanConvert(elementType)) return "(SELECT * FROM unnest(array[]::{1}[]) AS \"{0}\") AS \"{0}\"".With( name, NpgsqlTypes.TypeConverter.GetTypeName(elementType)); return "(SELECT * FROM {1} LIMIT 0) AS \"{0}\"".With(name, FromSqlSource("sq", elementType)); } private string FormatStringValues(string name, Type type, object[] array) { Type element = null; if (type.IsGenericType || type.IsArray) { element = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; var converter = ConverterFactory.GetSerializationFactory(element); if (converter != null) { var source = SqlSourceAttribute.FindSource(element) ?? "\"" + element.Namespace + "\".\"" + element.Name + "\""; var arr = Postgres.PostgresTypedArray.ToArray(array, converter); return @"(SELECT ""{2}"" FROM unnest({0}::{1}[]) ""{2}"") ""{2}""".With( arr, source, name); } else if (!NpgsqlTypes.TypeConverter.CanConvert(element)) { var fields = element.GetFields().Select(it => new ColumnValue(it)); var properties = element.GetProperties().Select(it => new ColumnValue(it)); var columns = fields.Union(properties).ToList(); return "(SELECT " + string.Join(", ", columns.Select((it, ind) => "column{0} AS \"{1}\"".With(ind + 1, it.Name))) + " FROM (VALUES" + string.Join( ", ", array.Select(it => "(" + string.Join(", ", columns.Select(c => c.GetBackendValue(it))) + ")")) + ") _sq1 ) \"" + name + "\""; } } var formated = (from i in array select FormatObject(i)).ToList(); var typeAlias = element != null && NpgsqlTypes.TypeConverter.CanConvert(element) ? "::" + NpgsqlTypes.TypeConverter.GetTypeName(element) : string.Empty; return "(SELECT {0}{1} AS \"{2}\"{3}) AS \"{2}\"".With( formated[0], typeAlias, name, string.Concat(formated.Skip(1).Select(it => " UNION ALL SELECT " + it))); } protected virtual void ProcessResultOperators(StringBuilder sb) { ProcessSetOperators( sb, ResultOperators .Where(it => it is ExceptResultOperator || it is IntersectResultOperator || it is UnionResultOperator || it is ConcatResultOperator) .ToList()); ProcessGroupOperators( sb, ResultOperators.FindAll(it => it is GroupResultOperator).Cast<GroupResultOperator>().ToList()); ProcessLimitAndOffsetOperators( sb, ResultOperators.FindAll(it => it is TakeResultOperator).Cast<TakeResultOperator>().ToList(), ResultOperators.FindAll(it => it is SkipResultOperator).Cast<SkipResultOperator>().ToList(), ResultOperators.FindAll(it => it is FirstResultOperator).Cast<FirstResultOperator>().ToList(), ResultOperators.FindAll(it => it is SingleResultOperator).Cast<SingleResultOperator>().ToList()); ProcessInOperators( sb, ResultOperators.FindAll(it => it is ContainsResultOperator).Cast<ContainsResultOperator>().ToList()); ProcessAllOperators( sb, ResultOperators.FindAll(it => it is AllResultOperator).Cast<AllResultOperator>().ToList()); if (ResultOperators.Exists(it => it is CountResultOperator || it is LongCountResultOperator)) ProcessCountOperators(sb); if (ResultOperators.Exists(it => it is AnyResultOperator)) ProcessAnyOperators(sb); } private void ProcessSetOperators(StringBuilder sb, List<ResultOperatorBase> operators) { foreach (var it in operators) { sb.AppendLine(); var ero = it as ExceptResultOperator; var iro = it as IntersectResultOperator; var uro = it as UnionResultOperator; var cro = it as ConcatResultOperator; if (ero != null) { sb.AppendLine("EXCEPT"); sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(ero.Source2, this)); } else if (iro != null) { sb.AppendLine("INTERSECT"); sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(iro.Source2, this)); } else { if (OrderBy.Count > 0) { sb.Insert(0, '('); sb.AppendLine(")"); } SubQueryExpression sqe; if (uro != null) { sb.AppendLine("UNION"); sqe = uro.Source2 as SubQueryExpression; } else { sb.AppendLine("UNION ALL"); sqe = cro.Source2 as SubQueryExpression; } foreach (var ro in ResultOperators) { if (ro is UnionResultOperator == false && ro is ConcatResultOperator == false) sqe.QueryModel.ResultOperators.Add(ro); } sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(sqe, this)); } } } protected virtual void ProcessGroupOperators(StringBuilder sb, List<GroupResultOperator> groupBy) { if (groupBy.Count > 1) throw new FrameworkException("More than one group operator!?"); else if (groupBy.Count == 1) { var group = groupBy[0]; sb.AppendLine("GROUP BY"); sb.AppendLine(GetSqlExpression(group.KeySelector)); } } protected virtual void ProcessLimitAndOffsetOperators( StringBuilder sb, List<TakeResultOperator> limit, List<SkipResultOperator> offset, List<FirstResultOperator> first, List<SingleResultOperator> single) { if (first.Count == 1) { sb.AppendLine("LIMIT 1"); if (offset.Count == 1) sb.AppendLine("OFFSET " + GetSqlExpression(offset[0].Count)); } else if (single.Count == 1) { if (limit.Count == 0) sb.Append("LIMIT 2"); else { if (limit.TrueForAll(it => it.Count is ConstantExpression)) { var min = limit.Min(it => (int)(it.Count as ConstantExpression).Value); if (min > 1) min = 2; sb.Append("LIMIT ").Append(min); } else { sb.Append("LIMIT LEAST(2,"); sb.Append(string.Join(", ", limit.Select(it => GetSqlExpression(it.Count)))); sb.AppendLine(")"); } } if (offset.Count == 1) sb.AppendLine("OFFSET " + GetSqlExpression(offset[0].Count)); } else if (limit.Count > 0 && offset.Count == 0) { sb.Append("LIMIT "); if (limit.Count > 1) sb.Append("LEAST(") .Append( string.Join( ", ", limit.Select(it => GetSqlExpression(it.Count)))) .AppendLine(")"); else sb.AppendLine(GetSqlExpression(limit[0].Count)); } else if (limit.Count == 0 && offset.Count > 0) { sb.AppendLine("OFFSET " + GetSqlExpression(offset[0].Count)); for (int i = 1; i < offset.Count; i++) sb.Append(" + " + GetSqlExpression(offset[i].Count)); } else if (limit.Count == 1 && offset.Count == 1) { if (ResultOperators.IndexOf(limit[0]) < ResultOperators.IndexOf(offset[0])) sb.AppendLine("LIMIT ({0} - {1})".With(GetSqlExpression(limit[0].Count), GetSqlExpression(offset[0].Count))); else sb.AppendLine("LIMIT " + GetSqlExpression(limit[0].Count)); sb.AppendLine("OFFSET " + GetSqlExpression(offset[0].Count)); } else if (limit.Count > 1 || offset.Count > 1) throw new NotSupportedException("Unsupported combination of limits and offsets in query. More than one offset and more than one limit found."); } protected virtual void ProcessInOperators(StringBuilder sb, List<ContainsResultOperator> contains) { if (contains.Count > 1) throw new FrameworkException("More than one contains operator!?"); else if (contains.Count == 1) { sb.Insert(0, GetSqlExpression(contains[0].Item) + " IN ("); sb.Append(")"); } } protected virtual void ProcessAllOperators(StringBuilder sb, List<AllResultOperator> all) { if (all.Count > 1) throw new FrameworkException("More than one all operator!?"); else if (all.Count == 1) { sb.Insert(0, "SELECT NOT EXISTS(SELECT * FROM ("); var where = GetSqlExpression(all[0].Predicate); sb.Append(") sq WHERE (" + where + ") = false)"); } } protected virtual void ProcessCountOperators(StringBuilder sb) { sb.Insert(0, "SELECT COUNT(*) FROM ("); sb.Append(") sq "); } protected virtual void ProcessAnyOperators(StringBuilder sb) { sb.Insert(0, "SELECT EXISTS("); sb.Append(") sq "); Selects.Clear(); CurrentSelectIndex = 0; AddSelectPart(MainFrom, sb.ToString(), "sq", typeof(bool), (_, __, dr) => dr.GetBoolean(0)); } protected string BuildCountQuery(ResultOperatorBase countOperator) { Selects.Clear(); CurrentSelectIndex = 0; var sb = new StringBuilder(); sb.Append("SELECT "); if (countOperator is LongCountResultOperator) { AddSelectPart(MainFrom, "COUNT(*)", "count", typeof(long), (_, __, dr) => dr.GetInt64(0)); sb.AppendLine("COUNT(*)"); } else { AddSelectPart(MainFrom, "COUNT(*)::int", "count", typeof(int), (_, __, dr) => dr.GetInt32(0)); sb.AppendLine("COUNT(*)::int"); } sb.Append(GetFromPart()); sb.Append(GetWherePart()); return sb.ToString(); } } }
using System; using System.Text; using GammaJul.ReSharper.ForTea.Psi.Directives; using GammaJul.ReSharper.ForTea.Tree; using JetBrains.Annotations; using JetBrains.Application; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; namespace GammaJul.ReSharper.ForTea.Psi { /// <summary>This class generates a code-behind file from C# embedded statements and directives in the T4 file.</summary> internal sealed class T4CSharpCodeGenerator : IRecursiveElementProcessor { internal const string CodeCommentStart = "/*_T4\x200CCodeStart_*/"; internal const string CodeCommentEnd = "/*_T4\x200CCodeEnd_*/"; internal const string ClassName = "Generated\x200CTransformation"; internal const string DefaultBaseClassName = "Microsoft.VisualStudio.TextTemplating.TextTransformation"; internal const string TransformTextMethodName = "TransformText"; [NotNull] private readonly IT4File _file; [NotNull] private readonly DirectiveInfoManager _directiveInfoManager; [NotNull] private readonly GenerationResult _usingsResult; [NotNull] private readonly GenerationResult _parametersResult; [NotNull] private readonly GenerationResult _inheritsResult; [NotNull] private readonly GenerationResult _transformTextResult; [NotNull] private readonly GenerationResult _featureResult; private int _includeDepth; private bool _rootFeatureStarted; private bool _hasHost; bool IRecursiveElementProcessor.InteriorShouldBeProcessed(ITreeNode element) => element is IT4CodeBlock || element is IT4Include; void IRecursiveElementProcessor.ProcessBeforeInterior(ITreeNode element) { if (element is IT4Include) ++_includeDepth; } void IRecursiveElementProcessor.ProcessAfterInterior(ITreeNode element) { switch (element) { case IT4Include _: --_includeDepth; return; case IT4Directive directive: HandleDirective(directive); return; case IT4CodeBlock codeBlock: HandleCodeBlock(codeBlock); break; } } bool IRecursiveElementProcessor.ProcessingIsFinished { get { InterruptableActivityCookie.CheckAndThrow(); return false; } } /// <summary>Handles a directive in the tree.</summary> /// <param name="directive">The directive.</param> private void HandleDirective([NotNull] IT4Directive directive) { if (directive.IsSpecificDirective(_directiveInfoManager.Import)) HandleImportDirective(directive); else if (directive.IsSpecificDirective(_directiveInfoManager.Template)) HandleTemplateDirective(directive); else if (directive.IsSpecificDirective(_directiveInfoManager.Parameter)) HandleParameterDirective(directive); } /// <summary>Handles an import directive, equivalent of an using directive in C#.</summary> /// <param name="directive">The import directive.</param> private void HandleImportDirective([NotNull] IT4Directive directive) { Pair<IT4Token, string> ns = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Import.NamespaceAttribute.Name); if (ns.First == null || ns.Second == null) return; _usingsResult.Builder.Append("using "); _usingsResult.AppendMapped(ns.Second, ns.First.GetTreeTextRange()); _usingsResult.Builder.AppendLine(";"); } /// <summary>Handles a template directive, determining if we should output a Host property and use a base class.</summary> /// <param name="directive">The template directive.</param> private void HandleTemplateDirective([NotNull] IT4Directive directive) { string value = directive.GetAttributeValue(_directiveInfoManager.Template.HostSpecificAttribute.Name); _hasHost = Boolean.TrueString.Equals(value, StringComparison.OrdinalIgnoreCase); (IT4Token classNameToken, string className) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Template.InheritsAttribute.Name); if (classNameToken != null && className != null) _inheritsResult.AppendMapped(className, classNameToken.GetTreeTextRange()); } /// <summary>Handles a parameter directive, outputting an extra property.</summary> /// <param name="directive">The parameter directive.</param> private void HandleParameterDirective([NotNull] IT4Directive directive) { (IT4Token typeToken, string type) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Parameter.TypeAttribute.Name); if (typeToken == null || type == null) return; (IT4Token nameToken, string name) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Parameter.NameAttribute.Name); if (nameToken == null || name == null) return; StringBuilder builder = _parametersResult.Builder; builder.Append("[System.CodeDom.Compiler.GeneratedCodeAttribute] private global::"); _parametersResult.AppendMapped(type, typeToken.GetTreeTextRange()); builder.Append(' '); _parametersResult.AppendMapped(name, nameToken.GetTreeTextRange()); builder.Append(" { get { return default(global::"); builder.Append(type); builder.AppendLine("); } }"); } /// <summary> /// Handles a code block: depending of whether it's a feature or transform text result, /// it is not added to the same part of the C# file. /// </summary> /// <param name="codeBlock">The code block.</param> private void HandleCodeBlock([NotNull] IT4CodeBlock codeBlock) { IT4Token codeToken = codeBlock.GetCodeToken(); if (codeToken == null) return; GenerationResult result; var expressionBlock = codeBlock as T4ExpressionBlock; if (expressionBlock != null) { result = _rootFeatureStarted && _includeDepth == 0 ? _featureResult : _transformTextResult; result.Builder.Append("this.Write(__\x200CToString("); } else { if (codeBlock is T4FeatureBlock) { if (_includeDepth == 0) _rootFeatureStarted = true; result = _featureResult; } else result = _transformTextResult; } result.Builder.Append(CodeCommentStart); result.AppendMapped(codeToken); result.Builder.Append(CodeCommentEnd); if (expressionBlock != null) result.Builder.Append("));"); result.Builder.AppendLine(); } /// <summary>Gets the namespace of the current T4 file. This is always <c>null</c> for a standard (non-preprocessed) file.</summary> /// <returns>A namespace, or <c>null</c>.</returns> [CanBeNull] private string GetNamespace() { IPsiSourceFile sourceFile = _file.GetSourceFile(); IProjectFile projectFile = sourceFile?.ToProjectFile(); if (projectFile == null || !projectFile.IsPreprocessedT4Template()) return null; string ns = projectFile.GetCustomToolNamespace(); if (!String.IsNullOrEmpty(ns)) return ns; return sourceFile.Properties.GetDefaultNamespace(); } /// <summary>Generates a new C# code behind.</summary> /// <returns>An instance of <see cref="GenerationResult"/> containing the C# file.</returns> [NotNull] public GenerationResult Generate() { _file.ProcessDescendants(this); var result = new GenerationResult(_file); StringBuilder builder = result.Builder; string ns = GetNamespace(); bool hasNamespace = !String.IsNullOrEmpty(ns); if (hasNamespace) { builder.AppendFormat("namespace {0} {{", ns); builder.AppendLine(); } builder.AppendLine("using System;"); result.Append(_usingsResult); builder.AppendFormat("[{0}]", SyntheticAttribute.Name); builder.AppendLine(); builder.AppendFormat("public class {0} : ", ClassName); if (_inheritsResult.Builder.Length == 0) builder.Append(DefaultBaseClassName); else result.Append(_inheritsResult); builder.AppendLine(" {"); builder.AppendFormat("[{0}] private static string __\x200CToString(object value) {{ return null; }}", SyntheticAttribute.Name); builder.AppendLine(); if (_hasHost) builder.AppendLine("public virtual Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost Host { get; set; }"); result.Append(_parametersResult); builder.AppendFormat("[System.CodeDom.Compiler.GeneratedCodeAttribute] public override string {0}() {{", TransformTextMethodName); builder.AppendLine(); result.Append(_transformTextResult); builder.AppendLine(); builder.AppendLine("return GenerationEnvironment.ToString();"); builder.AppendLine("}"); result.Append(_featureResult); builder.AppendLine("}"); if (hasNamespace) builder.AppendLine("}"); return result; } /// <summary>Initializes a new instance of the <see cref="T4CSharpCodeGenerator"/> class.</summary> /// <param name="file">The associated T4 file whose C# code behind will be generated.</param> /// <param name="directiveInfoManager">An instance of <see cref="DirectiveInfoManager"/>.</param> public T4CSharpCodeGenerator([NotNull] IT4File file, [NotNull] DirectiveInfoManager directiveInfoManager) { _file = file; _directiveInfoManager = directiveInfoManager; _usingsResult = new GenerationResult(file); _parametersResult = new GenerationResult(file); _inheritsResult = new GenerationResult(file); _transformTextResult = new GenerationResult(file); _featureResult = new GenerationResult(file); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Params.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. #pragma warning disable 1717 namespace Org.Apache.Http.Params { /// <java-name> /// org/apache/http/params/HttpAbstractParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpAbstractParamBean", AccessFlags = 1057)] public abstract partial class HttpAbstractParamBean /* scope: __dot42__ */ { /// <java-name> /// params /// </java-name> [Dot42.DexImport("params", "Lorg/apache/http/params/HttpParams;", AccessFlags = 20)] protected internal readonly global::Org.Apache.Http.Params.IHttpParams Params; [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpAbstractParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpAbstractParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_TIMEOUT </para></para> /// </summary> /// <java-name> /// SO_TIMEOUT /// </java-name> [Dot42.DexImport("SO_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_TIMEOUT = "http.socket.timeout"; /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. </para><para>This parameter expects a value of type Boolean. </para><para><para>java.net.SocketOptions::TCP_NODELAY </para></para> /// </summary> /// <java-name> /// TCP_NODELAY /// </java-name> [Dot42.DexImport("TCP_NODELAY", "Ljava/lang/String;", AccessFlags = 25)] public const string TCP_NODELAY = "http.tcp.nodelay"; /// <summary> /// <para>Determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// SOCKET_BUFFER_SIZE /// </java-name> [Dot42.DexImport("SOCKET_BUFFER_SIZE", "Ljava/lang/String;", AccessFlags = 25)] public const string SOCKET_BUFFER_SIZE = "http.socket.buffer-size"; /// <summary> /// <para>Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used. The setting only affects socket close. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_LINGER </para></para> /// </summary> /// <java-name> /// SO_LINGER /// </java-name> [Dot42.DexImport("SO_LINGER", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_LINGER = "http.socket.linger"; /// <summary> /// <para>Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// CONNECTION_TIMEOUT /// </java-name> [Dot42.DexImport("CONNECTION_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_TIMEOUT = "http.connection.timeout"; /// <summary> /// <para>Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STALE_CONNECTION_CHECK /// </java-name> [Dot42.DexImport("STALE_CONNECTION_CHECK", "Ljava/lang/String;", AccessFlags = 25)] public const string STALE_CONNECTION_CHECK = "http.connection.stalecheck"; /// <summary> /// <para>Determines the maximum line length limit. If set to a positive value, any HTTP line exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_LINE_LENGTH /// </java-name> [Dot42.DexImport("MAX_LINE_LENGTH", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_LINE_LENGTH = "http.connection.max-line-length"; /// <summary> /// <para>Determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_HEADER_COUNT /// </java-name> [Dot42.DexImport("MAX_HEADER_COUNT", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_HEADER_COUNT = "http.connection.max-header-count"; } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537)] public partial interface ICoreConnectionPNames /* scope: __dot42__ */ { } /// <java-name> /// org/apache/http/params/HttpProtocolParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParamBean", AccessFlags = 33)] public partial class HttpProtocolParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpProtocolParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetHttpElementCharset(string httpElementCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetContentCharset(string contentCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/HttpVersion;)V", AccessFlags = 1)] public virtual void SetVersion(global::Org.Apache.Http.HttpVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetUserAgent(string userAgent) /* MethodBuilder.Create */ { } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Z)V", AccessFlags = 1)] public virtual void SetUseExpectContinue(bool useExpectContinue) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpProtocolParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <java-name> /// org/apache/http/params/HttpConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParamBean", AccessFlags = 33)] public partial class HttpConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(I)V", AccessFlags = 1)] public virtual void SetSoTimeout(int soTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Z)V", AccessFlags = 1)] public virtual void SetTcpNoDelay(bool tcpNoDelay) /* MethodBuilder.Create */ { } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(I)V", AccessFlags = 1)] public virtual void SetSocketBufferSize(int socketBufferSize) /* MethodBuilder.Create */ { } /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(I)V", AccessFlags = 1)] public virtual void SetLinger(int linger) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(I)V", AccessFlags = 1)] public virtual void SetConnectionTimeout(int connectionTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Z)V", AccessFlags = 1)] public virtual void SetStaleCheckingEnabled(bool staleCheckingEnabled) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>An adaptor for accessing connection parameters in HttpParams. <br></br> Note that the <b>implements</b> relation to CoreConnectionPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpConnectionParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParams", AccessFlags = 49)] public sealed partial class HttpConnectionParams : global::Org.Apache.Http.Params.ICoreConnectionPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpConnectionParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds </para> /// </returns> /// <java-name> /// getSoTimeout /// </java-name> [Dot42.DexImport("getSoTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if Nagle's algorithm is to be used.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// getTcpNoDelay /// </java-name> [Dot42.DexImport("getTcpNoDelay", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool GetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption.</para><para></para> /// </summary> /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getSocketBufferSize /// </java-name> [Dot42.DexImport("getSocketBufferSize", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params, int size) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns linger-on-close timeout. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <returns> /// <para>the linger-on-close timeout </para> /// </returns> /// <java-name> /// getLinger /// </java-name> [Dot42.DexImport("getLinger", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetLinger(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetLinger(global::Org.Apache.Http.Params.IHttpParams @params, int value) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getConnectionTimeout /// </java-name> [Dot42.DexImport("getConnectionTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if stale connection check is to be used, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isStaleCheckingEnabled /// </java-name> [Dot42.DexImport("isStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Represents a collection of HTTP protocol and framework parameters.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpParams", AccessFlags = 1537)] public partial interface IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the value of the given parameter.</para><para><para>setParameter(String, Object) </para></para> /// </summary> /// <returns> /// <para>an object that represents the value of the parameter, <code>null</code> if the parameter is not set or if it is explicitly set to <code>null</code></para> /// </returns> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] object GetParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns the value to the parameter with the given name.</para><para></para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a copy of these parameters.</para><para></para> /// </summary> /// <returns> /// <para>a new set of parameters holding the same values as this one </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool RemoveParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Long parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setLongParameter(String, long) </para></para> /// </summary> /// <returns> /// <para>a Long that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1025)] long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Long to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns an Integer parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setIntParameter(String, int) </para></para> /// </summary> /// <returns> /// <para>a Integer that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1025)] int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns an Integer to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Double parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setDoubleParameter(String, double) </para></para> /// </summary> /// <returns> /// <para>a Double that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1025)] double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Double to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Boolean parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setBooleanParameter(String, boolean) </para></para> /// </summary> /// <returns> /// <para>a Boolean that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1025)] bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Boolean to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is set to <code>true</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is set to value <code>true</code>, <code>false</code> if it is not set or set to <code>false</code> </para> /// </returns> /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterTrue(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is not set or <code>false</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is either not set or set to value <code>false</code>, <code>false</code> if it is set to <code>true</code> </para> /// </returns> /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterFalse(string name) /* MethodBuilder.Create */ ; } /// <summary> /// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/DefaultedHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)] public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of the local collection with the same default </para> /// </summary> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para> /// </summary> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDefaults /// </java-name> [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public global::Org.Apache.Http.Params.IHttpParams GetDefaults() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal DefaultedHttpParams() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getDefaults /// </java-name> public global::Org.Apache.Http.Params.IHttpParams Defaults { [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] get{ return GetDefaults(); } } } /// <summary> /// <para>Abstract base class for parameter collections. Type specific setters and getters are mapped to the abstract, generic getters and setters.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>542224 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/AbstractHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/AbstractHttpParams", AccessFlags = 1057)] public abstract partial class AbstractHttpParams : global::Org.Apache.Http.Params.IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Instantiates parameters. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1)] public virtual long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ { return default(long); } /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1)] public virtual double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ { return default(double); } /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1)] public virtual bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterTrue(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterFalse(string name) /* MethodBuilder.Create */ { return default(bool); } [Dot42.DexImport("org/apache/http/params/HttpParams", "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] public virtual object GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(object); } [Dot42.DexImport("org/apache/http/params/HttpParams", "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams Copy() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public virtual bool RemoveParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreProtocolPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the protocol version used per default. </para><para>This parameter expects a value of type org.apache.http.ProtocolVersion. </para> /// </summary> /// <java-name> /// PROTOCOL_VERSION /// </java-name> [Dot42.DexImport("PROTOCOL_VERSION", "Ljava/lang/String;", AccessFlags = 25)] public const string PROTOCOL_VERSION = "http.protocol.version"; /// <summary> /// <para>Defines the charset to be used for encoding HTTP protocol elements. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_ELEMENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_ELEMENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; /// <summary> /// <para>Defines the charset to be used per default for encoding content body. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_CONTENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_CONTENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; /// <summary> /// <para>Defines the content of the <code>User-Agent</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// USER_AGENT /// </java-name> [Dot42.DexImport("USER_AGENT", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_AGENT = "http.useragent"; /// <summary> /// <para>Defines the content of the <code>Server</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// ORIGIN_SERVER /// </java-name> [Dot42.DexImport("ORIGIN_SERVER", "Ljava/lang/String;", AccessFlags = 25)] public const string ORIGIN_SERVER = "http.origin-server"; /// <summary> /// <para>Defines whether responses with an invalid <code>Transfer-Encoding</code> header should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STRICT_TRANSFER_ENCODING /// </java-name> [Dot42.DexImport("STRICT_TRANSFER_ENCODING", "Ljava/lang/String;", AccessFlags = 25)] public const string STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; /// <summary> /// <para>Activates 'Expect: 100-continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-continue' handshake to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. </para><para>The use of the 'Expect: 100-continue' handshake can result in noticable peformance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. </para><para>'Expect: 100-continue' handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// USE_EXPECT_CONTINUE /// </java-name> [Dot42.DexImport("USE_EXPECT_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; /// <summary> /// <para>Defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// WAIT_FOR_CONTINUE /// </java-name> [Dot42.DexImport("WAIT_FOR_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue"; } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537)] public partial interface ICoreProtocolPNames /* scope: __dot42__ */ { } /// <summary> /// <para>This class implements an adaptor around the HttpParams interface to simplify manipulation of the HTTP protocol specific parameters. <br></br> Note that the <b>implements</b> relation to CoreProtocolPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0</para><para>CoreProtocolPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpProtocolParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParams", AccessFlags = 49)] public sealed partial class HttpProtocolParams : global::Org.Apache.Http.Params.ICoreProtocolPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpProtocolParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the charset to be used for writing HTTP headers. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getHttpElementCharset /// </java-name> [Dot42.DexImport("getHttpElementCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the charset to be used for writing HTTP headers. </para> /// </summary> /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getContentCharset /// </java-name> [Dot42.DexImport("getContentCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns protocol version to be used per default.</para><para></para> /// </summary> /// <returns> /// <para>protocol version </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/ProtocolVersion;", AccessFlags = 9)] public static global::Org.Apache.Http.ProtocolVersion GetVersion(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Assigns the protocol version to be used by the HTTP methods that this collection of parameters applies to.</para><para></para> /// </summary> /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/ProtocolVersion;)V", AccessFlags = 9)] public static void SetVersion(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.ProtocolVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// getUserAgent /// </java-name> [Dot42.DexImport("getUserAgent", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params, string useragent) /* MethodBuilder.Create */ { } /// <java-name> /// useExpectContinue /// </java-name> [Dot42.DexImport("useExpectContinue", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool UseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetUseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params, bool b) /* MethodBuilder.Create */ { } } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.</para><para><para></para><para></para><title>Revision:</title><para>610464 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/BasicHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/BasicHttpParams", AccessFlags = 49)] public sealed partial class BasicHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams, global::Java.Io.ISerializable, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BasicHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Assigns the value to all the parameter with the given names</para><para></para> /// </summary> /// <java-name> /// setParameters /// </java-name> [Dot42.DexImport("setParameters", "([Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1)] public void SetParameters(string[] names, object value) /* MethodBuilder.Create */ { } /// <java-name> /// isParameterSet /// </java-name> [Dot42.DexImport("isParameterSet", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSet(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterSetLocally /// </java-name> [Dot42.DexImport("isParameterSetLocally", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSetLocally(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Removes all parameters from this collection. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1)] public void Clear() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of these parameters. The implementation here instantiates BasicHttpParams, then calls copyParams(HttpParams) to populate the copy.</para><para></para> /// </summary> /// <returns> /// <para>a new set of params holding a copy of the <b>local</b> parameters in this object. </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public object Clone() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Copies the locally defined parameters to the argument parameters. This method is called from copy().</para><para></para> /// </summary> /// <java-name> /// copyParams /// </java-name> [Dot42.DexImport("copyParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 4)] internal void CopyParams(global::Org.Apache.Http.Params.IHttpParams target) /* MethodBuilder.Create */ { } } }
#region Namespaces using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Fields; using Epi; using EpiInfo.Plugin; using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>; #endregion namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { /// <summary> /// Field definition dialog for relate fields /// </summary> public partial class RelateFieldDefinition : CommandButtonFieldDefinition { #region Private Members private RelatedViewField field; private EpiInfo.Plugin.IEnterInterpreter memoryRegion; private bool useExistingView = true; #endregion Private Members #region Constructors /// <summary> /// Default Constsructor, for exclusive use by the designer. /// </summary> public RelateFieldDefinition() { InitializeComponent(); } /// <summary> /// Constructor for the Relate Field Definition /// </summary> /// <param name="frm">The main form</param> public RelateFieldDefinition(Epi.Windows.MakeView.Forms.MakeViewMainForm frm) : base(frm) { InitializeComponent(); this.memoryRegion = frm.EpiInterpreter; } /// <summary> /// Constructor for the Relate Field Definition /// </summary> /// <param name="frm">The main form</param> /// <param name="page">The page</param> public RelateFieldDefinition(Epi.Windows.MakeView.Forms.MakeViewMainForm frm, Page page) : base(frm) { InitializeComponent(); this.memoryRegion = frm.EpiInterpreter; this.mode = FormMode.Create; this.page = page; } /// <summary> /// Constructor for the class /// </summary> /// <param name="frm">The parent form</param> /// <param name="field">The fied to be edited</param> public RelateFieldDefinition(Epi.Windows.MakeView.Forms.MakeViewMainForm frm, RelatedViewField field) : base(frm) { InitializeComponent(); this.mode = FormMode.Edit; this.field = field; this.page = field.Page; this.memoryRegion = frm.EpiInterpreter; LoadFormData(); } #endregion // Constructors #region Private Methods /// <summary> /// Loads default settings into the form /// </summary> private void LoadFormData() { Configuration config = Configuration.GetNewInstance(); FontStyle style = FontStyle.Regular; if (config.Settings.EditorFontBold) { style |= FontStyle.Bold; } if (config.Settings.EditorFontItalics) { style |= FontStyle.Italic; } if ((field.ControlFont == null) || ((field.ControlFont.Name == "Microsoft Sans Serif") && (field.ControlFont.Size == 8.5))) { field.ControlFont = new Font(config.Settings.EditorFontName, (float)config.Settings.EditorFontSize, style); } txtPrompt.Text = field.PromptText; txtPrompt.Font = field.ControlFont; txtFieldName.Text = field.Name; List<EpiInfo.Plugin.IVariable> vars = this.memoryRegion.Context.GetVariablesInScope(); foreach (EpiInfo.Plugin.IVariable v in vars) { if (v.VariableScope == VariableScope.Standard || v.VariableScope == VariableScope.DataSource) { cbxVariables.Items.Add(v.Name); cbxVariables.SelectedIndex = -1; } } cbxVariables.Sorted = true; DataTable cbxDs = new DataTable(); cbxDs.Columns.Add("RelatedFormId", typeof(int)); cbxDs.Columns.Add("FormName", typeof(string)); int SelectedIndex = -1; object[] row = new object[2]; row[0] = -1; row[1] = "(create new form)"; cbxDs.Rows.Add(row); Epi.Project project = field.GetView().Project; View viewPointer = field.GetView(); int currentViewId = viewPointer.Id; List<int> lineage = new List<int>(); lineage.Add(currentViewId); while (viewPointer.ParentView != null) { lineage.Add(viewPointer.ParentView.Id); viewPointer = viewPointer.ParentView; } foreach (Epi.View view in project.Views) { if (lineage.Contains(view.Id) == false) { cbxRelatedView.Items.Add(view.Name); row = new object[2]; row[0] = view.Id; row[1] = view.Name; cbxDs.Rows.Add(row); if (view.Id == field.RelatedViewID) { SelectedIndex = cbxDs.Rows.Count - 1; } } } cbxRelatedView.DataSource = cbxDs; cbxRelatedView.ValueMember = "RelatedFormId"; cbxRelatedView.DisplayMember = "FormName"; cbxRelatedView.SelectedIndex = SelectedIndex; if (field.ChildView != null) { cbxRelatedView.Text = field.ChildView.Name; } if (field.Condition.Length > 0) { rdbAccessibleWithConditions.Checked = true; txtCondition.Text = field.Condition; } else { rdbAccessibleAlways.Checked = true; txtCondition.Text = string.Empty; } controlFont = field.ControlFont; chkReturnToParent.Checked = field.ShouldReturnToParent; } /// <summary> /// Common event handler for build expression buttons /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ClickHandler(object sender, System.EventArgs e) { ToolStripButton btn = (ToolStripButton)sender; if ((string)btn.Tag == null) { if (btn.Text.ToString() != "\"") { txtCondition.Text += StringLiterals.SPACE; txtCondition.Text += btn.Text; txtCondition.Text += StringLiterals.SPACE; } else { txtCondition.Text += btn.Text; } } else { txtCondition.Text += (string)btn.Tag; txtCondition.Text += StringLiterals.SPACE; } } /// <summary> /// Creates a view /// </summary> /// <returns>View that was created</returns> private View PromptUserToCreateView() { View newView = null; Project project = field.Page.GetProject(); CreateViewDialog viewDialog = new CreateViewDialog(MainForm, project, txtFieldName.Text); viewDialog.ShowDialog(); if (viewDialog.DialogResult == DialogResult.OK) { string newViewName = viewDialog.ViewName; //newView = ((ProjectNode)projectTree.Nodes[0]).Project.CreateView(newViewName); newView = project.CreateView(newViewName, true); viewDialog.Close(); } return newView; } #endregion //Private Methods #region Protected Methods /// <summary> /// Validate Dialog Input flag /// </summary> /// <returns></returns> protected override bool ValidateDialogInput() { ErrorMessages.Clear(); if (!string.IsNullOrEmpty(txtCondition.Text)) { try { //string fireControlName = "fireControlName"; //string relatedFieldName = "relatedFieldName"; //string condition = txtCondition.Text.Trim(); //string checkCode = string.Format("field {0} after if {1} then unhide {2} else hide {2} end-if end-before end-field", fireControlName, condition, relatedFieldName); //((Epi.Windows.MakeView.Forms.MakeViewMainForm)this.mainForm).EpiInterpreter.Parse(checkCode); } catch (Exception ex) { ErrorMessages.Add(ex.Message); } } else { if (rdbAccessibleWithConditions.Checked == true) { ErrorMessages.Add(SharedStrings.WARNING_ADD_RELATE_CONDITION); } } // DEFECT# 321 & 384 fix. if (cbxRelatedView.Text != field.GetView().Name) { if (cbxRelatedView.SelectedItem == null || ((System.Data.DataRowView)cbxRelatedView.SelectedItem)[0].ToString() == "-1") { View view = PromptUserToCreateView(); if (view != null) { DataTable cbxDs = (DataTable)cbxRelatedView.DataSource; Page page = view.CreatePage("New Page", 0); object[] row = new object[2]; row[0] = view.Id; row[1] = view.Name; cbxDs.Rows.Add(row); cbxRelatedView.Text = view.Name; UseExistingView = false; view.IsRelatedView = true; } else { ErrorMessages.Add("The user elected not to create a related form."); } // ErrorMessages.Add(SharedStrings.WARNING_ADD_RELATED_VIEW_NAME); } else { View v = field.GetView().Project.Views[cbxRelatedView.Text]; v.IsRelatedView = true; } } else { ErrorMessages.Add("Warning. Cannot relate to the current form."); } return (ErrorMessages.Count.Equals(0)); } /// <summary> /// Sets the field's properties based on GUI values /// </summary> protected override void SetFieldProperties() { field.PromptText = txtPrompt.Text; if (field.Id == 0) { field.Name = txtFieldName.Text; } if (controlFont != null) { field.ControlFont = controlFont; } if (promptFont != null) { field.PromptFont = promptFont; } // DEFECT# 321 fix. if (cbxRelatedView.SelectedValue != null) { field.RelatedViewID = int.Parse(cbxRelatedView.SelectedValue.ToString()); } if (rdbAccessibleAlways.Checked == true) { field.Condition = string.Empty; } else { field.Condition = txtCondition.Text; } field.ShouldReturnToParent = chkReturnToParent.Checked; } #endregion //Protected Methods #region Public Methods /// <summary> /// Gets the field defined by this field definition dialog /// </summary> public override RenderableField Field { get { return field; } } public bool UseExistingView { get { return this.useExistingView; } set { this.useExistingView = value; } } #endregion //Public Methods #region Event Handlers /// <summary> /// Handles the CheckChanged event for the conditional relate check box /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void rdbAccessibleWithConditions_CheckedChanged(object sender, EventArgs e) { lblCondition.Enabled = rdbAccessibleWithConditions.Checked; txtCondition.Enabled = rdbAccessibleWithConditions.Checked; lblAvailableVariables.Enabled = rdbAccessibleWithConditions.Checked; cbxVariables.Enabled = rdbAccessibleWithConditions.Checked; grpOperators.Enabled = rdbAccessibleWithConditions.Checked; } /// <summary> /// Handles the SelectedIndexChanged event for the drop-down list of variables /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void cbxVariables_SelectedIndexChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(cbxVariables.Text)) { txtCondition.Text += cbxVariables.Text; } } #endregion // Event Handlers } }
using System; using System.Collections; using System.Collections.Generic; using Xunit; public static class xUnitSpecificationExtensions { public static void ShouldBeFalse(this bool condition) { ShouldBeFalse(condition, string.Empty); } public static void ShouldBeFalse(this bool condition, string message) { Assert.False(condition, message); } public static void ShouldBeTrue(this bool condition) { ShouldBeTrue(condition, string.Empty); } public static void ShouldBeTrue(this bool condition, string message) { Assert.True(condition, message); } public static T ShouldEqual<T>(this T actual, T expected) { Assert.Equal(expected, actual); return actual; } public static T ShouldEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.Equal(expected, actual, comparer); return actual; } public static string ShouldEqual(this string actual, string expected, StringComparer comparer) { Assert.Equal(expected, actual, comparer); return actual; } public static T ShouldNotEqual<T>(this T actual, T expected) { Assert.NotEqual(expected, actual); return actual; } public static string ShouldNotEqual(this string actual, string expected, StringComparer comparer) { Assert.NotEqual(expected, actual, comparer); return actual; } public static T ShouldNotEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.NotEqual(expected, actual, comparer); return actual; } public static void ShouldBeNull(this object anObject) { Assert.Null(anObject); } public static T ShouldNotBeNull<T>(this T anObject) { Assert.NotNull(anObject); return anObject; } public static object ShouldBeTheSameAs(this object actual, object expected) { Assert.Same(expected, actual); return actual; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { Assert.NotSame(expected, actual); return actual; } public static T ShouldBeOfType<T>(this T actual, Type expected) { Assert.IsType(expected, actual); return actual; } public static T ShouldNotBeOfType<T>(this T actual, Type expected) { Assert.IsNotType(expected, actual); return actual; } public static IEnumerable ShouldBeEmpty(this IEnumerable collection) { Assert.Empty(collection); return collection; } public static IEnumerable ShouldNotBeEmpty(this IEnumerable collection) { Assert.NotEmpty(collection); return collection; } public static string ShouldContain(this string actualString, string expectedSubString) { Assert.Contains(expectedSubString, actualString); return actualString; } public static string ShouldContain(this string actualString, string expectedSubString, StringComparison comparisonType) { Assert.Contains(expectedSubString, actualString, comparisonType); return actualString; } public static IEnumerable<string> ShouldContain(this IEnumerable<string> collection, string expected, StringComparer comparer) { Assert.Contains(expected, collection, comparer); return collection; } public static IEnumerable<T> ShouldContain<T>(this IEnumerable<T> collection, T expected) { Assert.Contains(expected, collection); return collection; } public static IEnumerable<T> ShouldContain<T>(this IEnumerable<T> collection, T expected, IEqualityComparer<T> equalityComparer) { Assert.Contains(expected, collection, equalityComparer); return collection; } public static string ShouldNotContain(this string actualString, string expectedSubString) { Assert.DoesNotContain(expectedSubString, actualString); return actualString; } public static string ShouldNotContain(this string actualString, string expectedSubString, StringComparison comparisonType) { Assert.DoesNotContain(expectedSubString, actualString, comparisonType); return actualString; } public static IEnumerable<string> ShouldNotContain(this IEnumerable<string> collection, string expected, StringComparer comparer) { Assert.DoesNotContain(expected, collection, comparer); return collection; } public static IEnumerable<T> ShouldNotContain<T>(this IEnumerable<T> collection, T expected) { Assert.DoesNotContain(expected, collection); return collection; } public static IEnumerable<T> ShouldNotContain<T>(this IEnumerable<T> collection, T expected, IEqualityComparer<T> equalityComparer) { Assert.DoesNotContain(expected, collection, equalityComparer); return collection; } public static Exception ShouldBeThrownBy(this Type exceptionType, Action method) { return Assert.Throws(exceptionType, method); } //public static void ShouldNotThrow(this Action method) //{ // Assert.DoesNotThrow(method); //} public static T IsInRange<T>(this T actual, T low, T high) where T : IComparable { Assert.InRange(actual, low, high); return actual; } public static T IsInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.InRange(actual, low, high, comparer); return actual; } public static T IsNotInRange<T>(this T actual, T low, T high) where T : IComparable { Assert.NotInRange(actual, low, high); return actual; } public static T IsNotInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.NotInRange(actual, low, high, comparer); return actual; } public static IEnumerable IsEmpty(this IEnumerable collection) { Assert.Empty(collection); return collection; } public static T IsType<T>(this T actual, Type expectedType) { Assert.IsType(expectedType, actual); return actual; } public static T IsNotType<T>(this T actual, Type expectedType) { Assert.IsNotType(expectedType, actual); return actual; } public static T IsAssignableFrom<T>(this T actual, Type expectedType) { Assert.IsAssignableFrom(expectedType, actual); return actual; } /* Consider implementing these later public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { StringAssert.AreEqualIgnoringCase(expected, actual); return actual; } public static string ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); return actual; } public static string ShouldEndWith(this string actual, string expected) { StringAssert.EndsWith(expected, actual); return actual; } public static void ShouldBeSurroundedWith(this string actual, string expectedStartDelimiter, string expectedEndDelimiter) { StringAssert.StartsWith(expectedStartDelimiter, actual); StringAssert.EndsWith(expectedEndDelimiter, actual); } public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter) { StringAssert.StartsWith(expectedDelimiter, actual); StringAssert.EndsWith(expectedDelimiter, actual); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { StringAssert.Contains(expected, exception.Message); } */ }
#region LGPL License /* Axiom Graphics Engine Library Copyright (C) 2003-2006 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion #region SVN Version Information // <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <id value="$Id$"/> // </file> #endregion SVN Version Information #region Namespace Declarations using System; using System.Collections.Generic; //using System.Diagnostics; using System.IO; using System.Text; #endregion Namespace Declarations namespace Axiom.Core { /// <summary> /// The MeterManager creates and hands out TimingMeter /// instances. Those instances are looked up by meter "title", a /// string name for the meter. Meter instances also have a string /// "category", so you can turn metering on and off by category. /// All public methods of MeterManager are static, so the user /// doesn't have to worry about managing the instance of /// MeterManager. /// /// The workflow is that the user program creates several meters by /// calling the static MakeMeter method, passing the title and /// category of the meter. That method looks up the meter by title, /// creating it if it doesn't already exists, and returns the meter. /// Thereafter, the user invokes the TimingMeter.Enter() and /// TimingMeter.Exit() methods, each of which causes the /// MeterManager to add a record to a collection of entries and /// exits. The record has the identity of the meter; whether it's /// an entry or exit, and the time in processor ticks, captured /// using the assembler primitive RDTSC. At any point, the program /// can call the method MeterManager.Report, which produces a report /// based on the trace. /// /// </summary> public class MeterManager { #region Protected MeterManager members internal const int ekEnter = 1; internal const int ekExit = 2; internal const int ekInfo = 3; protected static MeterManager instance = null; // Are we collecting now? protected bool collecting; // An id counter for timers protected short timerIdCounter; // The time when the meter manager was started protected long startTime; // The number of microseconds per tick; obviously a fraction float microsecondsPerTick; // The list of timing meter events internal List<MeterEvent> eventTrace; // Look up meters by title&category internal Dictionary<string, TimingMeter> metersByName; // Look up meters by id protected Dictionary<int, TimingMeter> metersById; // DEBUG private static List<MeterStackEntry> debugMeterStack = new List<MeterStackEntry>(); public static string MeterLogFilename = "MeterLog.txt"; public static string MeterEventsFilename = "MeterEvents.txt"; private static void DebugAddEvent( TimingMeter meter, MeterEvent evt ) { if ( evt.eventKind == ekEnter ) { debugMeterStack.Add( new MeterStackEntry( meter, 0 ) ); } else if ( evt.eventKind == ekExit ) { UnityEngine.Debug.Assert( debugMeterStack.Count > 0, "Meter stack is empty during ekExit" ); MeterStackEntry s = debugMeterStack[ debugMeterStack.Count - 1 ]; UnityEngine.Debug.Assert( s.meter == meter, "Entered " + s.meter.title + "; Exiting " + meter.title ); debugMeterStack.RemoveAt( debugMeterStack.Count - 1 ); } else if ( evt.eventKind == ekInfo ) { // just ignore these } else { UnityEngine.Debug.Assert( false ); } } protected static long CaptureCurrentTime() { return System.Diagnostics.Stopwatch.GetTimestamp(); } protected string OptionValue( string name, Dictionary<string, string> options ) { string value; if ( options.TryGetValue( name, out value ) ) return value; else return ""; } protected bool BoolOption( string name, Dictionary<string, string> options ) { string value = OptionValue( name, options ); return ( value != "" && value != "false" ); } protected int IntOption( string name, Dictionary<string, string> options ) { string value = OptionValue( name, options ); return ( value == "" ? 0 : int.Parse( value ) ); } protected static void BarfOnBadChars( string name, string nameDescription ) { if ( name.IndexOf( "\n" ) >= 0 ) throw new Exception( string.Format( "Carriage returns are not allowed in {0}", nameDescription ) ); else if ( name.IndexOf( "," ) >= 0 ) throw new Exception( string.Format( "Commas are not allowed in {0}", nameDescription ) ); } protected MeterManager() { timerIdCounter = 1; eventTrace = new List<MeterEvent>(); metersByName = new Dictionary<string, TimingMeter>(); metersById = new Dictionary<int, TimingMeter>(); startTime = CaptureCurrentTime(); microsecondsPerTick = 1000000.0f / (float)System.Diagnostics.Stopwatch.Frequency; instance = this; } protected TimingMeter GetMeterById( int id ) { TimingMeter meter; metersById.TryGetValue( id, out meter ); UnityEngine.Debug.Assert( meter != null, string.Format( "Meter for id {0} is not in the index", id ) ); return meter; } protected void SaveToFileInternal( string pathname ) { FileStream f = new FileStream( pathname, FileMode.Create, FileAccess.Write ); StreamWriter writer = new StreamWriter( f ); writer.Write( string.Format( "MeterCount={0}\n", metersById.Count ) ); foreach ( KeyValuePair<int, TimingMeter> pair in instance.metersById ) { TimingMeter meter = pair.Value; writer.Write( string.Format( "{0},{1},{2}\n", meter.title, meter.category, meter.meterId ) ); } } protected string IndentCount( int count ) { if ( count > 20 ) count = 20; string s = "|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-"; return s.Substring( 0, 2 * count ); } protected long ToMicroseconds( long ticks ) { return (long)( ( (float)ticks ) * microsecondsPerTick ); } protected void DumpEventLog() { if ( File.Exists( MeterEventsFilename ) ) File.Delete( MeterEventsFilename ); FileStream f = new FileStream( MeterEventsFilename, FileMode.Create, FileAccess.Write ); StreamWriter writer = new StreamWriter( f ); writer.Write( string.Format( "Dumping meter event log on {0} at {1}; units are usecs\r\n", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString() ) ); int indent = 0; List<MeterStackEntry> meterStack = new List<MeterStackEntry>(); long firstEventTime = 0; for ( int i = 0; i < eventTrace.Count; i++ ) { short kind = eventTrace[ i ].eventKind; long t = eventTrace[ i ].eventTime; if ( i == 0 ) firstEventTime = t; if ( kind == ekInfo ) { writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}{4}", ToMicroseconds( t - firstEventTime ), IndentCount( indent ), "Info ", " ", eventTrace[ i ].info ) ); continue; } TimingMeter meter = GetMeterById( eventTrace[ i ].meterId ); if ( kind == ekEnter ) { indent++; writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}.{4}", ToMicroseconds( t - firstEventTime ), IndentCount( indent ), "Enter", meter.category, meter.title ) ); meterStack.Add( new MeterStackEntry( meter, t ) ); } else if ( kind == ekExit ) { UnityEngine.Debug.Assert( meterStack.Count > 0, "Meter stack is empty during ekExit" ); MeterStackEntry s = meterStack[ meterStack.Count - 1 ]; UnityEngine.Debug.Assert( s.meter == meter, "Entered " + s.meter.title + "; Exiting " + meter.title ); writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}.{4}", ToMicroseconds( t - s.eventTime ), IndentCount( indent ), "Exit ", meter.category, meter.title ) ); indent--; meterStack.RemoveAt( meterStack.Count - 1 ); } } writer.Close(); } protected static bool dumpEventLog = true; protected void GenerateReport( StreamWriter writer, int start, Dictionary<string, string> options ) { // For now, ignore options and just print the event trace if ( dumpEventLog ) DumpEventLog(); // Zero the stack depth and added time foreach ( KeyValuePair<int, TimingMeter> pair in instance.metersById ) { TimingMeter meter = pair.Value; meter.stackDepth = 0; meter.addedTime = 0; } List<MeterStackEntry> meterStack = new List<MeterStackEntry>(); int indent = 0; long firstEventTime = 0; for ( int i = 0; i < eventTrace.Count; i++ ) { short kind = eventTrace[ i ].eventKind; long t = eventTrace[ i ].eventTime; if ( i == 0 ) firstEventTime = t; if ( kind == ekInfo ) { writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}{4}", ToMicroseconds( t - firstEventTime ), IndentCount( indent ), "Info ", " ", eventTrace[ i ].info ) ); continue; } TimingMeter meter = GetMeterById( eventTrace[ i ].meterId ); if ( kind == ekEnter ) { if ( meter.accumulate && meter.stackDepth == 0 ) meter.addedTime = 0; if ( i >= start && ( !meter.accumulate || meter.stackDepth == 0 ) ) { // Don't display the enter and exit if the // exit is the very next record, and the // elapsed usecs is less than DontDisplayUsecs if ( eventTrace.Count > i + 1 && eventTrace[ i + 1 ].meterId == eventTrace[ i ].meterId && eventTrace[ i + 1 ].eventKind == ekExit && ToMicroseconds( eventTrace[ i + 1 ].eventTime - t ) < DontDisplayUsecs ) { i++; continue; } writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}{4}.{5}", ToMicroseconds( t - firstEventTime ), IndentCount( indent ), "Enter", ( meter.accumulate ? "*" : " " ), meter.category, meter.title ) ); if ( !meter.accumulate ) indent++; } meter.stackDepth++; meterStack.Add( new MeterStackEntry( meter, t ) ); } else if ( kind == ekExit ) { UnityEngine.Debug.Assert( meterStack.Count > 0, "Meter stack is empty during ekExit" ); MeterStackEntry s = meterStack[ meterStack.Count - 1 ]; meter.stackDepth--; UnityEngine.Debug.Assert( s.meter == meter ); if ( meter.stackDepth > 0 && meter.accumulate ) meter.addedTime += t - s.eventTime; else if ( i >= start ) { if ( !meter.accumulate ) indent--; writer.WriteLine( string.Format( "{0,12:D} {1}{2} {3}{4}.{5}", ToMicroseconds( meter.accumulate ? meter.addedTime : t - s.eventTime ), IndentCount( indent ), "Exit ", ( meter.accumulate ? "*" : " " ), meter.category, meter.title ) ); } meterStack.RemoveAt( meterStack.Count - 1 ); } } } #endregion Protected MeterManager members #region Public MeterManager methods - - all static public static void Init() { if ( instance == null ) instance = new MeterManager(); } public static int DontDisplayUsecs = 3; public static bool Collecting { get { return instance.collecting; } set { instance.collecting = value; } } // Enable or disable meters by category public static void EnableCategory( string categoryName, bool enable ) { Init(); foreach ( KeyValuePair<int, TimingMeter> pair in instance.metersById ) { TimingMeter meter = pair.Value; if ( meter.category == categoryName ) meter.enabled = enable; } } // Enable or disable only a single category public static void EnableOnlyCategory( string categoryName, bool enable ) { Init(); foreach ( KeyValuePair<int, TimingMeter> pair in instance.metersById ) { TimingMeter meter = pair.Value; meter.enabled = ( meter.category == categoryName ? enable : !enable ); } } // Look up the timing meter by title; if it doesn't exist // create one with the title and category public static TimingMeter GetMeter( string title, string category ) { string name = title + "&" + category; TimingMeter meter; Init(); if ( instance.metersByName.TryGetValue( name, out meter ) ) return meter; else { BarfOnBadChars( title, "TimingMeter title" ); BarfOnBadChars( category, "TimingMeter category" ); short id = instance.timerIdCounter++; meter = new TimingMeter( title, category, id ); instance.metersByName.Add( name, meter ); instance.metersById.Add( id, meter ); return meter; } } public static TimingMeter GetMeter( string title, string category, bool accumulate ) { TimingMeter meter = GetMeter( title, category ); meter.accumulate = true; return meter; } public static int AddEvent( TimingMeter meter, short eventKind, string info ) { long time = CaptureCurrentTime(); short meterId = ( meter == null ) ? (short)0 : meter.meterId; MeterEvent meterEvent = new MeterEvent( meterId, eventKind, time, info ); #if DEBUG DebugAddEvent( meter, meterEvent ); #endif instance.eventTrace.Add( meterEvent ); return instance.eventTrace.Count; } public static void ClearEvents() { Init(); instance.eventTrace.Clear(); } public static void SaveToFile( string pathname ) { instance.SaveToFileInternal( pathname ); } public static long StartTime() { Init(); return instance.startTime; } public static void AddInfoEvent( string info ) { if ( MeterManager.Collecting ) AddEvent( null, ekInfo, info ); } public static void Report( string title ) { Report( title, null, 0, "" ); } public static void Report( string title, StreamWriter writer, int start, string optionsString ) { bool opened = false; if ( writer == null ) { FileStream f = new FileStream( MeterLogFilename, ( File.Exists( MeterLogFilename ) ? FileMode.Append : FileMode.Create ), FileAccess.Write ); writer = new StreamWriter( f ); writer.Write( string.Format( "\r\nStarting meter report on {0} at {1} for {2}; units are usecs.", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), title ) ); opened = true; } instance.GenerateReport( writer, start, null ); if ( opened ) writer.Close(); } #endregion Public MeterManager methods } internal struct MeterEvent { internal short meterId; internal short eventKind; internal long eventTime; internal string info; internal MeterEvent( short meterId, short eventKind, long eventTime, string info ) { this.meterId = meterId; this.eventKind = eventKind; this.eventTime = eventTime; this.info = info; } } internal struct MeterStackEntry { internal TimingMeter meter; internal long eventTime; internal MeterStackEntry( TimingMeter meter, long eventTime ) { this.meter = meter; this.eventTime = eventTime; } } public class TimingMeter { internal TimingMeter( string title, string category, short meterId ) { this.title = title; this.category = category; this.meterId = meterId; this.enabled = true; this.accumulate = false; } public string title; public string category; public bool enabled; public bool accumulate; public long addedTime; public long addStart; public int stackDepth; internal short meterId; public void Enter() { if ( MeterManager.Collecting && enabled ) MeterManager.AddEvent( this, MeterManager.ekEnter, "" ); } public void Exit() { if ( MeterManager.Collecting && enabled ) MeterManager.AddEvent( this, MeterManager.ekExit, "" ); } } public class AutoTimer : IDisposable { TimingMeter meter; public AutoTimer( TimingMeter meter ) { this.meter = meter; meter.Enter(); } public void Dispose() { meter.Exit(); meter = null; } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Xunit; namespace Imagekit.UnitTests { [Collection("Uses Utils.HttpClient")] public class ServerImagekitTests { private const string GOOD_PUBLICKEY = "test publickey"; private const string GOOD_PRIVATEKEY = "test privatekey"; private const string GOOD_URLENDPOINT = "test urlendpoint"; private const string GOOD_TRANSFORMATION = "path"; [Theory] [InlineData("N/A", GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT, GOOD_TRANSFORMATION, false)] [InlineData("publicKey", null, GOOD_PRIVATEKEY, GOOD_URLENDPOINT, GOOD_TRANSFORMATION, true)] [InlineData("publicKey", "", GOOD_PRIVATEKEY, GOOD_URLENDPOINT, GOOD_TRANSFORMATION, true)] [InlineData("privateKey", GOOD_PUBLICKEY, null, GOOD_URLENDPOINT, GOOD_TRANSFORMATION, true)] [InlineData("privateKey", GOOD_PUBLICKEY, "", GOOD_URLENDPOINT, GOOD_TRANSFORMATION, true)] [InlineData("urlEndpoint", GOOD_PUBLICKEY, GOOD_PRIVATEKEY, null, GOOD_TRANSFORMATION, true)] [InlineData("urlEndpoint", GOOD_PUBLICKEY, GOOD_PRIVATEKEY, "", GOOD_TRANSFORMATION, true)] public void Constructor_Required( string paramUnderTest, string publicKey, string privateKey, string urlEndpoint, string transformationPosition, bool expectException ) { if (expectException) { var ex = Assert.Throws<ArgumentNullException>(() => new ServerImagekit(publicKey, privateKey, urlEndpoint, transformationPosition)); Assert.Equal(paramUnderTest, ex.ParamName); } else { var imagekit = new ServerImagekit(publicKey, privateKey, urlEndpoint, transformationPosition); Assert.NotNull(imagekit); } } [Fact] public void Constructor_TransformationPosition_Default() { var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT); Assert.NotNull(imagekit); } [Theory] [InlineData("path", false)] [InlineData("query", false)] [InlineData("test path", true)] [InlineData("test query", true)] [InlineData("asdf", true)] [InlineData(null, true)] [InlineData("", true)] public void Constructor_TransformationPosition(string transformationPosition, bool expectException) { if (expectException) { var ex = Assert.Throws<ArgumentException>(() => new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT, transformationPosition)); Assert.Equal("transformationPosition", ex.ParamName); } else { var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT, transformationPosition); Assert.NotNull(imagekit); } } [Fact] public void Upload() { var fileName = Guid.NewGuid().ToString(); var fileUrl = "https://test.com/test.png"; var responseObj = TestHelpers.ImagekitResponseFaker.Generate(); var httpResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(responseObj)) }; var httpClient = TestHelpers.GetTestHttpClient(httpResponse, TestHelpers.GetUploadRequestMessageValidator(fileUrl, fileName)); Util.Utils.SetHttpClient(httpClient); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName); var response = imagekit.Upload(fileUrl); Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); } [Fact] public async Task UploadAsync() { var fileName = Guid.NewGuid().ToString(); var fileUrl = "https://test.com/test.png"; var responseObj = TestHelpers.ImagekitResponseFaker.Generate(); var httpResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(responseObj)) }; var httpClient = TestHelpers.GetTestHttpClient(httpResponse, TestHelpers.GetUploadRequestMessageValidator(fileUrl, fileName)); Util.Utils.SetHttpClient(httpClient); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName); var response = await imagekit.UploadAsync(fileUrl); Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); } [Fact] public void GetUploadData_TagsString() { var fileName = Guid.NewGuid().ToString(); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName) .Tags("tag1,tag2"); var data = imagekit.getUploadData(); Assert.True(data.TryGetValue("tags", out string actualTags), "tags upload data not found"); Assert.Equal("tag1,tag2", actualTags); } [Fact] public void GetUploadData_TagsArray() { var fileName = Guid.NewGuid().ToString(); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName) .Tags("tag1", "tag2"); var data = imagekit.getUploadData(); Assert.True(data.TryGetValue("tags", out string actualTags), "tags upload data not found"); Assert.Equal("tag1,tag2", actualTags); } [Theory] [InlineData(null)] [InlineData("null")] [InlineData("tag1")] [InlineData("tag1,tag2")] public async Task UpdateFileDetailsAsync_TagsString(string tags) { var fileId = Guid.NewGuid().ToString(); var fileName = Guid.NewGuid().ToString(); var responseObj = TestHelpers.ListAPIResponseFaker.Generate(); responseObj.Tags = tags == null ? null : tags.Split(","); if (responseObj.Tags != null && responseObj.Tags[0] == "null") { responseObj.Tags = null; } responseObj.CustomCoordinates = null; var httpResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(responseObj)) }; var httpClient = TestHelpers.GetTestHttpClient(httpResponse, TestHelpers.GetUpdateFileDetailsMessageValidator(responseObj.Tags, null)); Util.Utils.SetHttpClient(httpClient); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName) .Tags(tags); var response = await imagekit.UpdateFileDetailsAsync(fileId); Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); } [Theory, MemberData(nameof(TagsArrays))] public async Task UpdateFileDetailsAsync_TagsArray(string[] tags, bool isValid) { var fileId = Guid.NewGuid().ToString(); var fileName = Guid.NewGuid().ToString(); var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT) .FileName(fileName) .Tags(tags); if (isValid) { var responseObj = TestHelpers.ListAPIResponseFaker.Generate(); responseObj.Tags = tags; responseObj.CustomCoordinates = null; var httpResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(responseObj)) }; var httpClient = TestHelpers.GetTestHttpClient(httpResponse, TestHelpers.GetUpdateFileDetailsMessageValidator(responseObj.Tags, null)); Util.Utils.SetHttpClient(httpClient); var response = await imagekit.UpdateFileDetailsAsync(fileId); Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response)); } else { var ex = await Assert.ThrowsAsync<ArgumentException>(() => imagekit.UpdateFileDetailsAsync(fileId)); Assert.Equal(Util.errorMessages.UPDATE_DATA_TAGS_INVALID, ex.Message); } } public static IEnumerable<object[]> TagsArrays { get { // string[] tags, bool isValid yield return new object[] { null, false }; yield return new object[] { new string[] { }, false }; yield return new object[] { new string[] { "tag1" }, true }; yield return new object[] { new string[] { "tag1", "tag2" }, true }; } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using Grpc.Core; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// grpc_call from <grpc/grpc.h> /// </summary> internal class CallSafeHandle : SafeHandleZeroIsInvalid { const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionRegistry completionRegistry; [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call); [DllImport("grpc_csharp_ext.dll")] static extern void grpcsharp_call_destroy(IntPtr call); private CallSafeHandle() { } public void SetCompletionRegistry(CompletionRegistry completionRegistry) { this.completionRegistry = completionRegistry; } public void StartUnary(byte[] payload, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray) .CheckOk(); } public void StartUnary(byte[] payload, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray) { grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray) .CheckOk(); } public void StartClientStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_client_streaming(this, ctx, metadataArray).CheckOk(); } public void StartServerStreaming(byte[] payload, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray).CheckOk(); } public void StartDuplexStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray).CheckOk(); } public void StartSendMessage(byte[] payload, BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length)).CheckOk(); } public void StartSendCloseFromClient(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } public void StartSendStatusFromServer(Status status, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, status.Detail, metadataArray).CheckOk(); } public void StartReceiveMessage(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_recv_message(this, ctx).CheckOk(); } public void StartServerSide(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_serverside(this, ctx).CheckOk(); } public void Cancel() { grpcsharp_call_cancel(this).CheckOk(); } public void CancelWithStatus(Status status) { grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk(); } public string GetPeer() { using (var cstring = grpcsharp_call_get_peer(this)) { return cstring.GetValue(); } } protected override bool ReleaseHandle() { grpcsharp_call_destroy(handle); return true; } private static uint GetFlags(bool buffered) { return buffered ? 0 : GRPC_WRITE_BUFFER_HINT; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.FrameBuilder.CS { using System; using System.Text; using System.Collections.Generic; using Autodesk.Revit; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using UV = Autodesk.Revit.DB.UV; /// <summary> /// data class contains information to create framing /// </summary> public class FrameData { const int XNumberMaxValue = 50; // maximum number of Columns in the X Direction const int XNumberMinValue = 2; // minimum number of Columns in the X Direction const int XNumberDefault = 3; // default number of Columns in the X Direction const int YNumberMaxValue = 50; // maximum number of Columns in the Y Direction const int YNumberMinValue = 2; // minimum number of Columns in the Y Direction const int YNumberDefault = 3; // default number of Columns in the Y Direction const int TotalMaxValue = 200; // maximum total number of Columns to create const int FloorNumberMinValue = 1; // minimum number of floors const int FloorNumberMaxValue = 200; // maximum number of floors const double DistanceMaxValue = 3000; // maxinum distance between 2 adjoining columns const double DistanceMinValue = 1; // mininum distance between 2 adjoining columns const double DistanceDefault = 5; // default distance between 2 adjoining columns const double LevelHeightMaxValue = 100; // maximum height between 2 new levels const double LevelHeightMinValue = 1; // minimum height between 2 new levels const int DigitPrecision = 4; // the number of significant digits(precision) int m_xNumber = XNumberDefault; // number of Columns in the X Direction int m_yNumber = XNumberDefault; // number of Columns in the Y Direction double m_distance = DistanceDefault; // distance between 2 adjoining columns int m_floorNumber; // number of floors double m_levelHeight; // increaced height of autogenerated levels Autodesk.Revit.DB.UV m_frameOrigin = new Autodesk.Revit.DB.UV(0.0, 0.0); // bottom left point of the frame double m_frameOriginAngle = 0.0; // the angle to rotate around bottom left point int m_originalLevelSize; // the number of levels before invoke external command FamilySymbol m_columnSymbol; // column's type FamilySymbol m_beamSymbol; // beam's type FamilySymbol m_braceSymbol; // brace's type ExternalCommandData m_commandData; FrameTypesMgr m_columnSymbolsMgr; // object manage all column types FrameTypesMgr m_beambracesSymbolsMgr; // object manage all beam types SortedList<double, Level> m_levels; // list of all levels in the order of Elevation /// <summary> /// command data pass from entry point /// </summary> public ExternalCommandData CommandData { get { return m_commandData; } } /// <summary> /// object manage all column types /// </summary> public FrameTypesMgr ColumnSymbolsMgr { get { return m_columnSymbolsMgr; } } /// <summary> /// object manage all beam types /// </summary> public FrameTypesMgr BeamSymbolsMgr { get { return m_beambracesSymbolsMgr; } } /// <summary> /// object manage all brace types /// </summary> public FrameTypesMgr BraceSymbolsMgr { get { return m_beambracesSymbolsMgr; } } /// <summary> /// number of Columns in the Y Direction /// </summary> public int YNumber { get { return m_yNumber; } set { if (value < YNumberMinValue || value > YNumberMaxValue) { string message = "Number of Columns in the Y Direction should no less than " + YNumberMinValue.ToString() + " and no more than " + YNumberMaxValue.ToString(); throw new ErrorMessageException(message); } CheckTotalNumber(value * XNumber * (m_floorNumber - 1)); m_yNumber = value; } } /// <summary> /// number of Columns in the X Direction /// </summary> public int XNumber { get { return m_xNumber; } set { if (value < XNumberMinValue || value > XNumberMaxValue) { string message = "Number of Columns in the X Direction should no less than " + XNumberMinValue.ToString() + " and no more than " + XNumberMaxValue.ToString(); throw new ErrorMessageException(message); } CheckTotalNumber(value * YNumber * (m_floorNumber - 1)); m_xNumber = value; } } /// <summary> /// distance between 2 adjoining columns /// </summary> public double Distance { get { return m_distance; } set { if (value < DistanceMinValue || value > DistanceMaxValue) { string message = "The distance between columns shoule no less than " + DistanceMinValue.ToString() + "and no more than " + DistanceMaxValue.ToString(); throw new ErrorMessageException(message); } m_distance = value; } } /// <summary> /// number of floors /// </summary> public int FloorNumber { get { return m_floorNumber; } set { if (value < FloorNumberMinValue || value > FloorNumberMaxValue) { string message = "Number of floors should no less than " + FloorNumberMinValue.ToString() + " and no more than " + FloorNumberMaxValue.ToString(); throw new ErrorMessageException(message); } CheckTotalNumber(XNumber * YNumber * (value - 1)); m_floorNumber = value; } } /// <summary> /// increased height of autogenerated levels /// </summary> public double LevelHeight { get { return Math.Round(m_levelHeight, DigitPrecision); } set { if (value < LevelHeightMinValue || value > LevelHeightMaxValue) { string message = "The distance between columns shoule no less than " + LevelHeightMinValue.ToString() + "and no more than " + LevelHeightMaxValue.ToString(); throw new ErrorMessageException(message); } m_distance = value; } } /// <summary> /// bottom left point of the frame /// </summary> public Autodesk.Revit.DB.UV FrameOrigin { get { return m_frameOrigin; } set { m_frameOrigin = value; } } /// <summary> /// the angle to rotate around bottom left point /// </summary> public double FrameOriginAngle { get { return m_frameOriginAngle; } set { m_frameOriginAngle = value; } } /// <summary> /// column's type /// </summary> public FamilySymbol ColumnSymbol { get { return m_columnSymbol; } } /// <summary> /// beam's type /// </summary> public FamilySymbol BeamSymbol { get { return m_beamSymbol; } } /// <summary> /// brace's type /// </summary> public FamilySymbol BraceSymbol { get { return m_braceSymbol; } } /// <summary> /// list of all levels in the ordr of Elevation /// </summary> public SortedList<double, Level> Levels { get { return m_levels; } } /// <summary> /// the number of levels before invoke external command /// </summary> public int OriginalLevelSize { get { return m_originalLevelSize; } } /// <summary> /// create FramingData object. applicationException will throw out, /// if current Revit document doesn't satisfy the condition to create framing /// </summary> /// <param name="commandData"></param> /// <returns></returns> public static FrameData CreateInstance(ExternalCommandData commandData) { FrameData data = new FrameData(commandData); data.Initialize(); data.Validate(); // initialize members after checking precondition data.m_floorNumber = (data.m_levels.Count - 1) > 0 ? (data.m_levels.Count - 1) : 1; data.m_columnSymbol = data.m_columnSymbolsMgr.FramingSymbols[0]; data.m_beamSymbol = data.m_beambracesSymbolsMgr.FramingSymbols[0]; data.m_braceSymbol = data.m_beambracesSymbolsMgr.FramingSymbols[0]; data.m_levelHeight = data.m_levels.Values[data.m_levels.Count - 1].Elevation - data.m_levels.Values[data.m_levels.Count - 2].Elevation; return data; } /// <summary> /// cast object to FamilySymbol and set as column's type /// </summary> /// <param name="obj">FamilySymbol object</param> /// <returns>failed to cast and set</returns> public bool SetColumnSymbol(object obj) { FamilySymbol symbol = obj as FamilySymbol; if (null == symbol) { return false; } m_columnSymbol = symbol; return true; } /// <summary> /// cast object to FamilySymbol and set as beam's type /// </summary> /// <param name="obj">FamilySymbol object</param> /// <returns>failed to cast and set</returns> public bool SetBeamSymbol(object obj) { FamilySymbol symbol = obj as FamilySymbol; if (null == symbol) { return false; } m_beamSymbol = symbol; return true; } /// <summary> /// cast object to FamilySymbol and set as brace's type /// </summary> /// <param name="obj">FamilySymbol object</param> /// <returns>failed to cast and set</returns> public bool SetBraceSymbol(object obj) { FamilySymbol symbol = obj as FamilySymbol; if (null == symbol) { return false; } m_braceSymbol = symbol; return true; } /// <summary> /// add more levels so that level number can meet floor number /// </summary> public void UpdateLevels() { double baseElevation = m_levels.Values[m_levels.Count - 1].Elevation; Autodesk.Revit.Creation.Document createDoc = m_commandData.Application.ActiveUIDocument.Document.Create; int newLevelSize = (m_floorNumber + 1) - m_levels.Count; if (newLevelSize == 0) { return; } for (int ii = 0; ii < newLevelSize; ii++) { double elevation = baseElevation + m_levelHeight * (ii + 1); Level newLevel = createDoc.NewLevel(elevation); createDoc.NewViewPlan(newLevel.Name, newLevel, Autodesk.Revit.DB.ViewPlanType.FloorPlan); m_levels.Add(elevation, newLevel); } m_originalLevelSize = m_levels.Count; } /// <summary> /// it is only used for object factory method /// </summary> /// <param name="commandData"></param> private FrameData(ExternalCommandData commandData) { // initialize members m_commandData = commandData; m_columnSymbolsMgr = new FrameTypesMgr(commandData); m_beambracesSymbolsMgr = new FrameTypesMgr(commandData); m_levels = new SortedList<double, Level>(); m_originalLevelSize = m_levels.Count; m_yNumber = YNumberDefault; m_xNumber = XNumberDefault; m_distance = DistanceDefault; } /// <summary> /// check the total number of columns to create less than certain value /// </summary> /// <param name="number"></param> /// <returns></returns> private static void CheckTotalNumber(int number) { if (number > TotalMaxValue) { string message = "The total number of columns should less than " + TotalMaxValue.ToString(); throw new ErrorMessageException(message); } } /// <summary> /// initialize list of column, beam and brace's type; /// initialize list of level /// </summary> private void Initialize() { Application app = m_commandData.Application.Application; Document doc = m_commandData.Application.ActiveUIDocument.Document; FilteredElementCollector collector1 = new FilteredElementCollector(doc); IList<Autodesk.Revit.DB.Element> a1 = collector1.OfClass(typeof(Level)).ToElements(); foreach (Level lev in a1) { m_levels.Add(lev.Elevation, lev); } a1.Clear(); Categories categories = doc.Settings.Categories; BuiltInCategory bipColumn = BuiltInCategory.OST_StructuralColumns; BuiltInCategory bipFraming = BuiltInCategory.OST_StructuralFraming; Autodesk.Revit.DB.ElementId idColumn = categories.get_Item(bipColumn).Id; Autodesk.Revit.DB.ElementId idFraming = categories.get_Item(bipFraming).Id; ElementCategoryFilter filterColumn = new ElementCategoryFilter(bipColumn); ElementCategoryFilter filterFraming = new ElementCategoryFilter(bipFraming); LogicalOrFilter orFilter = new LogicalOrFilter(filterColumn, filterFraming); ElementClassFilter filterSymbol = new ElementClassFilter(typeof(FamilySymbol)); LogicalAndFilter andFilter = new LogicalAndFilter(orFilter, filterSymbol); // // without filtering for the structural categories, // our sample project was returning over 500 family symbols; // adding the category filters reduced this number to 40: // FilteredElementCollector collector2 = new FilteredElementCollector(doc); IList<Element> a2 = collector2.WherePasses(andFilter).ToElements(); foreach (FamilySymbol symbol in a2) { Autodesk.Revit.DB.ElementId categoryId = symbol.Category.Id; if (idFraming.Equals(categoryId)) { m_beambracesSymbolsMgr.AddSymbol(symbol); } else if (idColumn.Equals(categoryId)) { m_columnSymbolsMgr.AddSymbol(symbol); } } } /// <summary> /// validate the precondition to create framing /// </summary> private void Validate() { // level shouldn't less than 2 if (m_levels.Count < 2) { throw new ErrorMessageException("The level's number in active document is less than 2."); } // no Structural Column family is loaded in current document if (m_columnSymbolsMgr.Size == 0) { throw new ErrorMessageException("No Structural Column family is loaded in current project."); } // no Structural Beam family is loaded in current document if (m_beambracesSymbolsMgr.Size == 0) { throw new ErrorMessageException("No Structural Beam family is loaded in current project."); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; namespace Krystals4ObjectLibrary { public class Expansion { /// <summary> /// This constructor creates the strands from the strandNodeList and the expander. /// The expander has been checked to see that it satisfies the following conditions: /// 1. each gamete contains at least 1 point. /// 2. the smallest point value in each gamete is 1. /// 3. there are no duplicate values in a gamete. /// 4. the values in a gamete are contiguous (no gaps between the values). /// </summary> /// <param name="strandNodeList"></param> /// <param name="field"></param> public Expansion(List<StrandNode> strandNodeList, Expander expander) { Expand(strandNodeList, expander); } /// <summary> /// This constructor creates strands from the complete, checked inputs of its ExpansionKrystal argument. /// (No further checking is done.) /// </summary> /// <param name="ek">An expansion krystal with complete, checked inputs</param> public Expansion(ExpansionKrystal ek) { try { Expander expander = ek.Expander; expander.CalculateAbstractPointPositions(ek.DensityInputKrystal); List<StrandNode> strandNodeList = ek.StrandNodeList(); Expand(strandNodeList, expander); } catch(ApplicationException ex) { throw ex; } } /// <summary> /// This constructor creates strands from the complete, checked inputs of its ExpansionKrystal argument. /// (No further checking is done.) /// After expanding the strands normally, they are contoured. /// </summary> /// <param name="ek">An expansion krystal with complete, checked inputs</param> public Expansion(ShapedExpansionKrystal ek) { try { Expander expander = ek.Expander; expander.CalculateAbstractPointPositions(ek.DensityInputKrystal); List<StrandNode> strandNodeList = ek.StrandNodeList(); Expand(strandNodeList, expander); ContourStrands(strandNodeList, _strands); } catch(ApplicationException ex) { throw ex; } } private void Expand(List<StrandNode> strandNodeList, Expander expander) { #region preparation List<PointGroup> fixedInputPointGroups = expander.InputGamete.FixedPointGroups; List<PointGroup> fixedOutputPointGroups = expander.OutputGamete.FixedPointGroups; List<Planet> inputPlanets = expander.InputGamete.Planets; List<Planet> outputPlanets = expander.OutputGamete.Planets; List<TrammelMark> trammel = new List<TrammelMark>(); foreach(int value in expander.OutputGamete.Values) { TrammelMark tm = new TrammelMark(value); trammel.Add(tm); } uint[,] distances = new uint[expander.InputGamete.NumberOfValues, expander.OutputGamete.NumberOfValues]; CalculateFixedDistances(distances, fixedInputPointGroups, fixedOutputPointGroups); #endregion preparation #region expand strands int momentIndex = 0; foreach(StrandNode strandNode in strandNodeList) { int level = strandNode.strandLevel; int density = strandNode.strandDensity; int iPointValue = strandNode.strandPoint; int iPointIndex = iPointValue - 1; // the input point's index in the distances array #region calculate distances for planets where necessary. PointF? iPointPosition = null; if(inputPlanets.Count > 0) iPointPosition = InputPlanetPosition(momentIndex, iPointValue, inputPlanets); // iPointPosition == null if the current input point is not a planet // If the current input point is a planet, calculate distances to the fixed output points. if(iPointPosition != null && fixedOutputPointGroups.Count > 0) CalculateInputPlanetDistances(distances, iPointIndex, (PointF) iPointPosition, fixedOutputPointGroups); if(outputPlanets.Count > 0) { // If there are output planets, it is necessary to calculate their distances from the input point if(iPointPosition == null) // the input point is not a planet, so its a fixed point iPointPosition = FixedInputPointPosition(iPointValue, fixedInputPointGroups); if(iPointPosition == null) throw new ApplicationException("Error finding the position of an input point."); // There are output planets, so calculate their distances from the (planet or fixed)input point. CalculateOutputPlanetsDistances(momentIndex, distances, iPointIndex, (PointF) iPointPosition, outputPlanets); } #endregion calculate distances for planets where necessary foreach(TrammelMark tm in trammel) tm.Distance = distances[iPointIndex, tm.DistancesIndex]; Strand strand = ExpandStrand(level, density, trammel); _strands.Add(strand); momentIndex++; } #endregion expand strands } private void ContourStrands(List<StrandNode> contouredStrandNodeList, List<Strand> strands) { Debug.Assert(contouredStrandNodeList.Count == strands.Count); List<uint> tempList = new List<uint>(); int[] contour; for(int strandIndex = 0 ; strandIndex < _strands.Count ; strandIndex++) { if(contouredStrandNodeList[strandIndex] is ContouredStrandNode contouredStrandNode && contouredStrandNode.strandDensity > 1 && contouredStrandNode.strandDensity <= 7) { int density = contouredStrandNode.strandDensity; contour = K.Contour(density, contouredStrandNode.strandContour, contouredStrandNode.strandAxis); _strands[strandIndex].Values.Sort(); tempList.Clear(); for(int j = 0; j < density; j++) { tempList.Add(_strands[strandIndex].Values[contour[j] - 1]); } for(int j = 0; j < density; j++) { _strands[strandIndex].Values[j] = tempList[j]; } } } } #region private TrammelMark class private class TrammelMark { public TrammelMark(int value) { _value = value; _distancesIndex = value - 1; } #region Properties public uint Position { get { return _position; } set { _position = value; } } public uint Distance { get { return _distance; } set { _distance = value; } } public int DistancesIndex { get { return _distancesIndex; } } public int Value { get { return _value; } } public uint PositionKey { get { return (uint) (_position * 10000); } } // key in sorted expansion list #endregion Properties #region private variables private uint _position = 0; // the current position of this trammelMark in the distances expansion private uint _distance = 0; // the current distance to be added during expansion private readonly int _distancesIndex; // index in the distances array private readonly int _value; // this trammelMark's value #endregion private variables } #endregion private TrammelMark class #region public properties public List<Strand> Strands { get { return _strands; } } #endregion public Properties #region private functions /// <summary> /// This function is called once when beginning to expand the field. It calculates the distances between /// the fixed input and fixed output points, putting the result in the 'distances' array. /// </summary> /// <param name="distances">A two dimensional buffer which will contain the (squared) distances between the points.</param> /// <param name="inputPGs">The list of fixed input point groups</param> /// <param name="outputPGs">The list of fixed output point groups</param> private void CalculateFixedDistances(uint[,] distances, List<PointGroup> inputPGs, List<PointGroup> outputPGs) { foreach(PointGroup ipg in inputPGs) for(int iindex = 0 ; iindex < ipg.Count ; iindex++) { int iPointValue = (int) ipg.Value[iindex]; int iPointIndex = iPointValue - 1; PointF iPointPosition = ipg.WindowsPixelCoordinates[iindex]; foreach(PointGroup opg in outputPGs) for(int oindex = 0 ; oindex < opg.Count ; oindex++) { int oPointValue = (int) opg.Value[oindex]; int oPointIndex = oPointValue - 1; PointF oPointPosition = opg.WindowsPixelCoordinates[oindex]; distances[iPointIndex, oPointIndex] = SquaredDistance(iPointPosition, oPointPosition); } } } /// <summary> /// Returns the position of the planet with the given value if found, or null if there is no such planet. /// </summary> /// <param name="momentIndex">The 0-based moment index</param> /// <param name="planetValue">The value of the planet whose position should be returned.</param> /// <param name="inputPlanets">the list of input planets</param> /// <returns></returns> /// <summary> /// Returns the position of the planet with the given value if found, or null if there is no such planet. /// </summary> /// <param name="momentIndex">The 0-based moment index</param> /// <param name="planetValue">The value of the planet whose position should be returned.</param> /// <param name="inputPlanets">the list of input planets</param> /// <returns></returns> private PointF? InputPlanetPosition(int momentIndex, int planetValue, List<Planet> inputPlanets) { Planet planet = null; PointF? position = null; foreach(Planet p in inputPlanets) { if(p.Value == planetValue) { planet = p; break; } } if(planet != null) { //int indexInSubpath = momentIndex; foreach(PointGroup pg in planet.Subpaths) { if(momentIndex >= pg.Count) momentIndex -= (int) pg.Count; else { position = pg.WindowsPixelCoordinates[momentIndex]; break; } } } /////////////////////////////////////// //{ // //int indexInSubpath = momentIndex; // for (int i = 0; i < planet.Subpaths.Count; i++) // { // if (momentIndex >= planet.Subpaths[i].Count) // momentIndex -= (int)planet.Subpaths[i].Count; // else // { // position = planet.Subpaths[i].WindowsPixelCoordinates[momentIndex]; // break; // } // } //} ///////////////////////////////////// //{ // int indexInSubpath = momentIndex; // for (int i = 0; i < planet.Subpaths.Count; i++) // { // if (indexInSubpath >= planet.Subpaths[i].Count) // indexInSubpath -= (int)planet.Subpaths[i].Count; // else // { // position = planet.Subpaths[i].WindowsPixelCoordinates[indexInSubpath]; // break; // } // } //} return position; } /// <summary> /// This function is called if the input value is that of a planet, when beginning to expand each strand. /// It calculates the distances between the input planet and the fixed output points, putting the result /// in the 'distances' array. /// </summary> /// <param name="distances">A two dimensional buffer which will contain the (squared) distances between the points.</param> /// <param name="iPlanetPosition">The current position of the input planet</param> /// <param name="iPlanetValue">The value of the input planet</param> /// <param name="fixedOutputPointGroups">The list of fixed output point groups</param> private void CalculateInputPlanetDistances(uint[,] distances, int iPlanetIndex, PointF iPlanetPosition, List<PointGroup> fixedOutputPointGroups) { foreach(PointGroup opg in fixedOutputPointGroups) for(int oindex = 0 ; oindex < opg.Count ; oindex++) { int oPointIndex = (int) opg.Value[oindex] - 1; PointF oPointPosition = opg.WindowsPixelCoordinates[oindex]; distances[iPlanetIndex, oPointIndex] = SquaredDistance(iPlanetPosition, oPointPosition); } } /// <summary> /// Called when beginning to expand a strand if the input point is fixed and there are output planets. /// </summary> /// <param name="iPointValue">The value of the point whose position is required.</param> /// <param name="fixedInputPointGroups">The list of fixed input point groups</param> /// <returns>The position of the fixed point with the given value.</returns> private PointF? FixedInputPointPosition(int iPointValue, List<PointGroup> fixedInputPointGroups) { PointF? rPointF = null; bool found = false; foreach(PointGroup pg in fixedInputPointGroups) { for(int i = 0 ; i < pg.Count ; i++) { if(iPointValue == pg.Value[i]) { rPointF = pg.WindowsPixelCoordinates[i]; found = true; break; } } if(found) break; } return (rPointF); } /// <summary> /// This function is called if there are any output planets, when beginning to expand each strand. /// It calculates the distances between the input point having value 'pointValue' (the point may be /// either a fixed point or a planet) and the output planets. /// </summary> /// <param name="momentIndex">The current moment index (base 0)</param> /// <param name="distances">A two dimensional buffer which will contain the (squared) distances between the points.</param> /// <param name="pointValue">The value of the input point</param> /// <param name="outputPlanets">The list of output planets</param> private void CalculateOutputPlanetsDistances(int momentIndex, uint[,] distances, int iPointIndex, PointF iPointPosition, List<Planet> outputPlanets) { PointF? oPosition = null; foreach(Planet oPlanet in outputPlanets) { foreach(PointGroup opg in oPlanet.Subpaths) { if(momentIndex >= opg.WindowsPixelCoordinates.Length) momentIndex -= opg.WindowsPixelCoordinates.Length; else { oPosition = opg.WindowsPixelCoordinates[momentIndex]; break; } } if(oPosition == null) throw new ApplicationException("Error finding the position of an output planet."); distances[iPointIndex, (int) oPlanet.Value - 1] = SquaredDistance(iPointPosition, (PointF) oPosition); } } /// <summary> /// Returns the distance between the two points, to the power of two, as an unsigned integer. /// The distances are rounded (down and up) to the nearest integral value. /// </summary> /// <param name="inP">the input ('expansion') point</param> /// <param name="outP">the output point (or 'focus')</param> /// <returns></returns> private uint SquaredDistance(PointF inP, PointF outP) { float x = inP.X - outP.X; float y = inP.Y - outP.Y; float result = ((x * x) + (y * y)); uint uintResult = (uint) result; float diff = result - uintResult; if(diff >= 0.5f) uintResult++; return uintResult; } private Strand ExpandStrand(int level, int density, List<TrammelMark> trammel) { Strand strand = new Strand((uint) level); SortedList<uint, TrammelMark> expansion = new SortedList<uint, TrammelMark>(); // First add each trammel mark's distance to its current position... for(int i = 0 ; i < trammel.Count ; i++) { trammel[i].Position += trammel[i].Distance; uint positionKey = trammel[i].PositionKey; while(expansion.ContainsKey(positionKey)) positionKey += 1; // resolves positions which would otherwise be identical expansion.Add(positionKey, trammel[i]); } // Now construct the strand. for(int i = 0 ; i < density ; i++) { TrammelMark tm = expansion.Values[0]; strand.Values.Add((uint) tm.Value); expansion.RemoveAt(0); tm.Position += tm.Distance; uint positionKey = tm.PositionKey; while(expansion.ContainsKey(positionKey)) positionKey += 1; // resolves positions which would otherwise be identical expansion.Add(positionKey, tm); } // The strand is complete. // Now reset the trammel so that the smallest trammel mark position is 0. // First, remove unused distances... expansion.Clear(); for(int i = 0 ; i < trammel.Count ; i++) { trammel[i].Position -= trammel[i].Distance; uint positionKey = trammel[i].PositionKey; while(expansion.ContainsKey(positionKey)) positionKey += 1; // resolves positions which would otherwise be identical expansion.Add(positionKey, trammel[i]); } // Second, subtract the first trammel mark position from all trammel marks. uint minPos = expansion.Values[0].Position; foreach(TrammelMark tm in trammel) tm.Position -= minPos; return strand; } #endregion private functions #region private variables //private Dictionary<int, int> _inputIndexDict = new Dictionary<int, int>(); //private Dictionary<int, int> _outputIndexDict = new Dictionary<int, int>(); private List<Strand> _strands = new List<Strand>(); #endregion private variables } }
// 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.Text; using System.Diagnostics; namespace System.IO { // This abstract base class represents a writer that can write // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); protected Stream OutStream; private byte[] _buffer; // temp space for writing primitives to. private Encoding _encoding; private Encoder _encoder; private bool _leaveOpen; // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; // Protected default constructor that sets the output stream // to a null stream (a bit bucket). protected BinaryWriter() { OutStream = Stream.Null; _buffer = new byte[16]; _encoding = new UTF8Encoding(false, true); _encoder = _encoding.GetEncoder(); } public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false) { } public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false) { } public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } if (!output.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } OutStream = output; _buffer = new byte[16]; _encoding = encoding; _encoder = _encoding.GetEncoder(); _leaveOpen = leaveOpen; } protected virtual void Dispose(bool disposing) { if (disposing) { if (_leaveOpen) { OutStream.Flush(); } else { OutStream.Dispose(); } } } public void Dispose() { Dispose(true); } /* * Returns the stream associate with the writer. It flushes all pending * writes before returning. All subclasses should override Flush to * ensure that all buffered data is sent to the stream. */ public virtual Stream BaseStream { get { Flush(); return OutStream; } } // Clears all buffers for this writer and causes any buffered data to be // written to the underlying device. public virtual void Flush() { OutStream.Flush(); } public virtual long Seek(int offset, SeekOrigin origin) { return OutStream.Seek(offset, origin); } // Writes a boolean to this stream. A single byte is written to the stream // with the value 0 representing false or the value 1 representing true. // public virtual void Write(bool value) { _buffer[0] = (byte)(value ? 1 : 0); OutStream.Write(_buffer, 0, 1); } // Writes a byte to this stream. The current position of the stream is // advanced by one. // public virtual void Write(byte value) { OutStream.WriteByte(value); } // Writes a signed byte to this stream. The current position of the stream // is advanced by one. // [CLSCompliant(false)] public virtual void Write(sbyte value) { OutStream.WriteByte((byte)value); } // Writes a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } OutStream.Write(buffer, 0, buffer.Length); } // Writes a section of a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer, int index, int count) { OutStream.Write(buffer, index, count); } // Writes a character to this stream. The current position of the stream is // advanced by two. // Note this method cannot handle surrogates properly in UTF-8. // public unsafe virtual void Write(char ch) { if (char.IsSurrogate(ch)) { throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar); } Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); int numBytes = 0; char[] chBuf = new char[] { ch }; numBytes = _encoder.GetBytes(chBuf, 0, 1, _buffer, 0, true); OutStream.Write(_buffer, 0, numBytes); } // Writes a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars) { if (chars == null) { throw new ArgumentNullException(nameof(chars)); } byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length); OutStream.Write(bytes, 0, bytes.Length); } // Writes a section of a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars, int index, int count) { byte[] bytes = _encoding.GetBytes(chars, index, count); OutStream.Write(bytes, 0, bytes.Length); } // Writes a double to this stream. The current position of the stream is // advanced by eight. // public unsafe virtual void Write(double value) { ulong TmpValue = *(ulong*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); _buffer[4] = (byte)(TmpValue >> 32); _buffer[5] = (byte)(TmpValue >> 40); _buffer[6] = (byte)(TmpValue >> 48); _buffer[7] = (byte)(TmpValue >> 56); OutStream.Write(_buffer, 0, 8); } public virtual void Write(decimal value) { int[] bits = decimal.GetBits(value); Debug.Assert(bits.Length == 4); int lo = bits[0]; _buffer[0] = (byte)lo; _buffer[1] = (byte)(lo >> 8); _buffer[2] = (byte)(lo >> 16); _buffer[3] = (byte)(lo >> 24); int mid = bits[1]; _buffer[4] = (byte)mid; _buffer[5] = (byte)(mid >> 8); _buffer[6] = (byte)(mid >> 16); _buffer[7] = (byte)(mid >> 24); int hi = bits[2]; _buffer[8] = (byte)hi; _buffer[9] = (byte)(hi >> 8); _buffer[10] = (byte)(hi >> 16); _buffer[11] = (byte)(hi >> 24); int flags = bits[3]; _buffer[12] = (byte)flags; _buffer[13] = (byte)(flags >> 8); _buffer[14] = (byte)(flags >> 16); _buffer[15] = (byte)(flags >> 24); OutStream.Write(_buffer, 0, 16); } // Writes a two-byte signed integer to this stream. The current position of // the stream is advanced by two. // public virtual void Write(short value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a two-byte unsigned integer to this stream. The current position // of the stream is advanced by two. // [CLSCompliant(false)] public virtual void Write(ushort value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a four-byte signed integer to this stream. The current position // of the stream is advanced by four. // public virtual void Write(int value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a four-byte unsigned integer to this stream. The current position // of the stream is advanced by four. // [CLSCompliant(false)] public virtual void Write(uint value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes an eight-byte signed integer to this stream. The current position // of the stream is advanced by eight. // public virtual void Write(long value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes an eight-byte unsigned integer to this stream. The current // position of the stream is advanced by eight. // [CLSCompliant(false)] public virtual void Write(ulong value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes a float to this stream. The current position of the stream is // advanced by four. // public unsafe virtual void Write(float value) { uint TmpValue = *(uint*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a length-prefixed string to this stream in the BinaryWriter's // current Encoding. This method first writes the length of the string as // a four-byte unsigned integer, and then writes that many characters // to the stream. // public unsafe virtual void Write(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } int len = _encoding.GetByteCount(value); Write7BitEncodedInt(len); if (_largeByteBuffer == null) { _largeByteBuffer = new byte[LargeByteBufferSize]; _maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount(1); } if (len <= LargeByteBufferSize) { _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0); OutStream.Write(_largeByteBuffer, 0, len); } else { // Aggressively try to not allocate memory in this loop for // runtime performance reasons. Use an Encoder to write out // the string correctly (handling surrogates crossing buffer // boundaries properly). int charStart = 0; int numLeft = value.Length; #if DEBUG int totalBytes = 0; #endif while (numLeft > 0) { // Figure out how many chars to process this round. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft; int byteLen; byteLen = _encoder.GetBytes(value.ToCharArray(), charStart, charCount, _largeByteBuffer, 0, charCount == numLeft); #if DEBUG totalBytes += byteLen; Debug.Assert(totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write(_largeByteBuffer, 0, byteLen); charStart += charCount; numLeft -= charCount; } #if DEBUG Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } protected void Write7BitEncodedInt(int value) { // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint)value; // support negative numbers while (v >= 0x80) { Write((byte)(v | 0x80)); v >>= 7; } Write((byte)v); } } }
/* Copyright (c) 2004-2006 Jan Benda and Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Text; using System.Collections; using System.ComponentModel; using PHP.Core; #if SILVERLIGHT using PHP.CoreCLR; using MathEx = PHP.CoreCLR.MathEx; #else using MathEx = System.Math; using System.Diagnostics; #endif namespace PHP.Library { /// <summary> /// Implements PHP mathematical functions and constants. /// </summary> /// <threadsafety static="true"/> public static class PhpMath { #region Per-request Random Number Generators /// <summary> /// Gets an initialized random number generator associated with the current thread. /// </summary> internal static Random Generator { get { if (_generator == null) _generator = new Random(unchecked((int)DateTime.UtcNow.ToFileTime())); return _generator; } } #if !SILVERLIGHT [ThreadStatic] #endif private static Random _generator; /// <summary> /// Gets an initialized Mersenne Twister random number generator associated with the current thread. /// </summary> internal static MersenneTwister MTGenerator { get { if (_mtGenerator == null) _mtGenerator = new MersenneTwister(unchecked((uint)DateTime.UtcNow.ToFileTime())); return _mtGenerator; } } #if !SILVERLIGHT [ThreadStatic] #endif private static MersenneTwister _mtGenerator; /// <summary> /// Registers <see cref="ClearGenerators"/> routine to be called on request end. /// </summary> static PhpMath() { RequestContext.RequestEnd += new Action(ClearGenerators); } /// <summary> /// Nulls <see cref="_generator"/> and <see cref="_mtGenerator"/> fields on request end. /// </summary> private static void ClearGenerators() { _generator = null; _mtGenerator = null; } #endregion #region Constants [ImplementsConstant("M_PI")] public const double Pi = System.Math.PI; [ImplementsConstant("M_E")] public const double E = System.Math.E; [ImplementsConstant("M_LOG2E")] public const double Log2e = 1.4426950408889634074; [ImplementsConstant("M_LOG10E")] public const double Log10e = 0.43429448190325182765; [ImplementsConstant("M_LN2")] public const double Ln2 = 0.69314718055994530942; [ImplementsConstant("M_LN10")] public const double Ln10 = 2.30258509299404568402; [ImplementsConstant("M_PI_2")] public const double PiHalf = 1.57079632679489661923; [ImplementsConstant("M_PI_4")] public const double PiFourth = 0.78539816339744830962; [ImplementsConstant("M_1_PI")] public const double Pith = 0.31830988618379067154; [ImplementsConstant("M_2_PI")] public const double TwoPiths = 0.63661977236758134308; [ImplementsConstant("M_SQRTPI")] public const double SqrtPi = 1.77245385090551602729; [ImplementsConstant("M_2_SQRTPI")] public const double TwoSqrtPi = 1.12837916709551257390; [ImplementsConstant("M_SQRT3")] public const double Sqrt3 = 1.73205080756887729352; [ImplementsConstant("M_SQRT1_2")] public const double SqrtHalf = 0.70710678118654752440; [ImplementsConstant("M_LNPI")] public const double LnPi = 1.14472988584940017414; [ImplementsConstant("M_EULER")] public const double Euler = 0.57721566490153286061; [ImplementsConstant("NAN")] public const double NaN = Double.NaN; [ImplementsConstant("INF")] public const double Infinity = Double.PositiveInfinity; #endregion #region Absolutize Range /// <summary> /// Absolutizes range specified by an offset and a length relatively to a dimension of an array. /// </summary> /// <param name="count">The number of items in array. Should be non-negative.</param> /// <param name="offset"> /// The offset of the range relative to the beginning (if non-negative) or the end of the array (if negative). /// If the offset underflows or overflows the length is shortened appropriately. /// </param> /// <param name="length"> /// The length of the range if non-negative. Otherwise, its absolute value is the number of items /// which will not be included in the range from the end of the array. In the latter case /// the range ends with the |<paramref name="length"/>|-th item from the end of the array (counting from zero). /// </param> /// <remarks> /// Ensures that <c>[offset,offset + length]</c> is subrange of <c>[0,count]</c>. /// </remarks> public static void AbsolutizeRange(ref int offset, ref int length, int count) { Debug.Assert(count >= 0); // prevents overflows: if (offset >= count || count == 0) { offset = count; length = 0; return; } // negative offset => offset is relative to the end of the string: if (offset < 0) { offset += count; if (offset < 0) offset = 0; } Debug.Assert(offset >= 0 && offset < count); if (length < 0) { // there is count-offset items from offset to the end of array, // the last |length| items is taken away: length = count - offset + length; if (length < 0) length = 0; } else if ((long)offset + length > count) { // interval ends on the end of array: length = count - offset; } Debug.Assert(length >= 0 && offset + length <= count); } #endregion #region rand, srand, getrandmax, uniqid, lcg_value /// <summary> /// Gets <c>0</c> or <c>1</c> randomly. /// </summary> static int Random01() { return (int)Math.Round(Generator.NextDouble()); } /// <summary> /// Seed the random number generator. No return value. /// </summary> [ImplementsFunction("srand")] public static void Seed() { _generator = new Random(); } /// <summary> /// Seed the random number generator. No return value. /// </summary> /// <param name="seed">Optional seed value.</param> [ImplementsFunction("srand")] public static void Seed(int seed) { _generator = new Random(seed); } /// <summary> /// Show largest possible random value. /// </summary> /// <returns>The largest possible random value returned by rand().</returns> [ImplementsFunction("getrandmax")] public static int GetMaxRandomValue() { return Int32.MaxValue; } /// <summary> /// Generate a random integer. /// </summary> /// <returns>A pseudo random value between 0 and getrandmax(), inclusive.</returns> [ImplementsFunction("rand")] public static int Random() { return Generator.Next() + Random01(); } /// <summary> /// Generate a random integer. /// </summary> /// <param name="min">The lowest value to return.</param> /// <param name="max">The highest value to return.</param> /// <returns>A pseudo random value between min and max, inclusive. </returns> [ImplementsFunction("rand")] public static int Random(int min, int max) { if (min > max) return Random(max, min); if (min == max) return min; if (max == int.MaxValue) return Generator.Next(min, int.MaxValue) + Random01(); return Generator.Next(min, max + 1); } /// <summary> /// Generate a unique ID. /// Gets a prefixed unique identifier based on the current time in microseconds. /// </summary> /// <returns>Returns the unique identifier, as a string.</returns> [ImplementsFunction("uniqid")] public static string UniqueId() { return UniqueId(null, false); } /// <summary> /// Generate a unique ID. /// Gets a prefixed unique identifier based on the current time in microseconds. /// </summary> /// <param name="prefix">Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. /// With an empty prefix , the returned string will be 13 characters long. /// </param> /// <returns>Returns the unique identifier, as a string.</returns> [ImplementsFunction("uniqid")] public static string UniqueId(string prefix) { return UniqueId(prefix, false); } /// <summary> /// Generate a unique ID. /// </summary> /// <remarks> /// With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters. /// </remarks> /// <param name="prefix">Use the specified prefix.</param> /// <param name="more_entropy">Use LCG to generate a random postfix.</param> /// <returns>A pseudo-random string composed from the given prefix, current time and a random postfix.</returns> [ImplementsFunction("uniqid")] public static string UniqueId(string prefix, bool more_entropy) { // Note that Ticks specify time in 100nanoseconds but it is raised each 100144 // ticks which is around 10 times a second (the same for Milliseconds). string ticks = String.Format("{0:X}", DateTime.Now.Ticks + Generator.Next()); ticks = ticks.Substring(ticks.Length - 13); if (prefix == null) prefix = ""; if (more_entropy) { string rnd = LcgValue().ToString(); rnd = rnd.Substring(2, 8); return String.Format("{0}{1}.{2}", prefix, ticks, rnd); } else return String.Format("{0}{1}", prefix, ticks); } /// <summary> /// Generates a pseudo-random number using linear congruential generator in the range of (0,1). /// </summary> /// <remarks> /// This method uses the Framwork <see cref="Random"/> generator /// which may or may not be the same generator as the PHP one (L(CG(2^31 - 85),CG(2^31 - 249))). /// </remarks> /// <returns></returns> [ImplementsFunction("lcg_value")] public static double LcgValue() { return Generator.NextDouble(); } #endregion #region mt_getrandmax, mt_rand, mt_srand [ImplementsFunction("mt_getrandmax")] public static int MtGetMaxRandomValue() { return Int32.MaxValue; } [ImplementsFunction("mt_rand")] public static int MtRandom() { return MTGenerator.Next(); } [ImplementsFunction("mt_rand")] public static int MtRandom(int min, int max) { return (min < max) ? MTGenerator.Next(min, max) : MTGenerator.Next(max, min); } /// <summary> /// Seed the better random number generator. /// No return value. /// </summary> [ImplementsFunction("mt_srand")] public static void MtSeed() { MtSeed(Generator.Next()); } /// <summary> /// Seed the better random number generator. /// No return value. /// </summary> /// <param name="seed">Optional seed value.</param> [ImplementsFunction("mt_srand")] public static void MtSeed(int seed) { MTGenerator.Seed(unchecked((uint)seed)); } #endregion #region is_nan,is_finite,is_infinite [ImplementsFunction("is_nan")] [PureFunction] public static bool IsNaN(double x) { return Double.IsNaN(x); } [ImplementsFunction("is_finite")] [PureFunction] public static bool IsFinite(double x) { return !Double.IsInfinity(x); } [ImplementsFunction("is_infinite")] [PureFunction] public static bool IsInfinite(double x) { return Double.IsInfinity(x); } #endregion #region decbin, bindec, decoct, octdec, dechex, hexdec, base_convert /// <summary> /// Converts the given number to int (if the number is whole /// and fits into the int's range). /// </summary> /// <param name="number"></param> /// <returns><c>int</c> representation of number if possible, otherwise a <c>double</c> representation.</returns> private static object ConvertToInt(double number) { if ((Math.Round(number) == number) && (number <= int.MaxValue) && (number >= int.MinValue)) { return (int)number; } return number; } /// <summary> /// Converts the lowest 32 bits of the given number to a binary string. /// </summary> /// <param name="number"></param> /// <returns></returns> [ImplementsFunction("decbin")] public static PhpBytes DecToBin(double number) { // Trim the number to the lower 32 binary digits. uint temp = unchecked((uint)number); return DoubleToBase(temp, 2); } /// <summary> /// Converts the lowest 32 bits of the given number to a binary string. /// </summary> /// <param name="number"></param> /// <returns></returns> [ImplementsFunction("decbin_unicode")] public static string DecToBinUnicode(double number) { // Trim the number to the lower 32 binary digits. uint temp = unchecked((uint)number); return DoubleToBaseUnicode(temp, 2); } /// <summary> /// Returns the decimal equivalent of the binary number represented by the binary_string argument. /// bindec() converts a binary number to an integer or, if needed for size reasons, double. /// </summary> /// <param name="str">The binary string to convert.</param> /// <returns>The decimal value of <paramref name="str"/>.</returns> [ImplementsFunction("bindec")] public static object BinToDec(PhpBytes str) { if (str == null) return 0; return ConvertToInt(BaseToDouble(str, 2)); } [ImplementsFunction("bindec_unicode")] public static object BinToDecUnicode(string str) { if (str == null) return 0; return ConvertToInt(BaseToDoubleUnicode(str, 2)); } /// <summary> /// Returns a string containing an octal representation of the given number argument. /// </summary> /// <param name="number">Decimal value to convert.</param> /// <returns>Octal string representation of <paramref name="number"/>.</returns> [ImplementsFunction("decoct")] public static PhpBytes DecToOct(int number) { return new PhpBytes(System.Convert.ToString(number, 8)); } [ImplementsFunction("decoct_unicode")] public static string DecToOctUnicode(int number) { return System.Convert.ToString(number, 8); } /// <summary> /// Returns the decimal equivalent of the octal number represented by the <paramref name="str"/> argument. /// </summary> /// <param name="str">The octal string to convert.</param> /// <returns>The decimal representation of <paramref name="str"/>.</returns> [ImplementsFunction("octdec")] public static object OctToDec(PhpBytes str) { if (str == null) return 0; return ConvertToInt(BaseToDouble(str, 8)); } [ImplementsFunction("octdec_unicode")] public static object OctToDecUnicode(string str) { if (str == null) return 0; return ConvertToInt(BaseToDoubleUnicode(str, 8)); } /// <summary> /// Returns a string containing a hexadecimal representation of the given number argument. /// </summary> /// <param name="number">Decimal value to convert.</param> /// <returns>Hexadecimal string representation of <paramref name="number"/>.</returns> [ImplementsFunction("dechex")] public static PhpBytes DecToHex(int number) { return new PhpBytes(System.Convert.ToString(number, 16)); } [ImplementsFunction("dechex_unicode")] public static string DecToHexUnicode(int number) { return System.Convert.ToString(number, 16); } /// <summary> /// Hexadecimal to decimal. /// Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number. /// hexdec() will ignore any non-hexadecimal characters it encounters. /// </summary> /// <param name="str">The hexadecimal string to convert.</param> /// <returns>The decimal representation of <paramref name="str"/>.</returns> [ImplementsFunction("hexdec")] public static object HexToDec(PhpBytes str) { if (str == null) return 0; return ConvertToInt(BaseToDouble(str, 16)); } [ImplementsFunction("hexdec_unicode")] public static object HexToDecUnicode(string str) { if (str == null) return 0; return ConvertToInt(BaseToDoubleUnicode(str, 16)); } public static double BaseToDouble(PhpBytes number, int fromBase) { if (number == null) { PhpException.ArgumentNull("number"); return 0.0; } if (fromBase < 2 || fromBase > 36) { PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds")); return 0.0; } double fnum = 0; for (int i = 0; i < number.Length; i++) { int digit = Core.Parsers.Convert.AlphaNumericToDigit((char)number.ReadonlyData[i]); if (digit < fromBase) fnum = fnum * fromBase + digit; } return fnum; } public static double BaseToDoubleUnicode(string number, int fromBase) { if (number == null) { PhpException.ArgumentNull("number"); return 0.0; } if (fromBase < 2 || fromBase > 36) { PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds")); return 0.0; } double fnum = 0; for (int i = 0; i < number.Length; i++) { int digit = Core.Parsers.Convert.AlphaNumericToDigit(number[i]); if (digit < fromBase) fnum = fnum * fromBase + digit; } return fnum; } private const string digitsUnicode = "0123456789abcdefghijklmnopqrstuvwxyz"; private static byte[] digits = new byte[] {(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',(byte)'8',(byte)'9', (byte)'a',(byte)'b',(byte)'c',(byte)'d',(byte)'e',(byte)'f',(byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n', (byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v',(byte)'w',(byte)'x',(byte)'y',(byte)'z' }; public static PhpBytes DoubleToBase(double number, int toBase) { if (toBase < 2 || toBase > 36) { PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds")); return PhpBytes.Empty; } // Don't try to convert infinity or NaN: if (Double.IsInfinity(number) || Double.IsNaN(number)) { PhpException.InvalidArgument("number", LibResources.GetString("arg:out_of_bounds")); return PhpBytes.Empty; } double fvalue = Math.Floor(number); /* floor it just in case */ if (Math.Abs(fvalue) < 1) return new PhpBytes(new byte[]{(byte)'0'}); System.Collections.Generic.List<byte> sb = new System.Collections.Generic.List<byte>(); while (Math.Abs(fvalue) >= 1) { double mod = Fmod(fvalue, toBase); int i = (int)mod; byte b = digits[i]; //sb.Append(digits[(int) fmod(fvalue, toBase)]); sb.Add(b); fvalue /= toBase; } sb.Reverse(); return new PhpBytes(sb.ToArray()); } public static string DoubleToBaseUnicode(double number, int toBase) { if (toBase < 2 || toBase > 36) { PhpException.InvalidArgument("toBase", LibResources.GetString("arg:out_of_bounds")); return String.Empty; } // Don't try to convert infinity or NaN: if (Double.IsInfinity(number) || Double.IsNaN(number)) { PhpException.InvalidArgument("number", LibResources.GetString("arg:out_of_bounds")); return String.Empty; } double fvalue = Math.Floor(number); /* floor it just in case */ if (Math.Abs(fvalue) < 1) return "0"; StringBuilder sb = new StringBuilder(); while (Math.Abs(fvalue) >= 1) { double mod = Fmod(fvalue, toBase); int i = (int)mod; char c = digitsUnicode[i]; //sb.Append(digits[(int) fmod(fvalue, toBase)]); sb.Append(c); fvalue /= toBase; } return PhpStrings.Reverse(sb.ToString()); } /// <summary> /// Convert a number between arbitrary bases. /// Returns a string containing number represented in base tobase. The base in which number is given is specified in <paramref name="fromBase"/>. Both <paramref name="fromBase"/> and <paramref name="toBase"/> have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. /// </summary> /// <param name="number">The number to convert</param> /// <param name="fromBase">The base <paramref name="number"/> is in.</param> /// <param name="toBase">The base to convert <paramref name="number"/> to</param> /// <returns><paramref name="number"/> converted to base <paramref name="toBase"/>.</returns> [ImplementsFunction("base_convert")] [return: CastToFalse] public static string BaseConvert(string number, int fromBase, int toBase) { double value; if (number == null) return "0"; try { value = BaseToDoubleUnicode(number, fromBase); } catch (ArgumentException) { PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "fromBase", fromBase)); return null; } try { return DoubleToBaseUnicode(value, toBase); } catch (ArgumentException) { PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "toBase", toBase)); return null; } } #endregion #region deg2rad, pi, cos, sin, tan, acos, asin, atan, atan2 /// <summary> /// Degrees to radians. /// </summary> /// <param name="degrees"></param> /// <returns></returns> [ImplementsFunction("deg2rad"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double DegreesToRadians(double degrees) { return degrees / 180 * Math.PI; } /// <summary> /// Radians to degrees. /// </summary> /// <param name="radians"></param> /// <returns></returns> [ImplementsFunction("rad2deg")] [PureFunction] public static double RadiansToDegrees(double radians) { return radians / Math.PI * 180; } /// <summary> /// Returns an approximation of pi. /// </summary> /// <returns>The value of pi as <c>double</c>.</returns> [ImplementsFunction("pi")] [PureFunction] public static double PI() { return Math.PI; } /// <summary> /// Returns the arc cosine of arg in radians. /// acos() is the complementary function of cos(), which means that <paramref name="x"/>==cos(acos(<paramref name="x"/>)) for every value of a that is within acos()' range. /// </summary> /// <param name="x">The argument to process.</param> /// <returns>The arc cosine of <paramref name="x"/> in radians.</returns> [ImplementsFunction("acos"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Acos(double x) { return Math.Acos(x); } /// <summary> /// Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that <paramref name="x"/>==sin(asin(<paramref name="x"/>)) for every value of a that is within asin()'s range. /// </summary> /// <param name="x">The argument to process.</param> /// <returns>The arc sine of <paramref name="x"/> in radians.</returns> [ImplementsFunction("asin"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Asin(double x) { return Math.Asin(x); } [ImplementsFunction("atan"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Atan(double x) { return Math.Atan(x); } [ImplementsFunction("atan2")] [PureFunction] public static double Atan2(double y, double x) { double rv = Math.Atan(y / x); if (x < 0) { return ((rv > 0) ? -Math.PI : Math.PI) + rv; } else return rv; } [ImplementsFunction("cos"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Cos(double x) { return Math.Cos(x); } [ImplementsFunction("sin"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Sin(double x) { return Math.Sin(x); } [ImplementsFunction("tan"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Tan(double x) { return Math.Tan(x); } #endregion #region cosh, sinh, tanh, acosh, asinh, atanh [ImplementsFunction("cosh")] [PureFunction] public static double Cosh(double x) { return Math.Cosh(x); } [ImplementsFunction("sinh")] [PureFunction] public static double Sinh(double x) { return Math.Sinh(x); } [ImplementsFunction("tanh")] [PureFunction] public static double Tanh(double x) { return Math.Tanh(x); } [ImplementsFunction("acosh")] [PureFunction] public static double Acosh(double x) { return Math.Log(x + Math.Sqrt(x * x - 1)); } [ImplementsFunction("asinh")] [PureFunction] public static double Asinh(double x) { return Math.Log(x + Math.Sqrt(x * x + 1)); } [ImplementsFunction("atanh")] [PureFunction] public static double Atanh(double x) { return Math.Log((1 + x) / (1 - x)) / 2; } #endregion #region exp, expm1, log, log10, log1p, pow, sqrt, hypot /// <summary> /// Returns <c>e</c> raised to the power of <paramref name="x"/>. /// </summary> [ImplementsFunction("exp"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Exp(double x) { return Math.Exp(x); } /// <summary> /// expm1() returns the equivalent to 'exp(arg) - 1' computed in a way that is accurate even /// if the value of arg is near zero, a case where 'exp (arg) - 1' would be inaccurate due to /// subtraction of two numbers that are nearly equal. /// </summary> /// <param name="x">The argument to process </param> [ImplementsFunction("expm1")] [PureFunction] [EditorBrowsable(EditorBrowsableState.Never)] public static double ExpM1(double x) { return Math.Exp(x) - 1.0; // TODO: implement exp(x)-1 for x near to zero } /// <summary> /// Returns the base-10 logarithm of <paramref name="x"/>. /// </summary> [ImplementsFunction("log10")] [PureFunction] public static double Log10(double x) { return Math.Log10(x); } [ImplementsFunction("log"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Log(double x) { return Math.Log(x); } /// <summary> /// If the optional <paramref name="logBase"/> parameter is specified, log() returns log(<paramref name="logBase"/>) <paramref name="x"/>, otherwise log() returns the natural logarithm of <paramref name="x"/>. /// </summary> [ImplementsFunction("log"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Log(double x, double logBase) { return MathEx.Log(x, logBase); } /// <summary> /// log1p() returns log(1 + number) computed in a way that is accurate even when the value /// of number is close to zero. log() might only return log(1) in this case due to lack of precision. /// </summary> /// <param name="x">The argument to process </param> /// <returns></returns> [ImplementsFunction("log1p")] [PureFunction] [EditorBrowsable(EditorBrowsableState.Never)] public static double Log1P(double x) { return Math.Log(x + 1.0); // TODO: implement log(x+1) for x near to zero } /// <summary> /// Returns <paramref name="base"/> raised to the power of <paramref name="exp"/>. /// </summary> [ImplementsFunction("pow")] [PureFunction] public static object Power(object @base, object exp) { double dbase, dexp; int ibase, iexp; long lbase, lexp; Core.Convert.NumberInfo info_base, info_exp; info_base = Core.Convert.ObjectToNumber(@base, out ibase, out lbase, out dbase); info_exp = Core.Convert.ObjectToNumber(exp, out iexp, out lexp, out dexp); if (((info_base | info_exp) & PHP.Core.Convert.NumberInfo.Double) == 0 && lexp >= 0) { // integer base, non-negative integer exp // long lpower; double dpower; if (!Power(lbase, lexp, out lpower, out dpower)) return dpower; if (lpower >= Int32.MinValue && lpower <= Int32.MaxValue) return (Int32)lpower; return lpower; } if (dbase < 0) { // cannot rount to integer: if (Math.Ceiling(dexp) > dexp) return Double.NaN; double result = Math.Pow(-dbase, dexp); return (Math.IEEERemainder(Math.Abs(dexp), 2.0) < 1.0) ? result : -result; } if (dexp < 0) return 1 / Math.Pow(dbase, -dexp); else return Math.Pow(dbase, dexp); } private static bool Power(long x, long y, out long longResult, out double doubleResult) { long l1 = 1, l2 = x; if (y == 0) // anything powered by 0 is 1 { doubleResult = longResult = 1; return true; } if (x == 0) // 0^(anything except 0) is 0 { doubleResult = longResult = 0; return true; } try { while (y >= 1) { if ((y & 1) != 0) { l1 *= l2; y--; } else { l2 *= l2; y /= 2; } } } catch(ArithmeticException) { longResult = 0;//ignored doubleResult = (double)l1 * Math.Pow(l2, y); return false; } // able to do it with longs doubleResult = longResult = l1; return true; } [ImplementsFunction("sqrt"/*, FunctionImplOptions.Special*/)] [PureFunction] public static double Sqrt(double x) { return Math.Sqrt(x); } [ImplementsFunction("hypot")] [PureFunction] public static double Hypotenuse(double x, double y) { return Math.Sqrt(x * x + y * y); } #endregion #region ceil, floor, round, abs, fmod, max, min /// <summary> /// Returns the next highest integer value by rounding up <paramref name="x"/> if necessary. /// </summary> /// <param name="x">The value to round.</param> /// <returns><paramref name="x"/> rounded up to the next highest integer. The return value of ceil() is still of type <c>double</c> as the value range of double is usually bigger than that of integer.</returns> [ImplementsFunction("ceil")] [PureFunction] public static double Ceiling(double x) { return Math.Ceiling(x); } /// <summary> /// Returns the next lowest integer value by rounding down <paramref name="x"/> if necessary. /// </summary> /// <param name="x">The numeric value to round.</param> /// <returns><paramref name="x"/> rounded to the next lowest integer. The return value of floor() is still of type <c>double</c> because the value range of double is usually bigger than that of integer.</returns> [ImplementsFunction("floor")] [PureFunction] public static double Floor(double x) { return Math.Floor(x); } /// <summary> /// Rounds a float. /// </summary> /// <param name="x">The value to round.</param> /// <returns>The rounded value.</returns> [ImplementsFunction("round")] [PureFunction] public static double Round(double x) { return RoundInternal(x, RoundMode.HalfUp); } /// <summary> /// Rounds a float. /// </summary> /// <param name="x">The value to round.</param> /// <param name="precision">The optional number of decimal digits to round to. Can be less than zero to ommit digits at the end. Default is <c>0</c>.</param> /// <returns>The rounded value.</returns> [ImplementsFunction("round")] [PureFunction] public static double Round(double x, int precision /*= 0*/) { return Round(x, precision, RoundMode.HalfUp); } /// <summary> /// <c>$mode</c> parameter for <see cref="Round(double,int,RoundMode)"/> function. /// </summary> public enum RoundMode : int { /// <summary> /// When a number is halfway between two others, it is rounded away from zero. /// </summary> [ImplementsConstant("PHP_ROUND_HALF_UP")] HalfUp = 1, /// <summary> /// When a number is halfway between two others, it is rounded to the zero. /// </summary> [ImplementsConstant("PHP_ROUND_HALF_DOWN")] HalfDown = 2, /// <summary> /// When a number is halfway between two others, it is rounded toward the nearest even number. /// </summary> [ImplementsConstant("PHP_ROUND_HALF_EVEN")] HalfEven = 3, /// <summary> /// When a number is halfway between two others, it is rounded toward the nearest odd number. /// </summary> [ImplementsConstant("PHP_ROUND_HALF_ODD")] HalfOdd = 4, } #region Round Helpers /// <summary> /// Returns precise value of 10^<paramref name="power"/>. /// </summary> private static double Power10Value(int power) { switch (power) { case -15: return .000000000000001; case -14: return .00000000000001; case -13: return .0000000000001; case -12: return .000000000001; case -11: return .00000000001; case -10: return .0000000001; case -9: return .000000001; case -8: return .00000001; case -7: return .0000001; case -6: return .000001; case -5: return .00001; case -4: return .0001; case -3: return .001; case -2: return .01; case -1: return .1; case 0: return 1.0; case 1: return 10.0; case 2: return 100.0; case 3: return 1000.0; case 4: return 10000.0; case 5: return 100000.0; case 6: return 1000000.0; case 7: return 10000000.0; case 8: return 100000000.0; case 9: return 1000000000.0; case 10: return 10000000000.0; case 11: return 100000000000.0; case 12: return 1000000000000.0; case 13: return 10000000000000.0; case 14: return 100000000000000.0; case 15: return 1000000000000000.0; default: return Math.Pow(10.0, (double)power); } } private static double RoundInternal(double value, RoundMode mode) { double tmp_value; if (value >= 0.0) { tmp_value = Math.Floor(value + 0.5); if (mode != RoundMode.HalfUp) { if ((mode == RoundMode.HalfDown && value == (-0.5 + tmp_value)) || (mode == RoundMode.HalfEven && value == (0.5 + 2 * Math.Floor(tmp_value * .5))) || (mode == RoundMode.HalfOdd && value == (0.5 + 2 * Math.Floor(tmp_value * .5) - 1.0))) { tmp_value = tmp_value - 1.0; } } } else { tmp_value = Math.Ceiling(value - 0.5); if (mode != RoundMode.HalfUp) { if ((mode == RoundMode.HalfDown && value == (0.5 + tmp_value)) || (mode == RoundMode.HalfEven && value == (-0.5 + 2 * Math.Ceiling(tmp_value * .5))) || (mode == RoundMode.HalfOdd && value == (-0.5 + 2 * Math.Ceiling(tmp_value * .5) + 1.0))) { tmp_value = tmp_value + 1.0; } } } return tmp_value; } private static readonly double[] _Log10AbsValues = new[] { 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 1e23 }; private static int _Log10Abs(double value) { value = Math.Abs(value); if (value < 1e-8 || value > 1e23) { return (int)Math.Floor(Math.Log10(value)); } else { var values = _Log10AbsValues; /* Do a binary search with 5 steps */ var result = 16; if (value < values[result]) result -= 8; else result += 8; if (value < values[result]) result -= 4; else result += 4; if (value < values[result]) result -= 2; else result += 2; if (value < values[result]) result -= 1; else result += 1; if (value < values[result]) result -= 1; result -= 8; // return result; } } #endregion /// <summary> /// Rounds a float. /// </summary> /// <param name="x">The value to round.</param> /// <param name="precision">The optional number of decimal digits to round to. Can be less than zero to ommit digits at the end. Default is <c>0</c>.</param> /// <param name="mode">One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD. Default is <c>PHP_ROUND_HALF_UP</c>.</param> /// <returns>The rounded value.</returns> [ImplementsFunction("round")] [PureFunction] public static double Round(double x, int precision /*= 0*/, RoundMode mode /*= RoundMode.HalfUp*/) { if (Double.IsInfinity(x) || Double.IsNaN(x) || x == default(double)) return x; if (precision == 0) { return RoundInternal(x, mode); } else { if (precision > 23 || precision < -23) return x; // // Following code is taken from math.c to avoid incorrect .NET rounding // var precision_places = 14 - _Log10Abs(x); var f1 = Power10Value(precision); double tmp_value; /* If the decimal precision guaranteed by FP arithmetic is higher than the requested places BUT is small enough to make sure a non-zero value is returned, pre-round the result to the precision */ if (precision_places > precision && precision_places - precision < 15) { var f2 = Power10Value(precision_places); tmp_value = x * f2; /* preround the result (tmp_value will always be something * 1e14, thus never larger than 1e15 here) */ tmp_value = RoundInternal(tmp_value, mode); /* now correctly move the decimal point */ f2 = Power10Value(Math.Abs(precision - precision_places)); /* because places < precision_places */ tmp_value = tmp_value / f2; } else { /* adjust the value */ tmp_value = x * f1; /* This value is beyond our precision, so rounding it is pointless */ if (Math.Abs(tmp_value) >= 1e15) return x; } /* round the temp value */ tmp_value = RoundInternal(tmp_value, mode); /* see if it makes sense to use simple division to round the value */ //if (precision < 23 && precision > -23) { tmp_value = tmp_value / f1; } //else //{ // /* Simple division can't be used since that will cause wrong results. // Instead, the number is converted to a string and back again using // strtod(). strtod() will return the nearest possible FP value for // that string. */ // /* 40 Bytes should be more than enough for this format string. The // float won't be larger than 1e15 anyway. But just in case, use // snprintf() and make sure the buffer is zero-terminated */ // char buf[40]; // snprintf(buf, 39, "%15fe%d", tmp_value, -places); // buf[39] = '\0'; // tmp_value = zend_strtod(buf, NULL); // /* couldn't convert to string and back */ // if (!zend_finite(tmp_value) || zend_isnan(tmp_value)) { // tmp_value = value; // } //} return tmp_value; } } /// <summary> /// Returns the absolute value of <paramref name="x"/>. /// </summary> /// <param name="x">The numeric value to process.</param> /// <returns></returns> [ImplementsFunction("abs")] [PureFunction] public static object Abs(object x) { double dx; int ix; long lx; switch (Core.Convert.ObjectToNumber(x, out ix, out lx, out dx) & Core.Convert.NumberInfo.TypeMask) { case Core.Convert.NumberInfo.Double: return Math.Abs(dx); case Core.Convert.NumberInfo.Integer: if (ix == int.MinValue) return -lx; else return Math.Abs(ix); case Core.Convert.NumberInfo.LongInteger: if (lx == long.MinValue) return -dx; else return Math.Abs(lx); } return null; } /// <summary> /// Returns the floating point remainder (modulo) of the division of the arguments. /// </summary> /// <param name="x">The dividend.</param> /// <param name="y">The divisor.</param> /// <returns>The floating point remainder of <paramref name="x"/>/<paramref name="y"/>.</returns> [ImplementsFunction("fmod")] [PureFunction] public static double Fmod(double x, double y) { y = Math.Abs(y); double rem = Math.IEEERemainder(Math.Abs(x), y); if (rem < 0) rem += y; return (x >= 0) ? rem : -rem; } /// <summary> /// Find highest value. /// If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values. /// </summary> /// <param name="numbers">An array containing the values or values separately.</param> /// <returns>max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned. /// When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value. /// When given a string it will be cast as an integer when comparing.</returns> [ImplementsFunction("max")] [PureFunction] public static object Max(params object[] numbers) { return GetExtreme(numbers, true); } /// <summary> /// Find lowest value. /// If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values. /// </summary> /// <param name="numbers">An array containing the values or values separately.</param> /// <returns>min() returns the numerically lowest of the parameter values.</returns> [ImplementsFunction("min")] [PureFunction] public static object Min(params object[] numbers) { return GetExtreme(numbers, false); } internal static object GetExtreme(object[] numbers, bool maximum) { if ((numbers.Length == 1) && (numbers[0] is PhpArray)) { IEnumerable e = (numbers[0] as PhpArray).Values; Debug.Assert(e != null); return FindExtreme(e, maximum); } return FindExtreme(numbers, maximum); } internal static object FindExtreme(IEnumerable array, bool maximum) { object ex = null; int fact = maximum ? 1 : -1; foreach (object o in array) { if (ex == null) ex = o; else { if ((PhpComparer.Default.Compare(o, ex) * fact) > 0) ex = o; } } return ex; } #endregion } }
using System; using NBitcoin.BouncyCastle.Crypto.Parameters; namespace NBitcoin.BouncyCastle.Crypto.Modes { /** * implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher. */ public class CbcBlockCipher : IBlockCipher { private byte[] IV, cbcV, cbcNextV; private int blockSize; private IBlockCipher cipher; private bool encrypting; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of chaining. */ public CbcBlockCipher( IBlockCipher cipher) { this.cipher = cipher; this.blockSize = cipher.GetBlockSize(); this.IV = new byte[blockSize]; this.cbcV = new byte[blockSize]; this.cbcNextV = new byte[blockSize]; } /** * return the underlying block cipher that we are wrapping. * * @return the underlying block cipher that we are wrapping. */ public IBlockCipher GetUnderlyingCipher() { return cipher; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { bool oldEncrypting = this.encrypting; this.encrypting = forEncryption; if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length != blockSize) { throw new ArgumentException("initialisation vector must be the same length as block size"); } Array.Copy(iv, 0, IV, 0, iv.Length); parameters = ivParam.Parameters; } Reset(); // if null it's an IV changed only. if (parameters != null) { cipher.Init(encrypting, parameters); } else if (oldEncrypting != encrypting) { throw new ArgumentException("cannot change encrypting state without providing key."); } } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CBC". */ public string AlgorithmName { get { return cipher.AlgorithmName + "/CBC"; } } public bool IsPartialBlockOkay { get { return false; } } /** * return the block size of the underlying cipher. * * @return the block size of the underlying cipher. */ public int GetBlockSize() { return cipher.GetBlockSize(); } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { return (encrypting) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { Array.Copy(IV, 0, cbcV, 0, IV.Length); Array.Clear(cbcNextV, 0, cbcNextV.Length); cipher.Reset(); } /** * Do the appropriate chaining step for CBC mode encryption. * * @param in the array containing the data to be encrypted. * @param inOff offset into the in array the data starts at. * @param out the array the encrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ private int EncryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } /* * XOR the cbcV and the input, * then encrypt the cbcV */ for (int i = 0; i < blockSize; i++) { cbcV[i] ^= input[inOff + i]; } int length = cipher.ProcessBlock(cbcV, 0, outBytes, outOff); /* * copy ciphertext to cbcV */ Array.Copy(outBytes, outOff, cbcV, 0, cbcV.Length); return length; } /** * Do the appropriate chaining step for CBC mode decryption. * * @param in the array containing the data to be decrypted. * @param inOff offset into the in array the data starts at. * @param out the array the decrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ private int DecryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } Array.Copy(input, inOff, cbcNextV, 0, blockSize); int length = cipher.ProcessBlock(input, inOff, outBytes, outOff); /* * XOR the cbcV and the output */ for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] ^= cbcV[i]; } /* * swap the back up buffer into next position */ byte[] tmp; tmp = cbcV; cbcV = cbcNextV; cbcNextV = tmp; return length; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="CustomConversionGoalServiceClient"/> instances.</summary> public sealed partial class CustomConversionGoalServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomConversionGoalServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomConversionGoalServiceSettings"/>.</returns> public static CustomConversionGoalServiceSettings GetDefault() => new CustomConversionGoalServiceSettings(); /// <summary> /// Constructs a new <see cref="CustomConversionGoalServiceSettings"/> object with default settings. /// </summary> public CustomConversionGoalServiceSettings() { } private CustomConversionGoalServiceSettings(CustomConversionGoalServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateCustomConversionGoalsSettings = existing.MutateCustomConversionGoalsSettings; OnCopy(existing); } partial void OnCopy(CustomConversionGoalServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomConversionGoalServiceClient.MutateCustomConversionGoals</c> and /// <c>CustomConversionGoalServiceClient.MutateCustomConversionGoalsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCustomConversionGoalsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CustomConversionGoalServiceSettings"/> object.</returns> public CustomConversionGoalServiceSettings Clone() => new CustomConversionGoalServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomConversionGoalServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class CustomConversionGoalServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomConversionGoalServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomConversionGoalServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomConversionGoalServiceClientBuilder() { UseJwtAccessWithScopes = CustomConversionGoalServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomConversionGoalServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomConversionGoalServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomConversionGoalServiceClient Build() { CustomConversionGoalServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomConversionGoalServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomConversionGoalServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomConversionGoalServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomConversionGoalServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomConversionGoalServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomConversionGoalServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomConversionGoalServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomConversionGoalServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomConversionGoalServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CustomConversionGoalService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage custom conversion goal. /// </remarks> public abstract partial class CustomConversionGoalServiceClient { /// <summary> /// The default endpoint for the CustomConversionGoalService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CustomConversionGoalService scopes.</summary> /// <remarks> /// The default CustomConversionGoalService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CustomConversionGoalServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomConversionGoalServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomConversionGoalServiceClient"/>.</returns> public static stt::Task<CustomConversionGoalServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomConversionGoalServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomConversionGoalServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomConversionGoalServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomConversionGoalServiceClient"/>.</returns> public static CustomConversionGoalServiceClient Create() => new CustomConversionGoalServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomConversionGoalServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CustomConversionGoalServiceSettings"/>.</param> /// <returns>The created <see cref="CustomConversionGoalServiceClient"/>.</returns> internal static CustomConversionGoalServiceClient Create(grpccore::CallInvoker callInvoker, CustomConversionGoalServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomConversionGoalService.CustomConversionGoalServiceClient grpcClient = new CustomConversionGoalService.CustomConversionGoalServiceClient(callInvoker); return new CustomConversionGoalServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CustomConversionGoalService client</summary> public virtual CustomConversionGoalService.CustomConversionGoalServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomConversionGoalsResponse MutateCustomConversionGoals(MutateCustomConversionGoalsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomConversionGoalsResponse> MutateCustomConversionGoalsAsync(MutateCustomConversionGoalsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomConversionGoalsResponse> MutateCustomConversionGoalsAsync(MutateCustomConversionGoalsRequest request, st::CancellationToken cancellationToken) => MutateCustomConversionGoalsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose custom conversion goals are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual custom conversion goal. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomConversionGoalsResponse MutateCustomConversionGoals(string customerId, scg::IEnumerable<CustomConversionGoalOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomConversionGoals(new MutateCustomConversionGoalsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose custom conversion goals are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual custom conversion goal. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomConversionGoalsResponse> MutateCustomConversionGoalsAsync(string customerId, scg::IEnumerable<CustomConversionGoalOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomConversionGoalsAsync(new MutateCustomConversionGoalsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose custom conversion goals are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual custom conversion goal. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomConversionGoalsResponse> MutateCustomConversionGoalsAsync(string customerId, scg::IEnumerable<CustomConversionGoalOperation> operations, st::CancellationToken cancellationToken) => MutateCustomConversionGoalsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomConversionGoalService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage custom conversion goal. /// </remarks> public sealed partial class CustomConversionGoalServiceClientImpl : CustomConversionGoalServiceClient { private readonly gaxgrpc::ApiCall<MutateCustomConversionGoalsRequest, MutateCustomConversionGoalsResponse> _callMutateCustomConversionGoals; /// <summary> /// Constructs a client wrapper for the CustomConversionGoalService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CustomConversionGoalServiceSettings"/> used within this client. /// </param> public CustomConversionGoalServiceClientImpl(CustomConversionGoalService.CustomConversionGoalServiceClient grpcClient, CustomConversionGoalServiceSettings settings) { GrpcClient = grpcClient; CustomConversionGoalServiceSettings effectiveSettings = settings ?? CustomConversionGoalServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateCustomConversionGoals = clientHelper.BuildApiCall<MutateCustomConversionGoalsRequest, MutateCustomConversionGoalsResponse>(grpcClient.MutateCustomConversionGoalsAsync, grpcClient.MutateCustomConversionGoals, effectiveSettings.MutateCustomConversionGoalsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomConversionGoals); Modify_MutateCustomConversionGoalsApiCall(ref _callMutateCustomConversionGoals); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateCustomConversionGoalsApiCall(ref gaxgrpc::ApiCall<MutateCustomConversionGoalsRequest, MutateCustomConversionGoalsResponse> call); partial void OnConstruction(CustomConversionGoalService.CustomConversionGoalServiceClient grpcClient, CustomConversionGoalServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomConversionGoalService client</summary> public override CustomConversionGoalService.CustomConversionGoalServiceClient GrpcClient { get; } partial void Modify_MutateCustomConversionGoalsRequest(ref MutateCustomConversionGoalsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCustomConversionGoalsResponse MutateCustomConversionGoals(MutateCustomConversionGoalsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomConversionGoalsRequest(ref request, ref callSettings); return _callMutateCustomConversionGoals.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes custom conversion goals. Operation statuses /// are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCustomConversionGoalsResponse> MutateCustomConversionGoalsAsync(MutateCustomConversionGoalsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomConversionGoalsRequest(ref request, ref callSettings); return _callMutateCustomConversionGoals.Async(request, callSettings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Security; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { internal sealed class DynamicWinsockMethods { // In practice there will never be more than four of these, so its not worth a complicated // hash table structure. Store them in a list and search through it. private static List<DynamicWinsockMethods> s_methodTable = new List<DynamicWinsockMethods>(); public static DynamicWinsockMethods GetMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { lock (s_methodTable) { DynamicWinsockMethods methods; for (int i = 0; i < s_methodTable.Count; i++) { methods = s_methodTable[i]; if (methods._addressFamily == addressFamily && methods._socketType == socketType && methods._protocolType == protocolType) { return methods; } } methods = new DynamicWinsockMethods(addressFamily, socketType, protocolType); s_methodTable.Add(methods); return methods; } } private AddressFamily _addressFamily; private SocketType _socketType; private ProtocolType _protocolType; private object _lockObject; private AcceptExDelegate _acceptEx; private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs; private ConnectExDelegate _connectEx; private TransmitPacketsDelegate _transmitPackets; private WSARecvMsgDelegate _recvMsg; private WSARecvMsgDelegateBlocking _recvMsgBlocking; private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { _addressFamily = addressFamily; _socketType = socketType; _protocolType = protocolType; _lockObject = new object(); } public T GetDelegate<T>(SafeCloseSocket socketHandle) where T : class { if (typeof(T) == typeof(AcceptExDelegate)) { EnsureAcceptEx(socketHandle); Debug.Assert(_acceptEx != null); return (T)(object)_acceptEx; } else if (typeof(T) == typeof(GetAcceptExSockaddrsDelegate)) { EnsureGetAcceptExSockaddrs(socketHandle); Debug.Assert(_getAcceptExSockaddrs != null); return (T)(object)_getAcceptExSockaddrs; } else if (typeof(T) == typeof(ConnectExDelegate)) { EnsureConnectEx(socketHandle); Debug.Assert(_connectEx != null); return (T)(object)_connectEx; } else if (typeof(T) == typeof(WSARecvMsgDelegate)) { EnsureWSARecvMsg(socketHandle); Debug.Assert(_recvMsg != null); return (T)(object)_recvMsg; } else if (typeof(T) == typeof(WSARecvMsgDelegateBlocking)) { EnsureWSARecvMsgBlocking(socketHandle); Debug.Assert(_recvMsgBlocking != null); return (T)(object)_recvMsgBlocking; } else if (typeof(T) == typeof(TransmitPacketsDelegate)) { EnsureTransmitPackets(socketHandle); Debug.Assert(_transmitPackets != null); return (T)(object)_transmitPackets; } System.Diagnostics.Debug.Assert(false, "Invalid type passed to DynamicWinsockMethods.GetDelegate"); return null; } // Private methods that actually load the function pointers. private IntPtr LoadDynamicFunctionPointer(SafeCloseSocket socketHandle, ref Guid guid) { IntPtr ptr = IntPtr.Zero; int length; SocketError errorCode; unsafe { errorCode = Interop.Winsock.WSAIoctl( socketHandle, Interop.Winsock.IoctlSocketConstants.SIOGETEXTENSIONFUNCTIONPOINTER, ref guid, sizeof(Guid), out ptr, sizeof(IntPtr), out length, IntPtr.Zero, IntPtr.Zero); } if (errorCode != SocketError.Success) { throw new SocketException(); } return ptr; } // NOTE: the volatile writes in the functions below are necessary to ensure that all writes // to the fields of the delegate instances are visible before the write to the field // that holds the reference to the delegate instance. private void EnsureAcceptEx(SafeCloseSocket socketHandle) { if (_acceptEx == null) { lock (_lockObject) { if (_acceptEx == null) { Guid guid = new Guid("{0xb5367df1,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrAcceptEx = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _acceptEx, Marshal.GetDelegateForFunctionPointer<AcceptExDelegate>(ptrAcceptEx)); } } } } private void EnsureGetAcceptExSockaddrs(SafeCloseSocket socketHandle) { if (_getAcceptExSockaddrs == null) { lock (_lockObject) { if (_getAcceptExSockaddrs == null) { Guid guid = new Guid("{0xb5367df2,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrGetAcceptExSockaddrs = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _getAcceptExSockaddrs, Marshal.GetDelegateForFunctionPointer<GetAcceptExSockaddrsDelegate>(ptrGetAcceptExSockaddrs)); } } } } private void EnsureConnectEx(SafeCloseSocket socketHandle) { if (_connectEx == null) { lock (_lockObject) { if (_connectEx == null) { Guid guid = new Guid("{0x25a207b9,0x0ddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}"); IntPtr ptrConnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _connectEx, Marshal.GetDelegateForFunctionPointer<ConnectExDelegate>(ptrConnectEx)); } } } } private void EnsureWSARecvMsg(SafeCloseSocket socketHandle) { if (_recvMsg == null) { lock (_lockObject) { if (_recvMsg == null) { Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}"); IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid); _recvMsgBlocking = Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg); Volatile.Write(ref _recvMsg, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegate>(ptrWSARecvMsg)); } } } } private void EnsureWSARecvMsgBlocking(SafeCloseSocket socketHandle) { if (_recvMsgBlocking == null) { lock (_lockObject) { if (_recvMsgBlocking == null) { Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}"); IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _recvMsgBlocking, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg)); } } } } private void EnsureTransmitPackets(SafeCloseSocket socketHandle) { if (_transmitPackets == null) { lock (_lockObject) { if (_transmitPackets == null) { Guid guid = new Guid("{0xd9689da0,0x1f90,0x11d3,{0x99,0x71,0x00,0xc0,0x4f,0x68,0xc8,0x76}}"); IntPtr ptrTransmitPackets = LoadDynamicFunctionPointer(socketHandle, ref guid); Volatile.Write(ref _transmitPackets, Marshal.GetDelegateForFunctionPointer<TransmitPacketsDelegate>(ptrTransmitPackets)); } } } } } internal delegate bool AcceptExDelegate( SafeCloseSocket listenSocketHandle, SafeCloseSocket acceptSocketHandle, IntPtr buffer, int len, int localAddressLength, int remoteAddressLength, out int bytesReceived, SafeHandle overlapped); internal delegate void GetAcceptExSockaddrsDelegate( IntPtr buffer, int receiveDataLength, int localAddressLength, int remoteAddressLength, out IntPtr localSocketAddress, out int localSocketAddressLength, out IntPtr remoteSocketAddress, out int remoteSocketAddressLength); internal delegate bool ConnectExDelegate( SafeCloseSocket socketHandle, IntPtr socketAddress, int socketAddressSize, IntPtr buffer, int dataLength, out int bytesSent, SafeHandle overlapped); internal delegate SocketError WSARecvMsgDelegate( SafeCloseSocket socketHandle, IntPtr msg, out int bytesTransferred, SafeHandle overlapped, IntPtr completionRoutine); internal delegate SocketError WSARecvMsgDelegateBlocking( IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine); internal delegate bool TransmitPacketsDelegate( SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped, int flags); }
/* File : portfolio.cs Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved. Description : Presents several portfolio optimization models. Note: This example uses LINQ, which is only available in .NET Framework 3.5 and later. */ using System.IO; using System; using System.Linq; using System.Globalization; namespace mosek { namespace fusion { namespace examples { class MarkowitzData { /* Reads data from several files. */ private double[][] readlines(string f) { return File.ReadAllLines(f).Select(l => l.Split(',').Select(i => Double.Parse(i,CultureInfo.InvariantCulture)).ToArray()).ToArray(); } private double[] readfile(string f) { return File.ReadAllLines(f).Select(l => Double.Parse(l)).ToArray(); } public MarkowitzData(string name) { n = Int32.Parse(File.ReadAllText(name+"-n.txt")); gammas = readfile(name + "-gammas.csv"); mu = readfile(name + "-mu.csv"); GT = new DenseMatrix(readlines(name + "-GT.csv")); x0 = readfile(name + "-x0.csv"); w = Double.Parse(File.ReadAllText(name+"-w.csv")); } public int n; public double[] mu; public DenseMatrix GT; public double[] gammas; public double[] x0; public double w; } public class portfolio { public static double sum(double[] x) { double r = 0.0; for (int i = 0; i < x.Length; ++i) r += x[i]; return r; } public static double dot(double[] x, double[] y) { double r = 0.0; for (int i = 0; i < x.Length; ++i) r += x[i] * y[i]; return r; } /* Purpose: Computes the optimal portfolio for a given risk Input: n: Number of assets mu: An n dimmensional vector of expected returns GT: A matrix with n columns so (GT")*GT = covariance matrix" x0: Initial holdings w: Initial cash holding gamma: Maximum risk (=std. dev) accepted Output: Optimal expected return and the optimal portfolio */ public static double BasicMarkowitz ( int n, double[] mu, DenseMatrix GT, double[] x0, double w, double gamma) { using( Model M = new Model("Basic Markowitz")) { // Redirect log output from the solver to stdout for debugging. // ifuncommented. //M.SetLogHandler(Console.Out); // Defines the variables (holdings). Shortselling is not allowed. Variable x = M.Variable("x", n, Domain.GreaterThan(0.0)); // Maximize expected return M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu,x)); // The amount invested must be identical to intial wealth M.Constraint("budget", Expr.Sum(x), Domain.EqualsTo(w+sum(x0))); // Imposes a bound on the risk M.Constraint("risk", Expr.Vstack(Expr.ConstTerm(new double[] {gamma}),Expr.Mul(GT,x)), Domain.InQCone()); // Solves the model. M.Solve(); return dot(mu,x.Level()); } } /* Purpose: Computes several portfolios on the optimal portfolios by for alpha in alphas: maximize expected return - alpha * standard deviation subject to the constraints Input: n: Number of assets mu: An n dimmensional vector of expected returns GT: A matrix with n columns so (GT")*GT = covariance matrix" x0: Initial holdings w: Initial cash holding alphas: List of the alphas Output: The efficient frontier as list of tuples (alpha,expected return,risk) */ public static void EfficientFrontier ( int n, double[] mu, DenseMatrix GT, double[] x0, double w, double[] alphas, double[] frontier_mux, double[] frontier_s) { using(Model M = new Model("Efficient frontier")) { //M.SetLogHandler(Console.Out); // Defines the variables (holdings). Shortselling is not allowed. Variable x = M.Variable("x", n, Domain.GreaterThan(0.0)); // Portfolio variables Variable s = M.Variable("s", 1, Domain.Unbounded()); // Risk variable M.Constraint("budget", Expr.Sum(x), Domain.EqualsTo(w+sum(x0))); // Computes the risk M.Constraint("risk", Expr.Vstack(s.AsExpr(),Expr.Mul(GT,x)),Domain.InQCone()); for (int i = 0; i < alphas.Length; ++i) { // Define objective as a weighted combination of return and risk M.Objective("obj", ObjectiveSense.Maximize, Expr.Sub(Expr.Dot(mu,x),Expr.Mul(alphas[i],s))); M.Solve(); frontier_mux[i] = dot(mu,x.Level()); frontier_s[i] = s.Level()[0]; } } } /* Description: Extends the basic Markowitz model with a market cost term. Input: n: Number of assets mu: An n dimmensional vector of expected returns GT: A matrix with n columns so (GT')*GT = covariance matrix' x0: Initial holdings w: Initial cash holding gamma: Maximum risk (=std. dev) accepted m: It is assumed that market impact cost for the j'th asset is m_j|x_j-x0_j|^3/2 Output: Optimal expected return and the optimal portfolio */ public static void MarkowitzWithMarketImpact ( int n, double[] mu, DenseMatrix GT, double[] x0, double w, double gamma, double[] m, double[] xsol, double[] tsol) { using(Model M = new Model("Markowitz portfolio with market impact")) { //M.SetLogHandler(Console.Out); // Defines the variables. No shortselling is allowed. Variable x = M.Variable("x", n, Domain.GreaterThan(0.0)); // Addtional "helper" variables Variable t = M.Variable("t", n, Domain.Unbounded()); Variable z = M.Variable("z", n, Domain.Unbounded()); Variable v = M.Variable("v", n, Domain.Unbounded()); // Maximize expected return M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu,x)); // Invested amount + slippage cost = initial wealth M.Constraint("budget", Expr.Add(Expr.Sum(x),Expr.Dot(m,t)), Domain.EqualsTo(w+sum(x0))); // Imposes a bound on the risk M.Constraint("risk", Expr.Vstack(Expr.ConstTerm(new double[] {gamma}),Expr.Mul(GT,x)), Domain.InQCone()); // z >= |x-x0| M.Constraint("buy", Expr.Sub(z,Expr.Sub(x,x0)),Domain.GreaterThan(0.0)); M.Constraint("sell", Expr.Sub(z,Expr.Sub(x0,x)),Domain.GreaterThan(0.0)); // t >= z^1.5, z >= 0.0. Needs two rotated quadratic cones to model this term M.Constraint("ta", Expr.Hstack(v.AsExpr(),t.AsExpr(),z.AsExpr()),Domain.InRotatedQCone()); M.Constraint("tb", Expr.Hstack(z.AsExpr(),Expr.ConstTerm(n,1.0/8.0),v.AsExpr()), Domain.InRotatedQCone()); M.Solve(); if (xsol != null) Array.Copy(x.Level(),xsol,n); if (tsol != null) Array.Copy(t.Level(),tsol,n); } } /* Description: Extends the basic Markowitz model with a market cost term. Input: n: Number of assets mu: An n dimmensional vector of expected returns GT: A matrix with n columns so (GT")*GT = covariance matrix" x0: Initial holdings w: Initial cash holding gamma: Maximum risk (=std. dev) accepted f: If asset j is traded then a fixed cost f_j must be paid g: If asset j is traded then a cost g_j must be paid for each unit traded Output: Optimal expected return and the optimal portfolio */ public static double[] MarkowitzWithTransactionsCost ( int n, double[] mu, DenseMatrix GT, double[] x0, double w, double gamma, double[] f, double[] g) { // Upper bound on the traded amount double[] u = new double[n]; { double v = w+sum(x0); for (int i = 0; i < n; ++i) u[i] = v; } using( Model M = new Model("Markowitz portfolio with transaction costs") ) { Console.WriteLine("\n-------------------------------------------------------------------------"); Console.WriteLine("Markowitz portfolio optimization with transaction cost\n"); Console.WriteLine("------------------------------------------------------------------------\n"); //M.SetLogHandler(Console.Out); // Defines the variables. No shortselling is allowed. Variable x = M.Variable("x", n, Domain.GreaterThan(0.0)); // Addtional "helper" variables Variable z = M.Variable("z", n, Domain.Unbounded()); // Binary varables Variable y = M.Variable("y", n, Domain.InRange(0.0,1.0), Domain.IsInteger()); // Maximize expected return M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu,x)); // Invest amount + transactions costs = initial wealth M.Constraint("budget", Expr.Add(Expr.Add(Expr.Sum(x),Expr.Dot(f,y)),Expr.Dot(g,z)), Domain.EqualsTo(w+sum(x0))); // Imposes a bound on the risk M.Constraint("risk", Expr.Vstack(Expr.ConstTerm(new double[] {gamma}),Expr.Mul(GT,x)), Domain.InQCone()); // z >= |x-x0| M.Constraint("buy", Expr.Sub(z,Expr.Sub(x,x0)),Domain.GreaterThan(0.0)); M.Constraint("sell", Expr.Sub(z,Expr.Sub(x0,x)),Domain.GreaterThan(0.0)); //M.constraint("trade", Expr.hstack(z.asExpr(),Expr.sub(x,x0)), Domain.inQcone())" // Consraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j M.Constraint("y_on_off", Expr.Sub(z,Expr.Mul(Matrix.Diag(u),y)), Domain.LessThan(0.0)); // Integer optimization problems can be very hard to solve so limiting the // maximum amount of time is a valuable safe guard M.SetSolverParam("mioMaxTime", 180.0); M.Solve(); Console.WriteLine("Expected return: {0:e4} Std. deviation: {1:e4} Transactions cost: {2:e4}", dot(mu, x.Level()), gamma, dot(f, y.Level()) + dot(g, z.Level())); return x.Level(); } } /* The example python portfolio.py portfolio reads in data and solves the portfolio models. */ public static void Main(string[] argv) { string name = argv[0]; MarkowitzData d = new MarkowitzData(name); { Console.WriteLine("\n-------------------------------------------------------------------"); Console.WriteLine("Basic Markowitz portfolio optimization"); Console.WriteLine("---------------------------------------------------------------------\n"); for(int i = 0; i < d.gammas.Length; ++i) { double res = BasicMarkowitz(d.n, d.mu, d.GT, d.x0, d.w, d.gammas[i]); Console.WriteLine("Expected return: {0,-12:f4} Std. deviation: {1,-12:f4} ", res,d.gammas[i]); } } { // Some predefined alphas are chosen double[] alphas = { 0.0, 0.01, 0.1, 0.25, 0.30, 0.35, 0.4, 0.45, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 10.0 }; int niter = alphas.Length; double[] frontier_mux = new double[niter]; double[] frontier_s = new double[niter]; EfficientFrontier(d.n,d.mu,d.GT,d.x0,d.w,alphas, frontier_mux, frontier_s); Console.WriteLine("\n-------------------------------------------------------------------------"); Console.WriteLine("Efficient frontier\n") ; Console.WriteLine("------------------------------------------------------------------------\n"); Console.WriteLine("{0,-12} {1,-12} {2,-12}", "alpha","return","risk") ; for (int i = 0; i < frontier_mux.Length; ++i) Console.WriteLine("{0,-12:f4} {0,-12:e4} {0,-12:e4}\n", alphas[i],frontier_mux[i],frontier_s[i]); } { // Somewhat arbirtrary choice of m double[] m = new double[d.n]; for (int i = 0; i < d.n; ++i) m[i] = 1.0e-2; double[] x = new double[d.n]; double[] t = new double[d.n]; MarkowitzWithMarketImpact(d.n,d.mu,d.GT,d.x0,d.w,d.gammas[0],m, x,t); Console.WriteLine("\n-----------------------------------------------------------------------"); Console.WriteLine("Markowitz portfolio optimization with market impact cost\n"); Console.WriteLine("------------------------------------------------------------------------\n"); Console.WriteLine("Expected return: {0:e4} Std. deviation: {1:e4} Market impact cost: {2:e4}\n", dot(d.mu,x), d.gammas[0], dot(m,t)); } { double[] f = new double[d.n]; for (var i = 0; i < d.n; ++i) f[i] = 0.01; double[] g = new double[d.n]; for (var i = 0; i < d.n; ++i) g[i] = 0.001; MarkowitzWithTransactionsCost(d.n,d.mu,d.GT,d.x0,d.w,d.gammas[0],f,g); } } } } } }
// The MIT License // // Copyright (c) 2012-2015 Jordan E. Terrell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using NUnit.Framework; namespace iSynaptic.Commons.Runtime.Serialization { [TestFixture] public partial class CloneableTests { [Test] public void CanCloneTypesWithIndirectTypeRecursion() { Assert.IsTrue(Cloneable<ClassWithIndirectTypeRecursionLeft>.CanClone()); Assert.IsTrue(Cloneable<ClassWithIndirectTypeRecursionLeft>.CanShallowClone()); } [Test] public void CloneException() { var source = new Exception("Bad mojo!"); Assert.IsTrue(Cloneable<Exception>.CanClone()); Assert.IsTrue(Cloneable<Exception>.CanShallowClone()); var clone = Cloneable<Exception>.Clone(source); var shallowClone = Cloneable<Exception>.ShallowClone(source); Assert.IsFalse(ReferenceEquals(source, clone)); Assert.IsFalse(ReferenceEquals(source, shallowClone)); Assert.AreEqual(source.Message, clone.Message); Assert.AreEqual(source.Message, shallowClone.Message); } [Test] public void CloneClass() { var source = new CloneTestClass { FirstName = "John", LastName = "Doe" }; Assert.IsTrue(Cloneable<CloneTestClass>.CanClone()); Assert.IsTrue(Cloneable<CloneTestClass>.CanShallowClone()); var clone = Cloneable<CloneTestClass>.Clone(source); var shallowClone = Cloneable<CloneTestClass>.ShallowClone(source); Assert.IsFalse(ReferenceEquals(source, clone)); Assert.IsFalse(ReferenceEquals(source, shallowClone)); Assert.AreEqual("John", clone.FirstName); Assert.AreEqual("Doe", clone.LastName); Assert.AreEqual("John", shallowClone.FirstName); Assert.AreEqual("Doe", shallowClone.LastName); } [Test] public void CloneNullClass() { var clone = Cloneable<CloneTestClass>.Clone(null); var shallowClone = Cloneable<CloneTestClass>.ShallowClone(null); Assert.IsNull(clone); Assert.IsNull(shallowClone); } [Test] public void CloneSelfReferencingClass() { var source = new CloneTestClass { FirstName = "John", LastName = "Doe" }; source.InnerClass = source; var clone = Cloneable<CloneTestClass>.Clone(source); var shallowClone = Cloneable<CloneTestClass>.ShallowClone(source); Assert.IsFalse(object.ReferenceEquals(source, clone)); Assert.IsFalse(object.ReferenceEquals(source, shallowClone)); Assert.IsTrue(object.ReferenceEquals(clone, clone.InnerClass)); Assert.IsTrue(object.ReferenceEquals(shallowClone, shallowClone.InnerClass)); } [Test] public void CloneStructWithSelfReferencingClass() { var selfRefClass = new CloneTestClass { FirstName = "John", LastName = "Doe" }; selfRefClass.InnerClass = selfRefClass; var source = new StructWithReferenceToSelfReferencingClass {Class = selfRefClass}; var clone = Cloneable<StructWithReferenceToSelfReferencingClass>.Clone(source); var shallowClone = Cloneable<StructWithReferenceToSelfReferencingClass>.ShallowClone(source); Assert.IsFalse(object.ReferenceEquals(source.Class, clone.Class)); Assert.IsTrue(object.ReferenceEquals(source.Class, shallowClone.Class)); Assert.IsTrue(object.ReferenceEquals(clone.Class, clone.Class.InnerClass)); } [Test] public void CloneStruct() { var source = new CloneTestStruct { FirstName = "John", LastName = "Doe" }; Assert.IsTrue(Cloneable<CloneTestStruct>.CanClone()); Assert.IsTrue(Cloneable<CloneTestStruct>.CanShallowClone()); Assert.IsTrue(Cloneable<CloneTestStruct?>.CanClone()); Assert.IsTrue(Cloneable<CloneTestStruct?>.CanShallowClone()); var clone = Cloneable<CloneTestStruct>.Clone(source); var shallowClone = Cloneable<CloneTestStruct>.ShallowClone(source); Assert.AreEqual("John", clone.FirstName); Assert.AreEqual("Doe", clone.LastName); Assert.AreEqual("John", shallowClone.FirstName); Assert.AreEqual("Doe", shallowClone.LastName); clone = Cloneable<CloneTestStruct?>.Clone(source).Value; shallowClone = Cloneable<CloneTestStruct?>.ShallowClone(source).Value; Assert.AreEqual("John", clone.FirstName); Assert.AreEqual("Doe", clone.LastName); Assert.AreEqual("John", shallowClone.FirstName); Assert.AreEqual("Doe", shallowClone.LastName); Assert.IsNull(Cloneable<CloneTestStruct?>.Clone(null)); Assert.IsNull(Cloneable<CloneTestStruct?>.ShallowClone(null)); } [Test] public void CannotCloneClassWithIntPtrField() { Assert.IsFalse(Cloneable<ClassWithFuncField>.CanClone()); Assert.IsFalse(Cloneable<ClassWithFuncField>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncField>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncField>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncField>.Clone(new ClassWithFuncField())); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncField>.ShallowClone(new ClassWithFuncField())); } [Test] public void CannotCloneDerivedClassWithIntPtrField() { Assert.IsFalse(Cloneable<DerivedClassWithFuncField>.CanClone()); Assert.IsFalse(Cloneable<DerivedClassWithFuncField>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithFuncField>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithFuncField>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithFuncField>.Clone(new DerivedClassWithFuncField())); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithFuncField>.ShallowClone(new DerivedClassWithFuncField())); } [Test] public void CannotCloneClassWithDelegateField() { Assert.IsFalse(Cloneable<ClassWithDelegateField>.CanClone()); Assert.IsFalse(Cloneable<ClassWithDelegateField>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithDelegateField>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithDelegateField>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithDelegateField>.Clone(new ClassWithDelegateField())); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithDelegateField>.ShallowClone(new ClassWithDelegateField())); } [Test] public void CannotCloneDerivedClassWithDeletegateField() { Assert.IsFalse(Cloneable<DerivedClassWithDelegateField>.CanClone()); Assert.IsFalse(Cloneable<DerivedClassWithDelegateField>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithDelegateField>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithDelegateField>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithDelegateField>.Clone(new DerivedClassWithDelegateField())); Assert.Throws<InvalidOperationException>(() => Cloneable<DerivedClassWithDelegateField>.ShallowClone(new DerivedClassWithDelegateField())); } [Test] public void CannotCloneStructWithFuncField() { Assert.IsFalse(Cloneable<StructWithFuncField>.CanClone()); Assert.IsFalse(Cloneable<StructWithFuncField>.CanShallowClone()); Assert.IsFalse(Cloneable<StructWithFuncField?>.CanClone()); Assert.IsFalse(Cloneable<StructWithFuncField?>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField>.Clone(new StructWithFuncField())); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField>.ShallowClone(new StructWithFuncField())); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField?>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField?>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField?>.Clone(new StructWithFuncField())); Assert.Throws<InvalidOperationException>(() => Cloneable<StructWithFuncField?>.ShallowClone(new StructWithFuncField())); } [Test] public void CloneBidirectionalReferences() { var left = new CloneTestClass(); var right = new CloneTestClass(); left.InnerClass = right; right.InnerClass = left; var leftClone = Cloneable<CloneTestClass>.Clone(left); var rightClone = leftClone.InnerClass; Assert.IsFalse(object.ReferenceEquals(right, rightClone)); Assert.IsFalse(object.ReferenceEquals(rightClone.InnerClass, left)); Assert.IsTrue(object.ReferenceEquals(rightClone.InnerClass, leftClone)); leftClone = Cloneable<CloneTestClass>.ShallowClone(left); rightClone = leftClone.InnerClass; Assert.IsTrue(object.ReferenceEquals(right, rightClone)); Assert.IsTrue(object.ReferenceEquals(rightClone.InnerClass, left)); Assert.IsFalse(object.ReferenceEquals(rightClone.InnerClass, leftClone)); } [Test] public void CloneReferenceOnly() { var source = new ReferenceOnlyCloneTestClass(); source.InnerClass = new ReferenceOnlyCloneTestClass(); var clone = Cloneable<ReferenceOnlyCloneTestClass>.Clone(source); Assert.IsTrue(object.ReferenceEquals(source.InnerClass, clone.InnerClass)); } [Test] public void CannotCloneClassWithIllegalArrayFieldType() { Assert.IsFalse(Cloneable<ClassWithFuncArray>.CanClone()); Assert.IsFalse(Cloneable<ClassWithFuncArray>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncArray>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncArray>.ShallowClone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncArray>.Clone(new ClassWithFuncArray())); Assert.Throws<InvalidOperationException>(() => Cloneable<ClassWithFuncArray>.ShallowClone(new ClassWithFuncArray())); } [Test] public void CloneObjectHierarchy() { var parent = new ParentClass(); parent.Child = new ChildClass { Name = "John Doe" }; Assert.IsTrue(Cloneable<ParentClass>.CanClone()); Assert.IsTrue(Cloneable<ParentClass>.CanShallowClone()); var parentClone = Cloneable<ParentClass>.Clone(parent); Assert.IsFalse(object.ReferenceEquals(parent.Child, parentClone.Child)); Assert.AreEqual("John Doe", parentClone.Child.Name); } [Test] public void CannotCloneClassHierarchyWithIllegalFieldType() { Assert.IsFalse(Cloneable<ParentClassWithNonCloneableChild>.CanClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<ParentClassWithNonCloneableChild>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<ParentClassWithNonCloneableChild>.Clone(new ParentClassWithNonCloneableChild())); } [Test] public void ShallowCloneClassHierarchyWithIllegalFieldTypeInReferencedClass() { Assert.IsTrue(Cloneable<ParentClassWithNonCloneableChild>.CanShallowClone()); Assert.IsNull(Cloneable<ParentClassWithNonCloneableChild>.ShallowClone(null)); Assert.IsNotNull(Cloneable<ParentClassWithNonCloneableChild>.ShallowClone(new ParentClassWithNonCloneableChild())); } [Test] public void CloneClassWithNonSerializedIllegalField() { Assert.IsTrue(Cloneable<ClassWithNonSerializedIllegalField>.CanClone()); Assert.IsTrue(Cloneable<ClassWithNonSerializedIllegalField>.CanShallowClone()); var source = new ClassWithNonSerializedIllegalField { Name = "John Doe" }; var clone = Cloneable<ClassWithNonSerializedIllegalField>.Clone(source); Assert.IsNotNull(clone); clone = null; clone = Cloneable<ClassWithNonSerializedIllegalField>.ShallowClone(source); Assert.IsNotNull(clone); } [Test] public void CloneToWillOnAValueType() { var testClass = new CloneTestClass(); var source = new CloneTestStructWithClonableClassField {TestClass = new CloneTestClass {FirstName = "John", LastName = "Doe"}}; var dest = new CloneTestStructWithClonableClassField {TestClass = testClass}; var clone = source.CloneTo(dest); Assert.IsTrue(ReferenceEquals(testClass, clone.TestClass)); Assert.AreEqual("John", clone.TestClass.FirstName); Assert.AreEqual("Doe", clone.TestClass.LastName); } [Test] public void ShallowCloneToWillAValueType() { var testClass = new CloneTestClass {FirstName = "John", LastName = "Doe"}; var source = new CloneTestStructWithClonableClassField { TestClass = testClass }; var dest = new CloneTestStructWithClonableClassField {TestClass = new CloneTestClass()}; var clone = source.ShallowCloneTo(dest); Assert.IsTrue(ReferenceEquals(testClass, clone.TestClass)); } [Test] public void CloneToWillNotWorkWithNullReferences() { Assert.Throws<ArgumentNullException>(() => Cloneable<ParentClass>.CloneTo(new ParentClass(), null)); Assert.Throws<ArgumentNullException>(() => Cloneable<ParentClass>.CloneTo(null, new ParentClass())); } [Test] public void ShallowCloneToWillNotWorkWithNullReferences() { Assert.Throws<ArgumentNullException>(() => Cloneable<ParentClass>.ShallowCloneTo(new ParentClass(), null)); Assert.Throws<ArgumentNullException>(() => Cloneable<ParentClass>.ShallowCloneTo(null, new ParentClass())); } [Test] public void CloneToWithSameDestinationAsSourceWillNotWork() { var testClass = new ParentClass(); Assert.Throws<InvalidOperationException>(() => Cloneable<ParentClass>.CloneTo(testClass, testClass)); } [Test] public void ShallowCloneToWithSameDestinationAsSourceWillNotWork() { var testClass = new ParentClass(); Assert.Throws<InvalidOperationException>(() => Cloneable<ParentClass>.ShallowCloneTo(testClass, testClass)); } [Test] public void CloneToClass() { var source = new CloneTestClass { FirstName = "John", LastName = "Doe" }; var destination = new CloneTestClass(); Cloneable<CloneTestClass>.CloneTo(source, destination); Assert.AreEqual(source.FirstName, destination.FirstName); Assert.AreEqual(source.LastName, destination.LastName); } [Test] public void ShallowCloneToClass() { var source = new CloneTestClass { FirstName = "John", LastName = "Doe" }; var destination = new CloneTestClass(); Cloneable<CloneTestClass>.ShallowCloneTo(source, destination); Assert.AreEqual(source.FirstName, destination.FirstName); Assert.AreEqual(source.LastName, destination.LastName); } [Test] public void CloneToObjectHierarchy() { var source = new ParentClass(); var sourceChild = new ChildClass { Name = "John Doe" }; source.Child = sourceChild; var destination = new ParentClass(); var destinationChild = new ChildClass(); destination.Child = destinationChild; Cloneable<ParentClass>.CloneTo(source, destination); Assert.IsTrue(object.ReferenceEquals(destinationChild, destination.Child)); Assert.AreEqual(sourceChild.Name, destinationChild.Name); } [Test] public void CloneToObjectHierarchyWithNullDestinationChild() { var source = new ParentClass(); var sourceChild = new ChildClass { Name = "John Doe" }; source.Child = sourceChild; var destination = new ParentClass(); Cloneable<ParentClass>.CloneTo(source, destination); Assert.IsFalse(object.ReferenceEquals(sourceChild, destination.Child)); Assert.AreEqual(sourceChild.Name, destination.Child.Name); } [Test] public void CloneToObjectHierarchyWithNullSourceChild() { var source = new ParentClass(); var destination = new ParentClass {Child = new ChildClass {Name = "John Doe"}}; Cloneable<ParentClass>.CloneTo(source, destination); Assert.IsNull(destination.Child); } [Test] public void ShallowCloneToObjectHierarchy() { var source = new ParentClass(); var sourceChild = new ChildClass { Name = "John Doe" }; source.Child = sourceChild; var destination = new ParentClass(); var destinationChild = new ChildClass(); destination.Child = destinationChild; Cloneable<ParentClass>.ShallowCloneTo(source, destination); Assert.IsTrue(object.ReferenceEquals(sourceChild, destination.Child)); } [Test] public void ShallowCloneToObjectHierarchyWithNullDestinationChild() { var source = new ParentClass(); var sourceChild = new ChildClass { Name = "John Doe" }; source.Child = sourceChild; var destination = new ParentClass(); Cloneable<ParentClass>.ShallowCloneTo(source, destination); Assert.IsTrue(object.ReferenceEquals(sourceChild, destination.Child)); Assert.AreEqual(sourceChild.Name, destination.Child.Name); } [Test] public void ShallowCloneToObjectHierarchyWithNullSourceChild() { var source = new ParentClass(); var destination = new ParentClass {Child = new ChildClass {Name = "John Doe"}}; Cloneable<ParentClass>.ShallowCloneTo(source, destination); Assert.IsNull(destination.Child); } [Test] public void CloneClassWithReferenceToTypeThatHasCloneReferenceOnlyAttribute() { var ro = new CloneOnlyByReferenceClass(); var source = new ClassWithReferenceToTypeThatHasCloneReferenceOnlyAttribute {Reference = ro}; var clone = source.Clone(); Assert.IsTrue(ReferenceEquals(ro, clone.Reference)); } [Test] public void CloneClassWithClassReferenceViaInterface() { var wic = new WithInterfaceClass {Name = "John Doe"}; var source = new WithInterfaceReferenceClass {Reference = wic}; var clone = source.Clone(); Assert.IsFalse(ReferenceEquals(clone.Reference, wic)); Assert.IsAssignableFrom(typeof (WithInterfaceClass), clone.Reference); Assert.AreEqual("John Doe", ((WithInterfaceClass)clone.Reference).Name); } [Test] public void CloneClassWithCollectionReferenceViaInterface() { var source = new ClassWithCollectionViaInterface<string>(); var clone = source.Clone(); Assert.IsNull(clone.Collection); source.Collection = new string[] {"Hello", "World!"}; clone = source.Clone(); Assert.AreEqual(clone.Collection.GetType(), typeof(string[])); Assert.IsTrue(clone.Collection.SequenceEqual(new []{"Hello", "World!"})); source.Collection = new Collection<string> { "Hello", "World!" }; clone = source.Clone(); Assert.AreEqual(clone.Collection.GetType(), typeof(Collection<string>)); Assert.IsTrue(clone.Collection.SequenceEqual(new[] { "Hello", "World!" })); source.Collection = new List<string> { "Hello", "World!" }; clone = source.Clone(); Assert.AreEqual(clone.Collection.GetType(), typeof(List<string>)); Assert.IsTrue(clone.Collection.SequenceEqual(new[] { "Hello", "World!" })); } [Test] public void CloneDerivedClassThroughBaseClassReference() { var source = new ClassWithReferenceToBaseClass {Reference = new BaseClass {BaseClassName = "Foo"}}; var clone = source.Clone(); Assert.AreEqual("Foo", clone.Reference.BaseClassName); source.Reference = new DerivedClass {BaseClassName = "Bar", DerivedClassName = "Baz"}; clone = source.Clone(); var derivedClone = clone.Reference as DerivedClass; Assert.IsNotNull(derivedClone); Assert.AreEqual("Bar", derivedClone.BaseClassName); Assert.AreEqual("Baz", derivedClone.DerivedClassName); } } }
using System; using CSCore; using CSCore.Codecs; using CSCore.CoreAudioAPI; using CSCore.SoundOut; using CSCore.Streams; namespace KoPlayer { public class MusicPlayer : IDisposable { private ISoundOut soundOut; private IWaveSource finalSource; private Equalizer equalizer; private VolumeSource volumeSource; private float deviceVolume = 1f; public event EventHandler OpenCompleted; public static MMDevice PlaybackDevice { get; private set; } public static MMDeviceCollection PlaybackDevices { get; private set; } public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped { add { if (soundOut != null) soundOut.Stopped += value; } remove { if (soundOut != null) soundOut.Stopped -= value; } } public Equalizer Equalizer { get { return equalizer; } } public PlaybackState PlaybackState { get { if (soundOut != null) return soundOut.PlaybackState; return PlaybackState.Stopped; } } public TimeSpan Position { get { if (finalSource != null) return finalSource.GetPosition(); return TimeSpan.Zero; } set { if (finalSource != null) finalSource.SetPosition(value); } } public TimeSpan Length { get { if (finalSource != null) return finalSource.GetLength(); return TimeSpan.Zero; } } public int Volume { get { if (soundOut != null) return Math.Min(100, Math.Max((int)(volumeSource.Volume * 1000), 0)); return 1; } set { if (soundOut != null) { volumeSource.Volume = Math.Min(1.0f, Math.Max(value / 1000f, 0f)); } } } public float DeviceVolume { get { return deviceVolume; } set { if (deviceVolume > 0) deviceVolume = Math.Min(1.0f, value); } } public MusicPlayer() { SetDevice(); using (var client = AudioClient.FromMMDevice(PlaybackDevice)) { client.Initialize(AudioClientShareMode.Shared, AudioClientStreamFlags.None, 1000, 0, client.GetMixFormat(), Guid.Empty); } } public void SetDevice(string name = null) { using (var enumerator = new MMDeviceEnumerator()) { PlaybackDevices = enumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active); PlaybackDevice = PlaybackDevice ?? enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia); if (!string.IsNullOrEmpty(name)) { foreach (var device in PlaybackDevices) { if (device.FriendlyName == name) PlaybackDevice = device; } } } } public void Open(string filename) { CleanupPlayback(); var source = CodecFactory.Instance.GetCodec(filename); volumeSource = new VolumeSource(source); equalizer = Equalizer.Create10BandEqualizer(volumeSource); finalSource = equalizer .ToStereo() .ChangeSampleRate(44100) .AppendSource(Equalizer.Create10BandEqualizer, out equalizer) .ToWaveSource(16); if (WasapiOut.IsSupportedOnCurrentPlatform) soundOut = new WasapiOut() { Latency = 100, Device = PlaybackDevice }; else soundOut = new DirectSoundOut(); soundOut.Initialize(finalSource); soundOut.Volume = deviceVolume; if (this.OpenCompleted != null) this.OpenCompleted(this, new EventArgs()); } public void Play() { if (soundOut != null) soundOut.Play(); } public void Pause() { if (soundOut != null) soundOut.Pause(); } public void Stop() { if (soundOut != null) soundOut.Stop(); } private void CleanupPlayback() { if (soundOut != null) { deviceVolume = soundOut.Volume; soundOut.Dispose(); soundOut = null; } if (finalSource != null) { finalSource.Dispose(); finalSource = null; } } public void Dispose() { CleanupPlayback(); if (equalizer != null) equalizer.Dispose(); } } }
using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using Telligent.Evolution.Extensibility.Api.Entities.Version1; using Telligent.Evolution.Extensibility.Api.Version1; using Telligent.Evolution.Extensibility.Content.Version1; using Telligent.Evolution.Extensibility.Version1; using Telligent.Evolution.Extensions.SharePoint.Client.InternalApi; using Telligent.Evolution.Extensions.SharePoint.Client.InternalApi.Entities; using Telligent.Evolution.Extensions.SharePoint.Client.Plugins.Content.List; using Telligent.Evolution.Extensions.SharePoint.Components.Data.Log; using TEApi = Telligent.Evolution.Extensibility.Api.Version1.PublicApi; namespace Telligent.Evolution.Extensions.SharePoint.Client.Api.Version1 { public class SPListItem : ApiEntity, IContent { private static readonly IListService listService = ServiceLocator.Get<IListService>(); private static readonly IListItemUrls listItemUrls = ServiceLocator.Get<IListItemUrls>(); private static readonly IListDataService listDataService = ServiceLocator.Get<IListDataService>(); private readonly ListItem listItem; private readonly List<Field> fields; private string url; private readonly Regex xHtml = new Regex(@"<[^>]*>", RegexOptions.Singleline | RegexOptions.Compiled); public SPListItem() { } public SPListItem(Guid id) { UniqueId = id; } public SPListItem(ListItem listItem, List<Field> fields) { try { this.fields = fields; this.listItem = listItem; var spAuthor = Value("Author") as FieldUserValue; if (spAuthor != null) { Author = new Author(spAuthor.LookupId); } var spEditor = Value("Editor") as FieldUserValue; if (spEditor != null) { Editor = new Author(spEditor.LookupId); } CreatedDate = Value("Created") is DateTime ? ((DateTime)Value("Created")).ToLocalTime() : new DateTime(); Modified = Value("Modified") is DateTime ? ((DateTime)Value("Modified")).ToLocalTime() : new DateTime(); DisplayName = listItem.IsPropertyAvailable("DisplayName") ? listItem.DisplayName : String.Empty; Fields = new Dictionary<string, object>(); Id = listItem.Id; ListId = listItem.ParentList.Id; UniqueId = (listItem["UniqueId"] != null) ? Guid.Parse(listItem["UniqueId"].ToString()) : Guid.Empty; if (Author != null) { AvatarUrl = Author.AvatarUrl; } } catch (Exception ex) { SPLog.UnKnownError(ex, ex.Message); } } [Documentation(Description = "List Item counter Id")] public int Id { get; internal set; } [Documentation(Description = "List Item unique Id (ContentId)")] public Guid UniqueId { get; internal set; } [Documentation(Description = "Creator profile")] public Author Author { get; private set; } [Documentation(Description = "Editor profile")] public Author Editor { get; private set; } public DateTime CreatedDate { get; private set; } public DateTime Modified { get; private set; } public Dictionary<string, object> Fields { get; set; } [Documentation(Description = "Parent List Id (ApplicationId)")] public Guid ListId { get; internal set; } [Documentation(Description = "List item title")] public string DisplayName { get; internal set; } [Documentation(Description = "SharePoint Url for the parent List")] public string ListUrl { get { return listItem != null ? listItem.Context.Url : string.Empty; } } [Documentation(Description = "Returns a collection of fields, which could be modified")] public List<Field> EditableFields() { return (from Field field in fields where !field.ReadOnlyField select field).ToList(); } public string ValueAsHtml(string fieldName) { string value; if (!listItem.FieldValuesAsHtml.FieldValues.TryGetValue(fieldName, out value)) { value = this[fieldName]; } return value; } public string ValueAsText(string fieldName) { return ValueAsText(fieldName, false); } public string ValueAsText(string fieldName, bool stripHtmlTags) { string value; if (!listItem.FieldValuesAsText.FieldValues.TryGetValue(fieldName, out value)) { return HttpUtility.HtmlEncode(FieldValueToText(fieldName, Value(fieldName))); } if (stripHtmlTags && !string.IsNullOrEmpty(value)) { value = xHtml.Replace(value, string.Empty); } return value; } public string ValueForEdit(string fieldName) { string value; if (!listItem.FieldValuesForEdit.FieldValues.TryGetValue(fieldName, out value)) { value = this[fieldName]; } return value; } public object Value(string fieldName) { return listItem != null && listItem.FieldValues.ContainsKey(fieldName) ? listItem.FieldValues[fieldName] : null; } public bool HasValue(string fieldName) { var field = fields.FirstOrDefault(f => f.InternalName == fieldName); if (field == null) return false; var hasDefaultValue = !string.IsNullOrEmpty(field.DefaultValue); if (hasDefaultValue) return true; var fieldValue = Value(fieldName); var hasValue = fieldValue != null; if (hasValue) { // Check that the field value is not empty if (field.FieldTypeKind == FieldType.Choice || field.FieldTypeKind == FieldType.MultiChoice) { var choices = fieldValue as IEnumerable<string>; if (choices != null) { hasValue = choices.Any(); } } else if (field.FieldTypeKind == FieldType.User) { if (fieldValue is FieldUserValue) { var userName = ((FieldUserValue)fieldValue).LookupValue; hasValue = !string.IsNullOrEmpty(userName); } else if (fieldValue is IEnumerable<FieldUserValue>) { hasValue = ((IEnumerable<FieldUserValue>)fieldValue).Any(); } } else if (field.FieldTypeKind == FieldType.Lookup) { if (fieldValue is FieldLookupValue) { hasValue = !string.IsNullOrEmpty(((FieldLookupValue)fieldValue).LookupValue); } else if (fieldValue is FieldLookupValue[]) { hasValue = ((FieldLookupValue[])fieldValue).Any(); } } else if (field.FieldTypeKind == FieldType.URL && fieldValue is FieldUrlValue) { hasValue = !string.IsNullOrEmpty(((FieldUrlValue)fieldValue).Url); } else if (field.FieldTypeKind == FieldType.Attachments && fieldValue is bool) { hasValue = (bool)fieldValue; } else if (field.FieldTypeKind == FieldType.Invalid) { if (fieldValue is IEnumerable<object>) { hasValue = ((IEnumerable<object>)fieldValue).Any(); } else { hasValue = !string.IsNullOrEmpty(fieldValue.ToString()); } } } return hasValue; } public string this[string fieldName] { get { return RenderFieldValue(fieldName, Value(fieldName)); } } #region IContent public IApplication Application { get { return listService.Get(new ListGetQuery(ListId, ListApplicationType.Id)); } } public Guid ContentId { get { return UniqueId; } internal set { UniqueId = value; } } public Guid ContentTypeId { get { return ItemContentType.Id; } } private int? createdByUserId; public int? CreatedByUserId { get { if (Author != null && !string.IsNullOrEmpty(Author.Email) && !createdByUserId.HasValue) { var user = TEApi.Users.Get(new UsersGetOptions { Email = Author.Email }); createdByUserId = user != null ? user.Id : null; } return createdByUserId; } } public string HtmlName(string target) { if (!string.IsNullOrEmpty(DisplayName)) { return HttpUtility.HtmlEncode(DisplayName); } return string.Empty; } public string HtmlDescription(string target) { return string.Empty; } public bool IsEnabled { get { return true; } } public string AvatarUrl { get; private set; } public string Url { get { if (string.IsNullOrEmpty(url)) { var listBase = listDataService.Get(ListId); if (listBase != null) { url = listItemUrls.ViewListItem(listBase, new ItemUrlQuery(Id, ContentId)); } } return url; } internal set { url = value; } } #endregion #region FieldValueToText private string FieldValueToText(string fieldName, object fieldValue) { var field = fields.FirstOrDefault(f => f.InternalName == fieldName); if (field != null) { if (fieldValue == null) { return field.DefaultValue; } else { switch (field.FieldTypeKind) { case FieldType.Number: return NumberToText(field, fieldValue); case FieldType.Currency: return CurrencyToText(field, fieldValue); case FieldType.Choice: return ChoiceToText(field, fieldValue); case FieldType.Note: return NoteToText(field, fieldValue); case FieldType.MultiChoice: return ChoiceToText(field, fieldValue); case FieldType.DateTime: return DateTimeToText(field, fieldValue); case FieldType.User: return UserProfileToText(field, fieldValue); case FieldType.Lookup: return LookupToText(field, fieldValue); case FieldType.URL: return UrlToText(field, fieldValue); case FieldType.Invalid: return InvalidToText(field, fieldValue); default: return fieldValue.ToString(); } } } return string.Empty; } private static string NoteToText(Field field, object fieldValue) { var text = fieldValue != null ? fieldValue.ToString() : field.DefaultValue; if (text != null && text.StartsWith("<p>") && text.EndsWith("</p>")) { text = text.Substring("<p>".Length, text.Length - "<p>".Length - "</p>".Length); } return text; } private static string NumberToText(Field field, object fieldValue) { var showAsPercentage = false; try { var doc = new XmlDocument(); doc.LoadXml(field.SchemaXml); var percentage = doc.FirstChild.Attributes["Percentage"].Value; var p = false; showAsPercentage = !string.IsNullOrEmpty(percentage) && bool.TryParse(percentage, out p) && p; } catch { } return showAsPercentage ? string.Format("{0} %", (int)(100 * (double)(fieldValue != null ? fieldValue : field.DefaultValue))) : fieldValue.ToString(); } private static string CurrencyToText(Field field, object fieldValue) { if (field is FieldCurrency && fieldValue != null) { var currencyField = (FieldCurrency)field; double currencyValue = (double)fieldValue; return currencyValue.ToString("C2", System.Globalization.CultureInfo.GetCultureInfo(currencyField.CurrencyLocaleId)); } return field.DefaultValue; } private static string ChoiceToText(Field field, object fieldValue) { var fieldValueToShow = (fieldValue != null ? fieldValue : field.DefaultValue) ?? string.Empty; var selectedChoices = fieldValueToShow as IEnumerable<string> ?? new string[] { fieldValueToShow.ToString() }; return string.Join(", ", selectedChoices); } private static string DateTimeToText(Field field, object fieldValue) { if (fieldValue is DateTime) { return TEApi.Language.FormatDate((DateTime)fieldValue); } return field.DefaultValue; } private static string UserProfileToText(Field field, object fieldValue) { if (fieldValue is FieldUserValue) { return fieldValue != null ? ((FieldUserValue)fieldValue).LookupValue : field.DefaultValue; } else if (fieldValue is IEnumerable<FieldUserValue>) { return string.Join(", ", ((IEnumerable<FieldUserValue>)fieldValue).Select(f => f.LookupValue).ToList()); } return field.DefaultValue; } private static string LookupToText(Field field, object fieldValue) { if (fieldValue is FieldLookupValue) { return ((FieldLookupValue)fieldValue).LookupValue; } else if (fieldValue is FieldLookupValue[]) { return string.Join(", ", ((FieldLookupValue[])fieldValue).Select(f => f.LookupValue).ToList()); } return field.DefaultValue; } private static string UrlToText(Field field, object fieldValue) { if (fieldValue is FieldUrlValue) { return ((FieldUrlValue)fieldValue).Description; } return field.DefaultValue; } private static string InvalidToText(Field field, object fieldValue) { if (string.Equals(field.TypeAsString, "TaxonomyFieldTypeMulti", StringComparison.InvariantCultureIgnoreCase)) { var terms = new List<string>(); if (fieldValue is IEnumerable<object>) { terms.AddRange(((IEnumerable<object>)fieldValue).Select(v => v.ToString())); if (terms.Count == 0 && !string.IsNullOrEmpty(field.DefaultValue)) { terms.AddRange(field.DefaultValue.Split(';')); } } return string.Join(", ", terms.Where(term => term.Contains('|')).Select(term => term.Split('|')[0].TrimStart('#'))); } else if (string.Equals(field.TypeAsString, "TaxonomyFieldType", StringComparison.InvariantCultureIgnoreCase)) { return fieldValue == null && !string.IsNullOrEmpty(field.DefaultValue) ? field.DefaultValue.Split('|')[0].TrimStart('#') : fieldValue.ToString().Split('|')[0].TrimStart('#'); } return field.DefaultValue; } #endregion #region Rendering private string RenderFieldValue(string fieldName, object fieldValue) { var field = fields.FirstOrDefault(f => f.InternalName == fieldName); if (field != null) { var html = new StringBuilder(); html.Append("<div class=\"field-type-kind ").Append(Enum.GetName(field.FieldTypeKind.GetType(), field.FieldTypeKind).ToLowerInvariant()).Append("\" >"); switch (field.FieldTypeKind) { case FieldType.Number: RenderNumber(html, field, fieldValue); break; case FieldType.Currency: RenderCurrency(html, field, fieldValue); break; case FieldType.Choice: RenderChoice(html, field, fieldValue); break; case FieldType.MultiChoice: RenderChoice(html, field, fieldValue); break; case FieldType.Note: RenderNote(html, field, fieldValue); break; case FieldType.DateTime: RenderDateTime(html, field, fieldValue); break; case FieldType.User: RenderUserProfile(ListId, html, field, fieldValue); break; case FieldType.Lookup: RenderLookup(html, field, fieldValue); break; case FieldType.URL: RenderUrl(html, field, fieldValue); break; case FieldType.Attachments: RenderAttachments(html, fieldName, fieldValue); break; case FieldType.Invalid: RenderInvalid(html, field, fieldValue); break; default: RenderText(html, field, fieldValue); break; } html.Append("</div>"); return html.ToString(); } return string.Empty; } private static void RenderText(StringBuilder html, Field field, object fieldValue) { html.Append(HttpUtility.HtmlEncode(fieldValue != null ? fieldValue.ToString() : field.DefaultValue)); } private static void RenderNote(StringBuilder html, Field field, object fieldValue) { var text = fieldValue != null ? fieldValue.ToString() : field.DefaultValue; if (text != null && text.StartsWith("<p>") && text.EndsWith("</p>")) { text = text.Substring("<p>".Length, text.Length - "<p>".Length - "</p>".Length); } html.Append("<note>").Append(HttpUtility.HtmlEncode(text)).Append("</note>"); } private static void RenderNumber(StringBuilder html, Field field, object fieldValue) { var showAsPercentage = false; try { var fieldNumber = (FieldNumber)field; var doc = new XmlDocument(); doc.LoadXml(field.SchemaXml); var percentage = doc.FirstChild.Attributes["Percentage"].Value; var p = false; showAsPercentage = !string.IsNullOrEmpty(percentage) && bool.TryParse(percentage, out p) && p; } catch { } double numberValue = 0; double numberDefaultValue; if (fieldValue != null) { numberValue = (double)fieldValue; } else if (field.DefaultValue != null && double.TryParse(field.DefaultValue, out numberDefaultValue)) { numberValue = numberDefaultValue; } if (showAsPercentage) { html.AppendFormat("{0} %", (int)(100 * numberValue)); } else { html.Append(numberValue); } } private static void RenderCurrency(StringBuilder html, Field field, object fieldValue) { if (field is FieldCurrency) { var currencyField = (FieldCurrency)field; double currencyValue = 0; double currencyDefaultValue; if (fieldValue != null) { currencyValue = (double)fieldValue; } else if (field.DefaultValue != null && double.TryParse(field.DefaultValue, out currencyDefaultValue)) { currencyValue = currencyDefaultValue; } html.Append(currencyValue.ToString("C2", System.Globalization.CultureInfo.GetCultureInfo(currencyField.CurrencyLocaleId))); } } private static void RenderChoice(StringBuilder html, Field field, object fieldValue) { var fieldValueToShow = (fieldValue != null ? fieldValue : field.DefaultValue) ?? string.Empty; var selectedChoices = fieldValueToShow as IEnumerable<string> ?? new string[] { fieldValueToShow.ToString() }; if (field is FieldChoice) { var fieldChoice = (FieldChoice)field; RenderChoice(html, Enum.GetName(fieldChoice.EditFormat.GetType(), fieldChoice.EditFormat), fieldChoice.Choices, selectedChoices); } else if (field is FieldMultiChoice) { var fieldChoice = (FieldMultiChoice)field; RenderChoice(html, "checkbox", fieldChoice.Choices, selectedChoices); } } private static void RenderChoice(StringBuilder html, string fieldChoiceType, IEnumerable<string> availableChoices, IEnumerable<string> selectedChoices) { html.Append("<ul class=\"choice-list " + fieldChoiceType.ToLowerInvariant() + "\" >"); foreach (var choice in availableChoices) { html.Append("<li class=\"choice-item ").Append(selectedChoices.Contains(choice) ? "selected" : string.Empty).Append("\" >"); html.Append(HttpUtility.HtmlEncode(choice)); html.Append("</li>"); } html.Append("</ul>"); } private static void RenderDateTime(StringBuilder html, Field field, object fieldValue) { if (fieldValue is DateTime) { html.Append(TEApi.Language.FormatDate((DateTime)fieldValue)); } else { html.Append(field.DefaultValue); } } private static void RenderUserProfile(Guid listId, StringBuilder html, Field field, object fieldValue) { if (fieldValue is FieldUserValue) { html.Append("<div class=\"").Append(field.TypeAsString.ToLowerInvariant()).Append("\" >"); BuildUserProfileMarkup(listId, html, (FieldUserValue)fieldValue); html.Append("</div>"); } else if (fieldValue is IEnumerable<FieldUserValue>) { html.Append("<ul class=\"user-profile-list ").Append(field.TypeAsString.ToLowerInvariant()).Append("\" >"); foreach (FieldUserValue userProfileFieldValue in (IEnumerable<FieldUserValue>)fieldValue) { html.Append("<li class=\"user-profile-item\" >"); BuildUserProfileMarkup(listId, html, userProfileFieldValue); html.Append("</li>"); } html.Append("</ul>"); } } private static void BuildUserProfileMarkup(Guid listId, StringBuilder html, FieldUserValue userProfileField) { html.Append("<span class=\"user-name\">"); var userProfileId = userProfileField.LookupId; var userProfile = PublicApi.UserProfiles.Get(listId, userProfileId); if (!string.IsNullOrEmpty(userProfile.Email)) { var evolutionUser = TEApi.Users.Get(new UsersGetOptions { Email = userProfile.Email }); if (evolutionUser != null) { html.AppendFormat("<a href=\"{0}\" class=\"user-icon internal-link view-user-profile\">{1}</a>", HttpUtility.HtmlAttributeEncode(evolutionUser.ProfileUrl), HttpUtility.HtmlEncode(evolutionUser.DisplayName)); } else { html.AppendFormat("<span class=\"user-icon\" title=\"{0}\">{1}</span>", HttpUtility.HtmlAttributeEncode(userProfileField.LookupValue), HttpUtility.HtmlEncode(userProfileField.LookupValue)); } } else { html.Append(HttpUtility.HtmlEncode(userProfileField.LookupValue)); } html.Append("</span>"); } private static void RenderLookup(StringBuilder html, Field field, object fieldValue) { if (fieldValue is FieldLookupValue) { html.Append(((FieldLookupValue)fieldValue).LookupValue); } else if (fieldValue is FieldLookupValue[]) { html.Append("<ul class=\"field-lookup-list\" >"); foreach (var fieldLookupValue in (FieldLookupValue[])fieldValue) { html.Append("<li class=\"field-lookup-item\" >").Append(HttpUtility.HtmlEncode(fieldLookupValue.LookupValue)).Append("</li>"); } html.Append("</ul>"); } else { html.Append(field.DefaultValue); } } private static void RenderUrl(StringBuilder html, Field field, object fieldValue) { if (fieldValue is FieldUrlValue) { var urlValue = (FieldUrlValue)fieldValue; html.Append("<a href=\"").Append(HttpUtility.JavaScriptStringEncode(urlValue.Url)).Append("\" target=\"blank\">").Append(HttpUtility.HtmlEncode(urlValue.Description)).Append("</a>"); } else { html.Append(field.DefaultValue); } } private void RenderAttachments(StringBuilder html, string fieldName, object fieldValue) { if (fieldValue is bool && (bool)fieldValue) { html.Append("<ul class=\"attachment-list\" >"); foreach (var attachment in PublicApi.Attachments.List(ListId, new AttachmentsGetOptions(ContentId, fieldName))) { html.Append("<li class=\"attachment-item\" >"); html.Append("<a class=\"attachment-link\" href=\"").Append(HttpUtility.JavaScriptStringEncode(attachment.Uri.ToString())).Append("\" >"); html.Append(HttpUtility.HtmlEncode(attachment.Name)); html.Append("</a>"); html.Append("</li>"); } html.Append("</ul>"); } else { html.Append("<div class=\"no-records\"></div>"); } } private static void RenderInvalid(StringBuilder html, Field field, object fieldValue) { if (string.Equals(field.TypeAsString, "TaxonomyFieldTypeMulti", StringComparison.InvariantCultureIgnoreCase)) { var terms = new List<string>(); if (fieldValue is IEnumerable<object>) { terms.AddRange(((IEnumerable<object>)fieldValue).Select(ParseTermLabel)); if (terms.Count == 0 && !string.IsNullOrEmpty(field.DefaultValue)) { terms.AddRange(field.DefaultValue.Split(';')); } } RenderTaxonomyItems(html, field.TypeAsString, terms); } else if (string.Equals(field.TypeAsString, "TaxonomyFieldType", StringComparison.InvariantCultureIgnoreCase)) { if (fieldValue == null) { if (!string.IsNullOrEmpty(field.DefaultValue)) { RenderTaxonomyItems(html, field.TypeAsString, new[] { field.DefaultValue }); } } else { RenderTaxonomyItems(html, field.TypeAsString, new[] { ParseTermLabel(fieldValue) }); } } else { html.Append(fieldValue); } } private static string ParseTermLabel(object term) { if (term is TaxonomyFieldValue) { var taxonomyTerm = (TaxonomyFieldValue)term; return taxonomyTerm.Label; } else { Guid id; var termNameIdPair = term.ToString().Split('|'); if (termNameIdPair.Length == 2 && !string.IsNullOrEmpty(termNameIdPair[0]) && Guid.TryParse(termNameIdPair[1], out id)) return termNameIdPair[0]; return null; } } private static void RenderTaxonomyItems(StringBuilder html, string className, IEnumerable<string> termLabels) { html.Append("<ul class=\"taxonomy-term-list ").Append(className.ToLowerInvariant()).Append("\" >"); foreach (var label in termLabels) { html.Append("<li class=\"taxonomy-term-item\" ").Append("\" >").Append(HttpUtility.HtmlEncode(label)).Append("</li>"); } html.Append("</ul>"); } private static void RenderTaxonomyItems(StringBuilder html, string className, IEnumerable<Microsoft.SharePoint.Client.Taxonomy.TaxonomyFieldValue> terms) { html.Append("<ul class=\"taxonomy-term-list ").Append(className.ToLowerInvariant()).Append("\" >"); foreach (var term in terms) { html.Append("<li class=\"taxonomy-term-item\" ").Append("data-id=\"").Append(term.TermGuid).Append("\" >").Append(HttpUtility.HtmlEncode(term.Label)).Append("</li>"); } html.Append("</ul>"); } #endregion } }
using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; /// <summary> /// Plays tactile effects on a tracked VR controller. /// </summary> public static class OVRHaptics { public readonly static OVRHapticsChannel[] Channels; public readonly static OVRHapticsChannel LeftChannel; public readonly static OVRHapticsChannel RightChannel; private readonly static OVRHapticsOutput[] m_outputs; static OVRHaptics() { Config.Load(); m_outputs = new OVRHapticsOutput[] { new OVRHapticsOutput((uint)OVRPlugin.Controller.LTouch), new OVRHapticsOutput((uint)OVRPlugin.Controller.RTouch), }; Channels = new OVRHapticsChannel[] { LeftChannel = new OVRHapticsChannel(0), RightChannel = new OVRHapticsChannel(1), }; } /// <summary> /// Determines the target format for haptics data on a specific device. /// </summary> public static class Config { public static int SampleRateHz { get; private set; } public static int SampleSizeInBytes { get; private set; } public static int MinimumSafeSamplesQueued { get; private set; } public static int MinimumBufferSamplesCount { get; private set; } public static int OptimalBufferSamplesCount { get; private set; } public static int MaximumBufferSamplesCount { get; private set; } static Config() { Load(); } public static void Load() { OVRPlugin.HapticsDesc desc = OVRPlugin.GetControllerHapticsDesc((uint)OVRPlugin.Controller.RTouch); SampleRateHz = desc.SampleRateHz; SampleSizeInBytes = desc.SampleSizeInBytes; MinimumSafeSamplesQueued = desc.MinimumSafeSamplesQueued; MinimumBufferSamplesCount = desc.MinimumBufferSamplesCount; OptimalBufferSamplesCount = desc.OptimalBufferSamplesCount; MaximumBufferSamplesCount = desc.MaximumBufferSamplesCount; } } /// <summary> /// A track of haptics data that can be mixed or sequenced with another track. /// </summary> public class OVRHapticsChannel { private OVRHapticsOutput m_output; /// <summary> /// Constructs a channel targeting the specified output. /// </summary> public OVRHapticsChannel(uint outputIndex) { m_output = m_outputs[outputIndex]; } /// <summary> /// Cancels any currently-playing clips and immediatly plays the specified clip instead. /// </summary> public void Preempt(OVRHapticsClip clip) { m_output.Preempt(clip); } /// <summary> /// Enqueues the specified clip to play after any currently-playing clips finish. /// </summary> public void Queue(OVRHapticsClip clip) { m_output.Queue(clip); } /// <summary> /// Adds the specified clip to play simultaneously to the currently-playing clip(s). /// </summary> public void Mix(OVRHapticsClip clip) { m_output.Mix(clip); } /// <summary> /// Cancels any currently-playing clips. /// </summary> public void Clear() { m_output.Clear(); } } private class OVRHapticsOutput { private class ClipPlaybackTracker { public int ReadCount { get; set; } public OVRHapticsClip Clip { get; set; } public ClipPlaybackTracker(OVRHapticsClip clip) { Clip = clip; } } private bool m_lowLatencyMode = true; private bool m_paddingEnabled = true; private int m_prevSamplesQueued = 0; private float m_prevSamplesQueuedTime = 0; private int m_numPredictionHits = 0; private int m_numPredictionMisses = 0; private int m_numUnderruns = 0; private List<ClipPlaybackTracker> m_pendingClips = new List<ClipPlaybackTracker>(); private uint m_controller = 0; private OVRNativeBuffer m_nativeBuffer = new OVRNativeBuffer(OVRHaptics.Config.MaximumBufferSamplesCount * OVRHaptics.Config.SampleSizeInBytes); private OVRHapticsClip m_paddingClip = new OVRHapticsClip(); public OVRHapticsOutput(uint controller) { #if UNITY_ANDROID m_paddingEnabled = false; #endif m_controller = controller; } /// <summary> /// The system calls this each frame to update haptics playback. /// </summary> public void Process() { var hapticsState = OVRPlugin.GetControllerHapticsState(m_controller); float elapsedTime = Time.realtimeSinceStartup - m_prevSamplesQueuedTime; if (m_prevSamplesQueued > 0) { int expectedSamples = m_prevSamplesQueued - (int)(elapsedTime * OVRHaptics.Config.SampleRateHz + 0.5f); if (expectedSamples < 0) expectedSamples = 0; if ((hapticsState.SamplesQueued - expectedSamples) == 0) m_numPredictionHits++; else m_numPredictionMisses++; //Debug.Log(hapticsState.SamplesAvailable + "a " + hapticsState.SamplesQueued + "q " + expectedSamples + "e " //+ "Prediction Accuracy: " + m_numPredictionHits / (float)(m_numPredictionMisses + m_numPredictionHits)); if ((expectedSamples > 0) && (hapticsState.SamplesQueued == 0)) { m_numUnderruns++; //Debug.LogError("Samples Underrun (" + m_controller + " #" + m_numUnderruns + ") -" // + " Expected: " + expectedSamples // + " Actual: " + hapticsState.SamplesQueued); } m_prevSamplesQueued = hapticsState.SamplesQueued; m_prevSamplesQueuedTime = Time.realtimeSinceStartup; } int desiredSamplesCount = OVRHaptics.Config.OptimalBufferSamplesCount; if (m_lowLatencyMode) { float sampleRateMs = 1000.0f / (float)OVRHaptics.Config.SampleRateHz; float elapsedMs = elapsedTime * 1000.0f; int samplesNeededPerFrame = (int)Mathf.Ceil(elapsedMs / sampleRateMs); int lowLatencySamplesCount = OVRHaptics.Config.MinimumSafeSamplesQueued + samplesNeededPerFrame; if (lowLatencySamplesCount < desiredSamplesCount) desiredSamplesCount = lowLatencySamplesCount; } if (hapticsState.SamplesQueued > desiredSamplesCount) return; if (desiredSamplesCount > OVRHaptics.Config.MaximumBufferSamplesCount) desiredSamplesCount = OVRHaptics.Config.MaximumBufferSamplesCount; if (desiredSamplesCount > hapticsState.SamplesAvailable) desiredSamplesCount = hapticsState.SamplesAvailable; int acquiredSamplesCount = 0; int clipIndex = 0; while(acquiredSamplesCount < desiredSamplesCount && clipIndex < m_pendingClips.Count) { int numSamplesToCopy = desiredSamplesCount - acquiredSamplesCount; int remainingSamplesInClip = m_pendingClips[clipIndex].Clip.Count - m_pendingClips[clipIndex].ReadCount; if (numSamplesToCopy > remainingSamplesInClip) numSamplesToCopy = remainingSamplesInClip; if (numSamplesToCopy > 0) { int numBytes = numSamplesToCopy * OVRHaptics.Config.SampleSizeInBytes; int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes; int srcOffset = m_pendingClips[clipIndex].ReadCount * OVRHaptics.Config.SampleSizeInBytes; Marshal.Copy(m_pendingClips[clipIndex].Clip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes); m_pendingClips[clipIndex].ReadCount += numSamplesToCopy; acquiredSamplesCount += numSamplesToCopy; } clipIndex++; } for (int i = m_pendingClips.Count - 1; i >= 0 && m_pendingClips.Count > 0; i--) { if (m_pendingClips[i].ReadCount >= m_pendingClips[i].Clip.Count) m_pendingClips.RemoveAt(i); } if (m_paddingEnabled) { int desiredPadding = desiredSamplesCount - (hapticsState.SamplesQueued + acquiredSamplesCount); if (desiredPadding < (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount)) desiredPadding = (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount); if (desiredPadding > hapticsState.SamplesAvailable) desiredPadding = hapticsState.SamplesAvailable; if (desiredPadding > 0) { int numBytes = desiredPadding * OVRHaptics.Config.SampleSizeInBytes; int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes; int srcOffset = 0; Marshal.Copy(m_paddingClip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes); acquiredSamplesCount += desiredPadding; } } if (acquiredSamplesCount > 0) { OVRPlugin.HapticsBuffer hapticsBuffer; hapticsBuffer.Samples = m_nativeBuffer.GetPointer(); hapticsBuffer.SamplesCount = acquiredSamplesCount; OVRPlugin.SetControllerHaptics(m_controller, hapticsBuffer); hapticsState = OVRPlugin.GetControllerHapticsState(m_controller); m_prevSamplesQueued = hapticsState.SamplesQueued; m_prevSamplesQueuedTime = Time.realtimeSinceStartup; } } /// <summary> /// Immediately plays the specified clip without waiting for any currently-playing clip to finish. /// </summary> public void Preempt(OVRHapticsClip clip) { m_pendingClips.Clear(); m_pendingClips.Add(new ClipPlaybackTracker(clip)); } /// <summary> /// Enqueues the specified clip to play after any currently-playing clip finishes. /// </summary> public void Queue(OVRHapticsClip clip) { m_pendingClips.Add(new ClipPlaybackTracker(clip)); } /// <summary> /// Adds the samples from the specified clip to the ones in the currently-playing clip(s). /// </summary> public void Mix(OVRHapticsClip clip) { int numClipsToMix = 0; int numSamplesToMix = 0; int numSamplesRemaining = clip.Count; while (numSamplesRemaining > 0 && numClipsToMix < m_pendingClips.Count) { int numSamplesRemainingInClip = m_pendingClips[numClipsToMix].Clip.Count - m_pendingClips[numClipsToMix].ReadCount; numSamplesRemaining -= numSamplesRemainingInClip; numSamplesToMix += numSamplesRemainingInClip; numClipsToMix++; } if (numSamplesRemaining > 0) { numSamplesToMix += numSamplesRemaining; numSamplesRemaining = 0; } if (numClipsToMix > 0) { OVRHapticsClip mixClip = new OVRHapticsClip(numSamplesToMix); OVRHapticsClip a = clip; int aReadCount = 0; for (int i = 0; i < numClipsToMix; i++) { OVRHapticsClip b = m_pendingClips[i].Clip; for(int bReadCount = m_pendingClips[i].ReadCount; bReadCount < b.Count; bReadCount++) { if (OVRHaptics.Config.SampleSizeInBytes == 1) { byte sample = 0; // TODO support multi-byte samples if ((aReadCount < a.Count) && (bReadCount < b.Count)) { sample = (byte)(Mathf.Clamp(a.Samples[aReadCount] + b.Samples[bReadCount], 0, System.Byte.MaxValue)); // TODO support multi-byte samples aReadCount++; } else if (bReadCount < b.Count) { sample = b.Samples[bReadCount]; // TODO support multi-byte samples } mixClip.WriteSample(sample); // TODO support multi-byte samples } } } while (aReadCount < a.Count) { if (OVRHaptics.Config.SampleSizeInBytes == 1) { mixClip.WriteSample(a.Samples[aReadCount]); // TODO support multi-byte samples } aReadCount++; } m_pendingClips[0] = new ClipPlaybackTracker(mixClip); for (int i = 1; i < numClipsToMix; i++) { m_pendingClips.RemoveAt(1); } } else { m_pendingClips.Add(new ClipPlaybackTracker(clip)); } } public void Clear() { m_pendingClips.Clear(); } } /// <summary> /// The system calls this each frame to update haptics playback. /// </summary> public static void Process() { Config.Load(); for (int i = 0; i < m_outputs.Length; i++) { m_outputs[i].Process(); } } }
// 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.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Net.Http.HPack; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using System.Net.Http; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Internal; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2 { internal partial class Http2Connection : IHttp2StreamLifetimeHandler, IHttpHeadersHandler, IRequestProcessor { public static ReadOnlySpan<byte> ClientPreface => ClientPrefaceBytes; private const PseudoHeaderFields _mandatoryRequestPseudoHeaderFields = PseudoHeaderFields.Method | PseudoHeaderFields.Path | PseudoHeaderFields.Scheme; private const int InitialStreamPoolSize = 5; private const int MaxStreamPoolSize = 100; private const long StreamPoolExpiryTicks = TimeSpan.TicksPerSecond * 5; private readonly HttpConnectionContext _context; private readonly Http2FrameWriter _frameWriter; private readonly Pipe _input; private readonly Task _inputTask; private readonly int _minAllocBufferSize; private readonly HPackDecoder _hpackDecoder; private readonly InputFlowControl _inputFlowControl; private readonly OutputFlowControl _outputFlowControl = new OutputFlowControl(new MultipleAwaitableProvider(), Http2PeerSettings.DefaultInitialWindowSize); private readonly Http2PeerSettings _serverSettings = new Http2PeerSettings(); private readonly Http2PeerSettings _clientSettings = new Http2PeerSettings(); private readonly Http2Frame _incomingFrame = new Http2Frame(); // This is only set to true by tests. private readonly bool _scheduleInline; private Http2Stream? _currentHeadersStream; private RequestHeaderParsingState _requestHeaderParsingState; private PseudoHeaderFields _parsedPseudoHeaderFields; private Http2HeadersFrameFlags _headerFlags; private int _totalParsedHeaderSize; private bool _isMethodConnect; private int _highestOpenedStreamId; private bool _gracefulCloseStarted; private int _clientActiveStreamCount; private int _serverActiveStreamCount; // The following are the only fields that can be modified outside of the ProcessRequestsAsync loop. private readonly ConcurrentQueue<Http2Stream> _completedStreams = new ConcurrentQueue<Http2Stream>(); private readonly StreamCloseAwaitable _streamCompletionAwaitable = new StreamCloseAwaitable(); private int _gracefulCloseInitiator; private int _isClosed; // Internal for testing internal readonly Http2KeepAlive? _keepAlive; internal readonly Dictionary<int, Http2Stream> _streams = new Dictionary<int, Http2Stream>(); internal PooledStreamStack<Http2Stream> StreamPool; public Http2Connection(HttpConnectionContext context) { var httpLimits = context.ServiceContext.ServerOptions.Limits; var http2Limits = httpLimits.Http2; _context = context; // Capture the ExecutionContext before dispatching HTTP/2 middleware. Will be restored by streams when processing request _context.InitialExecutionContext = ExecutionContext.Capture(); _frameWriter = new Http2FrameWriter( context.Transport.Output, context.ConnectionContext, this, _outputFlowControl, context.TimeoutControl, httpLimits.MinResponseDataRate, context.ConnectionId, context.MemoryPool, context.ServiceContext); var inputOptions = new PipeOptions(pool: context.MemoryPool, readerScheduler: context.ServiceContext.Scheduler, writerScheduler: PipeScheduler.Inline, pauseWriterThreshold: 1, resumeWriterThreshold: 1, minimumSegmentSize: context.MemoryPool.GetMinimumSegmentSize(), useSynchronizationContext: false); _input = new Pipe(inputOptions); _minAllocBufferSize = context.MemoryPool.GetMinimumAllocSize(); _hpackDecoder = new HPackDecoder(http2Limits.HeaderTableSize, http2Limits.MaxRequestHeaderFieldSize); var connectionWindow = (uint)http2Limits.InitialConnectionWindowSize; _inputFlowControl = new InputFlowControl(connectionWindow, connectionWindow / 2); if (http2Limits.KeepAlivePingDelay != TimeSpan.MaxValue) { _keepAlive = new Http2KeepAlive( http2Limits.KeepAlivePingDelay, http2Limits.KeepAlivePingTimeout, context.ServiceContext.SystemClock); } _serverSettings.MaxConcurrentStreams = (uint)http2Limits.MaxStreamsPerConnection; _serverSettings.MaxFrameSize = (uint)http2Limits.MaxFrameSize; _serverSettings.HeaderTableSize = (uint)http2Limits.HeaderTableSize; _serverSettings.MaxHeaderListSize = (uint)httpLimits.MaxRequestHeadersTotalSize; _serverSettings.InitialWindowSize = (uint)http2Limits.InitialStreamWindowSize; // Start pool off at a smaller size if the max number of streams is less than the InitialStreamPoolSize StreamPool = new PooledStreamStack<Http2Stream>(Math.Min(InitialStreamPoolSize, http2Limits.MaxStreamsPerConnection)); _scheduleInline = context.ServiceContext.Scheduler == PipeScheduler.Inline; _inputTask = ReadInputAsync(); } public string ConnectionId => _context.ConnectionId; public PipeReader Input => _input.Reader; public KestrelTrace Log => _context.ServiceContext.Log; public IFeatureCollection ConnectionFeatures => _context.ConnectionFeatures; public ISystemClock SystemClock => _context.ServiceContext.SystemClock; public ITimeoutControl TimeoutControl => _context.TimeoutControl; public KestrelServerLimits Limits => _context.ServiceContext.ServerOptions.Limits; internal Http2PeerSettings ServerSettings => _serverSettings; // Max tracked streams is double max concurrent streams. // If a small MaxConcurrentStreams value is configured then still track at least to 100 streams // to support clients that send a burst of streams while the connection is being established. internal uint MaxTrackedStreams => Math.Max(_serverSettings.MaxConcurrentStreams * 2, 100); public void OnInputOrOutputCompleted() { TryClose(); _frameWriter.Abort(new ConnectionAbortedException(CoreStrings.ConnectionAbortedByClient)); } public void Abort(ConnectionAbortedException ex) { if (TryClose()) { _frameWriter.WriteGoAwayAsync(int.MaxValue, Http2ErrorCode.INTERNAL_ERROR).Preserve(); } _frameWriter.Abort(ex); } public void StopProcessingNextRequest() => StopProcessingNextRequest(serverInitiated: true); public void HandleRequestHeadersTimeout() { Log.ConnectionBadRequest(ConnectionId, KestrelBadHttpRequestException.GetException(RequestRejectionReason.RequestHeadersTimeout)); Abort(new ConnectionAbortedException(CoreStrings.BadRequest_RequestHeadersTimeout)); } public void HandleReadDataRateTimeout() { Debug.Assert(Limits.MinRequestBodyDataRate != null); Log.RequestBodyMinimumDataRateNotSatisfied(ConnectionId, null, Limits.MinRequestBodyDataRate.BytesPerSecond); Abort(new ConnectionAbortedException(CoreStrings.BadRequest_RequestBodyTimeout)); } public void StopProcessingNextRequest(bool serverInitiated) { var initiator = serverInitiated ? GracefulCloseInitiator.Server : GracefulCloseInitiator.Client; if (Interlocked.CompareExchange(ref _gracefulCloseInitiator, initiator, GracefulCloseInitiator.None) == GracefulCloseInitiator.None) { Input.CancelPendingRead(); } } public async Task ProcessRequestsAsync<TContext>(IHttpApplication<TContext> application) where TContext : notnull { Exception? error = null; var errorCode = Http2ErrorCode.NO_ERROR; try { ValidateTlsRequirements(); TimeoutControl.InitializeHttp2(_inputFlowControl); TimeoutControl.SetTimeout(Limits.KeepAliveTimeout.Ticks, TimeoutReason.KeepAlive); if (!await TryReadPrefaceAsync()) { return; } if (_isClosed == 0) { await _frameWriter.WriteSettingsAsync(_serverSettings.GetNonProtocolDefaults()); // Inform the client that the connection window is larger than the default. It can't be lowered here, // It can only be lowered by not issuing window updates after data is received. var connectionWindow = _context.ServiceContext.ServerOptions.Limits.Http2.InitialConnectionWindowSize; var diff = connectionWindow - (int)Http2PeerSettings.DefaultInitialWindowSize; if (diff > 0) { await _frameWriter.WriteWindowUpdateAsync(0, diff); } } while (_isClosed == 0) { var result = await Input.ReadAsync(); var buffer = result.Buffer; // Call UpdateCompletedStreams() prior to frame processing in order to remove any streams that have exceeded their drain timeouts. UpdateCompletedStreams(); if (result.IsCanceled) { // Heartbeat will cancel ReadAsync and trigger expiring unused streams from pool. StreamPool.RemoveExpired(SystemClock.UtcNowTicks); } try { bool frameReceived = false; while (Http2FrameReader.TryReadFrame(ref buffer, _incomingFrame, _serverSettings.MaxFrameSize, out var framePayload)) { frameReceived = true; Log.Http2FrameReceived(ConnectionId, _incomingFrame); try { await ProcessFrameAsync(application, framePayload); } catch (Http2StreamErrorException ex) { Log.Http2StreamError(ConnectionId, ex); // The client doesn't know this error is coming, allow draining additional frames for now. AbortStream(_incomingFrame.StreamId, new IOException(ex.Message, ex)); await _frameWriter.WriteRstStreamAsync(ex.StreamId, ex.ErrorCode); // Resume reading frames after aborting this HTTP/2 stream. // This is important because additional frames could be // in the current buffer. We don't want to delay reading // them until the next incoming read/heartbeat. } } if (result.IsCompleted) { return; } if (_keepAlive != null) { // Note that the keep alive uses a complete frame being received to reset state. // Some other keep alive implementations use any bytes being received to reset state. var state = _keepAlive.ProcessKeepAlive(frameReceived); if (state == KeepAliveState.SendPing) { await _frameWriter.WritePingAsync(Http2PingFrameFlags.NONE, Http2KeepAlive.PingPayload); } else if (state == KeepAliveState.Timeout) { // There isn't a good error code to return with the GOAWAY. // NO_ERROR isn't a good choice because it indicates the connection is gracefully shutting down. throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorKeepAliveTimeout, Http2ErrorCode.INTERNAL_ERROR); } } } finally { Input.AdvanceTo(buffer.Start, buffer.End); UpdateConnectionState(); } } } catch (ConnectionResetException ex) { // Don't log ECONNRESET errors when there are no active streams on the connection. Browsers like IE will reset connections regularly. if (_clientActiveStreamCount > 0) { Log.RequestProcessingError(ConnectionId, ex); } error = ex; } catch (IOException ex) { Log.RequestProcessingError(ConnectionId, ex); error = ex; } catch (ConnectionAbortedException ex) { Log.RequestProcessingError(ConnectionId, ex); error = ex; } catch (Http2ConnectionErrorException ex) { Log.Http2ConnectionError(ConnectionId, ex); error = ex; errorCode = ex.ErrorCode; } catch (HPackDecodingException ex) { Debug.Assert(_currentHeadersStream != null); Log.HPackDecodingError(ConnectionId, _currentHeadersStream.StreamId, ex); error = ex; errorCode = Http2ErrorCode.COMPRESSION_ERROR; } catch (Exception ex) { Log.LogWarning(0, ex, CoreStrings.RequestProcessingEndError); error = ex; errorCode = Http2ErrorCode.INTERNAL_ERROR; } finally { var connectionError = error as ConnectionAbortedException ?? new ConnectionAbortedException(CoreStrings.Http2ConnectionFaulted, error!); try { if (TryClose()) { await _frameWriter.WriteGoAwayAsync(_highestOpenedStreamId, errorCode); } // Ensure aborting each stream doesn't result in unnecessary WINDOW_UPDATE frames being sent. _inputFlowControl.StopWindowUpdates(); foreach (var stream in _streams.Values) { stream.Abort(new IOException(CoreStrings.Http2StreamAborted, connectionError)); } // Use the server _serverActiveStreamCount to drain all requests on the server side. // Can't use _clientActiveStreamCount now as we now decrement that count earlier/ // Can't use _streams.Count as we wait for RST/END_STREAM before removing the stream from the dictionary while (_serverActiveStreamCount > 0) { await _streamCompletionAwaitable; UpdateCompletedStreams(); } while (StreamPool.TryPop(out var pooledStream)) { pooledStream.Dispose(); } // This cancels keep-alive and request header timeouts, but not the response drain timeout. TimeoutControl.CancelTimeout(); TimeoutControl.StartDrainTimeout(Limits.MinResponseDataRate, Limits.MaxResponseBufferSize); _frameWriter.Complete(); } catch { _frameWriter.Abort(connectionError); throw; } finally { Input.Complete(); _context.Transport.Input.CancelPendingRead(); await _inputTask; } } } // https://tools.ietf.org/html/rfc7540#section-9.2 // Some of these could not be checked in advance. Fail before using the connection. private void ValidateTlsRequirements() { var tlsFeature = ConnectionFeatures.Get<ITlsHandshakeFeature>(); if (tlsFeature == null) { // Not using TLS at all. return; } if (tlsFeature.Protocol < SslProtocols.Tls12) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorMinTlsVersion(tlsFeature.Protocol), Http2ErrorCode.INADEQUATE_SECURITY); } } private async Task<bool> TryReadPrefaceAsync() { while (_isClosed == 0) { var result = await Input.ReadAsync(); var readableBuffer = result.Buffer; var consumed = readableBuffer.Start; var examined = readableBuffer.End; try { if (!readableBuffer.IsEmpty) { if (ParsePreface(readableBuffer, out consumed, out examined)) { return true; } } if (result.IsCompleted) { return false; } } finally { Input.AdvanceTo(consumed, examined); UpdateConnectionState(); } } return false; } private static bool ParsePreface(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined) { consumed = buffer.Start; examined = buffer.End; if (buffer.Length < ClientPreface.Length) { return false; } var preface = buffer.Slice(0, ClientPreface.Length); var span = preface.ToSpan(); if (!span.SequenceEqual(ClientPreface)) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInvalidPreface, Http2ErrorCode.PROTOCOL_ERROR); } consumed = examined = preface.End; return true; } private Task ProcessFrameAsync<TContext>(IHttpApplication<TContext> application, in ReadOnlySequence<byte> payload) where TContext : notnull { // http://httpwg.org/specs/rfc7540.html#rfc.section.5.1.1 // Streams initiated by a client MUST use odd-numbered stream identifiers; ... // An endpoint that receives an unexpected stream identifier MUST respond with // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. if (_incomingFrame.StreamId != 0 && (_incomingFrame.StreamId & 1) == 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdEven(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } return _incomingFrame.Type switch { Http2FrameType.DATA => ProcessDataFrameAsync(payload), Http2FrameType.HEADERS => ProcessHeadersFrameAsync(application, payload), Http2FrameType.PRIORITY => ProcessPriorityFrameAsync(), Http2FrameType.RST_STREAM => ProcessRstStreamFrameAsync(), Http2FrameType.SETTINGS => ProcessSettingsFrameAsync(payload), Http2FrameType.PUSH_PROMISE => throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorPushPromiseReceived, Http2ErrorCode.PROTOCOL_ERROR), Http2FrameType.PING => ProcessPingFrameAsync(payload), Http2FrameType.GOAWAY => ProcessGoAwayFrameAsync(), Http2FrameType.WINDOW_UPDATE => ProcessWindowUpdateFrameAsync(), Http2FrameType.CONTINUATION => ProcessContinuationFrameAsync(payload), _ => ProcessUnknownFrameAsync(), }; } private Task ProcessDataFrameAsync(in ReadOnlySequence<byte> payload) { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId == 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.DataHasPadding && _incomingFrame.DataPadLength >= _incomingFrame.PayloadLength) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorPaddingTooLong(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } ThrowIfIncomingFrameSentToIdleStream(); if (_streams.TryGetValue(_incomingFrame.StreamId, out var stream)) { if (stream.RstStreamReceived) { // Hard abort, do not allow any more frames on this stream. throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamAborted(_incomingFrame.Type, stream.StreamId), Http2ErrorCode.STREAM_CLOSED); } if (stream.EndStreamReceived) { // http://httpwg.org/specs/rfc7540.html#rfc.section.5.1 // // ...an endpoint that receives any frames after receiving a frame with the // END_STREAM flag set MUST treat that as a connection error (Section 5.4.1) // of type STREAM_CLOSED, unless the frame is permitted as described below. // // (The allowed frame types for this situation are WINDOW_UPDATE, RST_STREAM and PRIORITY) throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamHalfClosedRemote(_incomingFrame.Type, stream.StreamId), Http2ErrorCode.STREAM_CLOSED); } return stream.OnDataAsync(_incomingFrame, payload); } // If we couldn't find the stream, it was either alive previously but closed with // END_STREAM or RST_STREAM, or it was implicitly closed when the client opened // a new stream with a higher ID. Per the spec, we should send RST_STREAM if // the stream was closed with RST_STREAM or implicitly, but the spec also says // in http://httpwg.org/specs/rfc7540.html#rfc.section.5.4.1 that // // An endpoint can end a connection at any time. In particular, an endpoint MAY // choose to treat a stream error as a connection error. // // We choose to do that here so we don't have to keep state to track implicitly closed // streams vs. streams closed with END_STREAM or RST_STREAM. throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamClosed(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.STREAM_CLOSED); } private Task ProcessHeadersFrameAsync<TContext>(IHttpApplication<TContext> application, in ReadOnlySequence<byte> payload) where TContext : notnull { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId == 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.HeadersHasPadding && _incomingFrame.HeadersPadLength >= _incomingFrame.PayloadLength - 1) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorPaddingTooLong(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.HeadersHasPriority && _incomingFrame.HeadersStreamDependency == _incomingFrame.StreamId) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamSelfDependency(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_streams.TryGetValue(_incomingFrame.StreamId, out var stream)) { if (stream.RstStreamReceived) { // Hard abort, do not allow any more frames on this stream. throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamAborted(_incomingFrame.Type, stream.StreamId), Http2ErrorCode.STREAM_CLOSED); } // http://httpwg.org/specs/rfc7540.html#rfc.section.5.1 // // ...an endpoint that receives any frames after receiving a frame with the // END_STREAM flag set MUST treat that as a connection error (Section 5.4.1) // of type STREAM_CLOSED, unless the frame is permitted as described below. // // (The allowed frame types after END_STREAM are WINDOW_UPDATE, RST_STREAM and PRIORITY) if (stream.EndStreamReceived) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamHalfClosedRemote(_incomingFrame.Type, stream.StreamId), Http2ErrorCode.STREAM_CLOSED); } // This is the last chance for the client to send END_STREAM if (!_incomingFrame.HeadersEndStream) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorHeadersWithTrailersNoEndStream, Http2ErrorCode.PROTOCOL_ERROR); } // Since we found an active stream, this HEADERS frame contains trailers _currentHeadersStream = stream; _requestHeaderParsingState = RequestHeaderParsingState.Trailers; var headersPayload = payload.Slice(0, _incomingFrame.HeadersPayloadLength); // Minus padding return DecodeTrailersAsync(_incomingFrame.HeadersEndHeaders, headersPayload); } else if (_incomingFrame.StreamId <= _highestOpenedStreamId) { // http://httpwg.org/specs/rfc7540.html#rfc.section.5.1.1 // // The first use of a new stream identifier implicitly closes all streams in the "idle" // state that might have been initiated by that peer with a lower-valued stream identifier. // // If we couldn't find the stream, it was previously closed (either implicitly or with // END_STREAM or RST_STREAM). throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamClosed(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.STREAM_CLOSED); } else { // Cancel keep-alive timeout and start header timeout if necessary. if (TimeoutControl.TimerReason != TimeoutReason.None) { Debug.Assert(TimeoutControl.TimerReason == TimeoutReason.KeepAlive, "Non keep-alive timeout set at start of stream."); TimeoutControl.CancelTimeout(); } if (!_incomingFrame.HeadersEndHeaders) { TimeoutControl.SetTimeout(Limits.RequestHeadersTimeout.Ticks, TimeoutReason.RequestHeaders); } // Start a new stream _currentHeadersStream = GetStream(application); _headerFlags = _incomingFrame.HeadersFlags; var headersPayload = payload.Slice(0, _incomingFrame.HeadersPayloadLength); // Minus padding return DecodeHeadersAsync(_incomingFrame.HeadersEndHeaders, headersPayload); } } private Http2Stream GetStream<TContext>(IHttpApplication<TContext> application) where TContext : notnull { if (StreamPool.TryPop(out var stream)) { stream.InitializeWithExistingContext(_incomingFrame.StreamId); return stream; } return new Http2Stream<TContext>( application, CreateHttp2StreamContext()); } private Http2StreamContext CreateHttp2StreamContext() { var streamContext = new Http2StreamContext( ConnectionId, protocols: default, _context.AltSvcHeader, _context.ServiceContext, _context.ConnectionFeatures, _context.MemoryPool, _context.LocalEndPoint, _context.RemoteEndPoint, _incomingFrame.StreamId, streamLifetimeHandler: this, _clientSettings, _serverSettings, _frameWriter, _inputFlowControl, _outputFlowControl); streamContext.TimeoutControl = _context.TimeoutControl; streamContext.InitialExecutionContext = _context.InitialExecutionContext; return streamContext; } private Task ProcessPriorityFrameAsync() { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId == 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.PriorityStreamDependency == _incomingFrame.StreamId) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamSelfDependency(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.PayloadLength != 5) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorUnexpectedFrameLength(_incomingFrame.Type, 5), Http2ErrorCode.FRAME_SIZE_ERROR); } return Task.CompletedTask; } private Task ProcessRstStreamFrameAsync() { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId == 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.PayloadLength != 4) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorUnexpectedFrameLength(_incomingFrame.Type, 4), Http2ErrorCode.FRAME_SIZE_ERROR); } ThrowIfIncomingFrameSentToIdleStream(); if (_streams.TryGetValue(_incomingFrame.StreamId, out var stream)) { // Second reset if (stream.RstStreamReceived) { // https://tools.ietf.org/html/rfc7540#section-5.1 // If RST_STREAM has already been received then the stream is in a closed state. // Additional frames (other than PRIORITY) are a stream error. // The server will usually send a RST_STREAM for a stream error, but RST_STREAM // shouldn't be sent in response to RST_STREAM to avoid a loop. // The best course of action here is to do nothing. return Task.CompletedTask; } // No additional inbound header or data frames are allowed for this stream after receiving a reset. stream.AbortRstStreamReceived(); } return Task.CompletedTask; } private Task ProcessSettingsFrameAsync(in ReadOnlySequence<byte> payload) { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId != 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdNotZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.SettingsAck) { if (_incomingFrame.PayloadLength != 0) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorSettingsAckLengthNotZero, Http2ErrorCode.FRAME_SIZE_ERROR); } return Task.CompletedTask; } if (_incomingFrame.PayloadLength % 6 != 0) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorSettingsLengthNotMultipleOfSix, Http2ErrorCode.FRAME_SIZE_ERROR); } try { // int.MaxValue is the largest allowed windows size. var previousInitialWindowSize = (int)_clientSettings.InitialWindowSize; var previousMaxFrameSize = _clientSettings.MaxFrameSize; _clientSettings.Update(Http2FrameReader.ReadSettings(payload)); // Ack before we update the windows, they could send data immediately. var ackTask = _frameWriter.WriteSettingsAckAsync(); if (_clientSettings.MaxFrameSize != previousMaxFrameSize) { // Don't let the client choose an arbitrarily large size, this will be used for response buffers. _frameWriter.UpdateMaxFrameSize(Math.Min(_clientSettings.MaxFrameSize, _serverSettings.MaxFrameSize)); } // This difference can be negative. var windowSizeDifference = (int)_clientSettings.InitialWindowSize - previousInitialWindowSize; if (windowSizeDifference != 0) { foreach (var stream in _streams.Values) { if (!stream.TryUpdateOutputWindow(windowSizeDifference)) { // This means that this caused a stream window to become larger than int.MaxValue. // This can never happen with a well behaved client and MUST be treated as a connection error. // https://httpwg.org/specs/rfc7540.html#rfc.section.6.9.2 throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInitialWindowSizeInvalid, Http2ErrorCode.FLOW_CONTROL_ERROR); } } } // Maximum HPack encoder size is limited by Http2Limits.HeaderTableSize, configured max the server. // // Note that the client HPack decoder doesn't care about the ACK so we don't need to lock sending the // ACK and updating the table size on the server together. // The client will wait until a size agreed upon by it (sent in SETTINGS_HEADER_TABLE_SIZE) and the // server (sent as a dynamic table size update in the next HEADERS frame) is received before applying // the new size. _frameWriter.UpdateMaxHeaderTableSize(Math.Min(_clientSettings.HeaderTableSize, (uint)Limits.Http2.HeaderTableSize)); return ackTask.GetAsTask(); } catch (Http2SettingsParameterOutOfRangeException ex) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorSettingsParameterOutOfRange(ex.Parameter), ex.Parameter == Http2SettingsParameter.SETTINGS_INITIAL_WINDOW_SIZE ? Http2ErrorCode.FLOW_CONTROL_ERROR : Http2ErrorCode.PROTOCOL_ERROR); } } private Task ProcessPingFrameAsync(in ReadOnlySequence<byte> payload) { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId != 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdNotZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.PayloadLength != 8) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorUnexpectedFrameLength(_incomingFrame.Type, 8), Http2ErrorCode.FRAME_SIZE_ERROR); } // Incoming ping resets connection keep alive timeout if (TimeoutControl.TimerReason == TimeoutReason.KeepAlive) { TimeoutControl.ResetTimeout(Limits.KeepAliveTimeout.Ticks, TimeoutReason.KeepAlive); } if (_incomingFrame.PingAck) { // TODO: verify that payload is equal to the outgoing PING frame return Task.CompletedTask; } return _frameWriter.WritePingAsync(Http2PingFrameFlags.ACK, payload).GetAsTask(); } private Task ProcessGoAwayFrameAsync() { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId != 0) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdNotZero(_incomingFrame.Type), Http2ErrorCode.PROTOCOL_ERROR); } StopProcessingNextRequest(serverInitiated: false); return Task.CompletedTask; } private Task ProcessWindowUpdateFrameAsync() { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.PayloadLength != 4) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorUnexpectedFrameLength(_incomingFrame.Type, 4), Http2ErrorCode.FRAME_SIZE_ERROR); } ThrowIfIncomingFrameSentToIdleStream(); if (_incomingFrame.WindowUpdateSizeIncrement == 0) { // http://httpwg.org/specs/rfc7540.html#rfc.section.6.9 // A receiver MUST treat the receipt of a WINDOW_UPDATE // frame with an flow-control window increment of 0 as a // stream error (Section 5.4.2) of type PROTOCOL_ERROR; // errors on the connection flow-control window MUST be // treated as a connection error (Section 5.4.1). // // http://httpwg.org/specs/rfc7540.html#rfc.section.5.4.1 // An endpoint can end a connection at any time. In // particular, an endpoint MAY choose to treat a stream // error as a connection error. // // Since server initiated stream resets are not yet properly // implemented and tested, we treat all zero length window // increments as connection errors for now. throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorWindowUpdateIncrementZero, Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId == 0) { if (!_frameWriter.TryUpdateConnectionWindow(_incomingFrame.WindowUpdateSizeIncrement)) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorWindowUpdateSizeInvalid, Http2ErrorCode.FLOW_CONTROL_ERROR); } } else if (_streams.TryGetValue(_incomingFrame.StreamId, out var stream)) { if (stream.RstStreamReceived) { // Hard abort, do not allow any more frames on this stream. throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamAborted(_incomingFrame.Type, stream.StreamId), Http2ErrorCode.STREAM_CLOSED); } if (!stream.TryUpdateOutputWindow(_incomingFrame.WindowUpdateSizeIncrement)) { throw new Http2StreamErrorException(_incomingFrame.StreamId, CoreStrings.Http2ErrorWindowUpdateSizeInvalid, Http2ErrorCode.FLOW_CONTROL_ERROR); } } else { // The stream was not found in the dictionary which means the stream was probably closed. This can // happen when the client sends a window update for a stream right as the server closes the same stream // Since this is an unavoidable race, we just ignore the window update frame. } return Task.CompletedTask; } private Task ProcessContinuationFrameAsync(in ReadOnlySequence<byte> payload) { if (_currentHeadersStream == null) { throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorContinuationWithNoHeaders, Http2ErrorCode.PROTOCOL_ERROR); } if (_incomingFrame.StreamId != _currentHeadersStream.StreamId) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers) { return DecodeTrailersAsync(_incomingFrame.ContinuationEndHeaders, payload); } else { Debug.Assert(TimeoutControl.TimerReason == TimeoutReason.RequestHeaders, "Received continuation frame without request header timeout being set."); if (_incomingFrame.HeadersEndHeaders) { TimeoutControl.CancelTimeout(); } return DecodeHeadersAsync(_incomingFrame.ContinuationEndHeaders, payload); } } private Task ProcessUnknownFrameAsync() { if (_currentHeadersStream != null) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorHeadersInterleaved(_incomingFrame.Type, _incomingFrame.StreamId, _currentHeadersStream.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } return Task.CompletedTask; } private Task DecodeHeadersAsync(bool endHeaders, in ReadOnlySequence<byte> payload) { Debug.Assert(_currentHeadersStream != null); try { _highestOpenedStreamId = _currentHeadersStream.StreamId; _hpackDecoder.Decode(payload, endHeaders, handler: this); if (endHeaders) { StartStream(); ResetRequestHeaderParsingState(); } } catch (Http2StreamErrorException) { _currentHeadersStream.Dispose(); ResetRequestHeaderParsingState(); throw; } return Task.CompletedTask; } private Task DecodeTrailersAsync(bool endHeaders, in ReadOnlySequence<byte> payload) { Debug.Assert(_currentHeadersStream != null); _hpackDecoder.Decode(payload, endHeaders, handler: this); if (endHeaders) { _currentHeadersStream.OnEndStreamReceived(); ResetRequestHeaderParsingState(); } return Task.CompletedTask; } private void StartStream() { Debug.Assert(_currentHeadersStream != null); // The stream now exists and must be tracked and drained even if Http2StreamErrorException is thrown before dispatching to the application. _streams[_incomingFrame.StreamId] = _currentHeadersStream; IncrementActiveClientStreamCount(); _serverActiveStreamCount++; try { // This must be initialized before we offload the request or else we may start processing request body frames without it. _currentHeadersStream.InputRemaining = _currentHeadersStream.RequestHeaders.ContentLength; // This must wait until we've received all of the headers so we can verify the content-length. // We also must set the proper EndStream state before rejecting the request for any reason. if ((_headerFlags & Http2HeadersFrameFlags.END_STREAM) == Http2HeadersFrameFlags.END_STREAM) { _currentHeadersStream.OnEndStreamReceived(); } if (!_isMethodConnect && (_parsedPseudoHeaderFields & _mandatoryRequestPseudoHeaderFields) != _mandatoryRequestPseudoHeaderFields) { // All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header // fields, unless it is a CONNECT request (Section 8.3). An HTTP request that omits mandatory pseudo-header // fields is malformed (Section 8.1.2.6). throw new Http2StreamErrorException(_currentHeadersStream.StreamId, CoreStrings.HttpErrorMissingMandatoryPseudoHeaderFields, Http2ErrorCode.PROTOCOL_ERROR); } if (_clientActiveStreamCount == _serverSettings.MaxConcurrentStreams) { // Provide feedback in server logs that the client hit the number of maximum concurrent streams, // and that the client is likely waiting for existing streams to be completed before it can continue. Log.Http2MaxConcurrentStreamsReached(_context.ConnectionId); } else if (_clientActiveStreamCount > _serverSettings.MaxConcurrentStreams) { // The protocol default stream limit is infinite so the client can exceed our limit at the start of the connection. // Refused streams can be retried, by which time the client must have received our settings frame with our limit information. throw new Http2StreamErrorException(_currentHeadersStream.StreamId, CoreStrings.Http2ErrorMaxStreams, Http2ErrorCode.REFUSED_STREAM); } // We don't use the _serverActiveRequestCount here as during shutdown, it and the dictionary counts get out of sync. // The streams still exist in the dictionary until the client responds with a RST or END_STREAM. // Also, we care about the dictionary size for too much memory consumption. if (_streams.Count > MaxTrackedStreams) { // Server is getting hit hard with connection resets. // Tell client to calm down. // TODO consider making when to send ENHANCE_YOUR_CALM configurable? throw new Http2StreamErrorException(_currentHeadersStream.StreamId, CoreStrings.Http2TellClientToCalmDown, Http2ErrorCode.ENHANCE_YOUR_CALM); } } catch (Http2StreamErrorException) { MakeSpaceInDrainQueue(); // Because this stream isn't being queued, OnRequestProcessingEnded will not be // automatically called and the stream won't be completed. // Manually complete stream to ensure pipes are completed. // Completing the stream will add it to the completed stream queue. _currentHeadersStream.DecrementActiveClientStreamCount(); _currentHeadersStream.CompleteStream(errored: true); throw; } KestrelEventSource.Log.RequestQueuedStart(_currentHeadersStream, AspNetCore.Http.HttpProtocol.Http2); // _scheduleInline is only true in tests if (!_scheduleInline) { // Must not allow app code to block the connection handling loop. ThreadPool.UnsafeQueueUserWorkItem(_currentHeadersStream, preferLocal: false); } else { _currentHeadersStream.Execute(); } } private void ResetRequestHeaderParsingState() { _currentHeadersStream = null; _requestHeaderParsingState = RequestHeaderParsingState.Ready; _parsedPseudoHeaderFields = PseudoHeaderFields.None; _headerFlags = Http2HeadersFrameFlags.NONE; _isMethodConnect = false; _totalParsedHeaderSize = 0; } private void ThrowIfIncomingFrameSentToIdleStream() { // http://httpwg.org/specs/rfc7540.html#rfc.section.5.1 // 5.1. Stream states // ... // idle: // ... // Receiving any frame other than HEADERS or PRIORITY on a stream in this state MUST be // treated as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. // // If the stream ID in the incoming frame is higher than the highest opened stream ID so // far, then the incoming frame's target stream is in the idle state, which is the implicit // initial state for all streams. if (_incomingFrame.StreamId > _highestOpenedStreamId) { throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamIdle(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.PROTOCOL_ERROR); } } private void AbortStream(int streamId, IOException error) { if (_streams.TryGetValue(streamId, out var stream)) { stream.DecrementActiveClientStreamCount(); stream.Abort(error); } } void IRequestProcessor.Tick(DateTimeOffset now) { Input.CancelPendingRead(); } void IHttp2StreamLifetimeHandler.OnStreamCompleted(Http2Stream stream) { _completedStreams.Enqueue(stream); _streamCompletionAwaitable.Complete(); } private void UpdateCompletedStreams() { Http2Stream? firstRequedStream = null; var now = SystemClock.UtcNowTicks; while (_completedStreams.TryDequeue(out var stream)) { if (stream == firstRequedStream) { // We've checked every stream that was in _completedStreams by the time // _checkCompletedStreams was unset, so exit the loop. _completedStreams.Enqueue(stream); break; } if (stream.DrainExpirationTicks == default) { _serverActiveStreamCount--; stream.DrainExpirationTicks = now + Constants.RequestBodyDrainTimeout.Ticks; } if (stream.EndStreamReceived || stream.RstStreamReceived || stream.DrainExpirationTicks < now) { if (stream == _currentHeadersStream) { // The drain expired out while receiving trailers. The most recent incoming frame is either a header or continuation frame for the timed out stream. throw new Http2ConnectionErrorException(CoreStrings.FormatHttp2ErrorStreamClosed(_incomingFrame.Type, _incomingFrame.StreamId), Http2ErrorCode.STREAM_CLOSED); } RemoveStream(stream); } else { if (firstRequedStream == null) { firstRequedStream = stream; } _completedStreams.Enqueue(stream); } } } private void RemoveStream(Http2Stream stream) { _streams.Remove(stream.StreamId); if (stream.CanReuse && StreamPool.Count < MaxStreamPoolSize) { // Pool and reuse the stream if it finished in a graceful state and there is space in the pool. // This property is used to remove unused streams from the pool stream.DrainExpirationTicks = SystemClock.UtcNowTicks + StreamPoolExpiryTicks; StreamPool.Push(stream); } else { // Stream didn't complete gracefully or pool is full. stream.Dispose(); } } // Compare to UpdateCompletedStreams, but only removes streams if over the max stream drain limit. private void MakeSpaceInDrainQueue() { var maxStreams = MaxTrackedStreams; // If we're tracking too many streams, discard the oldest. while (_streams.Count >= maxStreams && _completedStreams.TryDequeue(out var stream)) { if (stream.DrainExpirationTicks == default) { _serverActiveStreamCount--; } RemoveStream(stream); } } private void UpdateConnectionState() { if (_isClosed != 0) { return; } if (_gracefulCloseInitiator != GracefulCloseInitiator.None && !_gracefulCloseStarted) { _gracefulCloseStarted = true; Log.Http2ConnectionClosing(_context.ConnectionId); if (_gracefulCloseInitiator == GracefulCloseInitiator.Server && _clientActiveStreamCount > 0) { _frameWriter.WriteGoAwayAsync(int.MaxValue, Http2ErrorCode.NO_ERROR).Preserve(); } } if (_clientActiveStreamCount == 0) { if (_gracefulCloseStarted) { if (TryClose()) { _frameWriter.WriteGoAwayAsync(_highestOpenedStreamId, Http2ErrorCode.NO_ERROR).Preserve(); } } else { if (TimeoutControl.TimerReason == TimeoutReason.None) { TimeoutControl.SetTimeout(Limits.KeepAliveTimeout.Ticks, TimeoutReason.KeepAlive); } // If we're awaiting headers, either a new stream will be started, or there will be a connection // error possibly due to a request header timeout, so no need to start a keep-alive timeout. Debug.Assert(TimeoutControl.TimerReason == TimeoutReason.RequestHeaders || TimeoutControl.TimerReason == TimeoutReason.KeepAlive); } } } public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { OnHeaderCore(index: null, indexedValue: false, name, value); } public void OnStaticIndexedHeader(int index) { Debug.Assert(index <= H2StaticTable.Count); ref readonly var entry = ref H2StaticTable.Get(index - 1); OnHeaderCore(index, indexedValue: true, entry.Name, entry.Value); } public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { Debug.Assert(index <= H2StaticTable.Count); OnHeaderCore(index, indexedValue: false, H2StaticTable.Get(index - 1).Name, value); } // We can't throw a Http2StreamErrorException here, it interrupts the header decompression state and may corrupt subsequent header frames on other streams. // For now these either need to be connection errors or BadRequests. If we want to downgrade any of them to stream errors later then we need to // rework the flow so that the remaining headers are drained and the decompression state is maintained. private void OnHeaderCore(int? index, bool indexedValue, ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { Debug.Assert(_currentHeadersStream != null); // https://tools.ietf.org/html/rfc7540#section-6.5.2 // "The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field."; _totalParsedHeaderSize += HeaderField.RfcOverhead + name.Length + value.Length; if (_totalParsedHeaderSize > _context.ServiceContext.ServerOptions.Limits.MaxRequestHeadersTotalSize) { throw new Http2ConnectionErrorException(CoreStrings.BadRequest_HeadersExceedMaxTotalSize, Http2ErrorCode.PROTOCOL_ERROR); } if (index != null) { ValidateStaticHeader(index.Value, value); } else { ValidateHeader(name, value); } try { if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers) { _currentHeadersStream.OnTrailer(name, value); } else { // Throws BadRequest for header count limit breaches. // Throws InvalidOperation for bad encoding. if (index != null) { _currentHeadersStream.OnHeader(index.Value, indexedValue, name, value); } else { _currentHeadersStream.OnHeader(name, value, checkForNewlineChars : true); } } } catch (Microsoft.AspNetCore.Http.BadHttpRequestException bre) { throw new Http2ConnectionErrorException(bre.Message, Http2ErrorCode.PROTOCOL_ERROR); } catch (InvalidOperationException) { throw new Http2ConnectionErrorException(CoreStrings.BadRequest_MalformedRequestInvalidHeaders, Http2ErrorCode.PROTOCOL_ERROR); } } public void OnHeadersComplete(bool endStream) => _currentHeadersStream!.OnHeadersComplete(); private void ValidateHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { // Clients will normally send pseudo headers as an indexed header. // Because pseudo headers can still be sent by name we need to check for them. UpdateHeaderParsingState(value, GetPseudoHeaderField(name)); if (IsConnectionSpecificHeaderField(name, value)) { throw new Http2ConnectionErrorException(CoreStrings.HttpErrorConnectionSpecificHeaderField, Http2ErrorCode.PROTOCOL_ERROR); } // http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2 // A request or response containing uppercase header field names MUST be treated as malformed (Section 8.1.2.6). for (var i = 0; i < name.Length; i++) { if (((uint)name[i] - 65) <= (90 - 65)) { if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers) { throw new Http2ConnectionErrorException(CoreStrings.HttpErrorTrailerNameUppercase, Http2ErrorCode.PROTOCOL_ERROR); } else { throw new Http2ConnectionErrorException(CoreStrings.HttpErrorHeaderNameUppercase, Http2ErrorCode.PROTOCOL_ERROR); } } } } private void ValidateStaticHeader(int index, ReadOnlySpan<byte> value) { var headerField = index switch { 1 => PseudoHeaderFields.Authority, 2 => PseudoHeaderFields.Method, 3 => PseudoHeaderFields.Method, 4 => PseudoHeaderFields.Path, 5 => PseudoHeaderFields.Path, 6 => PseudoHeaderFields.Scheme, 7 => PseudoHeaderFields.Scheme, 8 => PseudoHeaderFields.Status, 9 => PseudoHeaderFields.Status, 10 => PseudoHeaderFields.Status, 11 => PseudoHeaderFields.Status, 12 => PseudoHeaderFields.Status, 13 => PseudoHeaderFields.Status, 14 => PseudoHeaderFields.Status, _ => PseudoHeaderFields.None }; UpdateHeaderParsingState(value, headerField); // http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2 // No need to validate if header name if it is specified using a static index. } private void UpdateHeaderParsingState(ReadOnlySpan<byte> value, PseudoHeaderFields headerField) { // http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.1 /* Intermediaries that process HTTP requests or responses (i.e., any intermediary not acting as a tunnel) MUST NOT forward a malformed request or response. Malformed requests or responses that are detected MUST be treated as a stream error (Section 5.4.2) of type PROTOCOL_ERROR. For malformed requests, a server MAY send an HTTP response prior to closing or resetting the stream. Clients MUST NOT accept a malformed response. Note that these requirements are intended to protect against several types of common attacks against HTTP; they are deliberately strict because being permissive can expose implementations to these vulnerabilities.*/ if (headerField != PseudoHeaderFields.None) { if (_requestHeaderParsingState == RequestHeaderParsingState.Headers) { // All pseudo-header fields MUST appear in the header block before regular header fields. // Any request or response that contains a pseudo-header field that appears in a header // block after a regular header field MUST be treated as malformed (Section 8.1.2.6). throw new Http2ConnectionErrorException(CoreStrings.HttpErrorPseudoHeaderFieldAfterRegularHeaders, Http2ErrorCode.PROTOCOL_ERROR); } if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers) { // Pseudo-header fields MUST NOT appear in trailers. throw new Http2ConnectionErrorException(CoreStrings.HttpErrorTrailersContainPseudoHeaderField, Http2ErrorCode.PROTOCOL_ERROR); } _requestHeaderParsingState = RequestHeaderParsingState.PseudoHeaderFields; if (headerField == PseudoHeaderFields.Unknown) { // Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header // fields as malformed (Section 8.1.2.6). throw new Http2ConnectionErrorException(CoreStrings.HttpErrorUnknownPseudoHeaderField, Http2ErrorCode.PROTOCOL_ERROR); } if (headerField == PseudoHeaderFields.Status) { // Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields // defined for responses MUST NOT appear in requests. throw new Http2ConnectionErrorException(CoreStrings.HttpErrorResponsePseudoHeaderField, Http2ErrorCode.PROTOCOL_ERROR); } if ((_parsedPseudoHeaderFields & headerField) == headerField) { // http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.3 // All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header fields throw new Http2ConnectionErrorException(CoreStrings.HttpErrorDuplicatePseudoHeaderField, Http2ErrorCode.PROTOCOL_ERROR); } if (headerField == PseudoHeaderFields.Method) { _isMethodConnect = value.SequenceEqual(ConnectBytes); } _parsedPseudoHeaderFields |= headerField; } else if (_requestHeaderParsingState != RequestHeaderParsingState.Trailers) { _requestHeaderParsingState = RequestHeaderParsingState.Headers; } } private static PseudoHeaderFields GetPseudoHeaderField(ReadOnlySpan<byte> name) { if (name.IsEmpty || name[0] != (byte)':') { return PseudoHeaderFields.None; } else if (name.SequenceEqual(PathBytes)) { return PseudoHeaderFields.Path; } else if (name.SequenceEqual(MethodBytes)) { return PseudoHeaderFields.Method; } else if (name.SequenceEqual(SchemeBytes)) { return PseudoHeaderFields.Scheme; } else if (name.SequenceEqual(StatusBytes)) { return PseudoHeaderFields.Status; } else if (name.SequenceEqual(AuthorityBytes)) { return PseudoHeaderFields.Authority; } else { return PseudoHeaderFields.Unknown; } } private static bool IsConnectionSpecificHeaderField(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { return name.SequenceEqual(ConnectionBytes) || (name.SequenceEqual(TeBytes) && !value.SequenceEqual(TrailersBytes)); } private bool TryClose() { if (Interlocked.Exchange(ref _isClosed, 1) == 0) { Log.Http2ConnectionClosed(_context.ConnectionId, _highestOpenedStreamId); return true; } return false; } public void IncrementActiveClientStreamCount() { Interlocked.Increment(ref _clientActiveStreamCount); } public void DecrementActiveClientStreamCount() { Interlocked.Decrement(ref _clientActiveStreamCount); } private async Task ReadInputAsync() { Exception? error = null; try { while (true) { var reader = _context.Transport.Input; var writer = _input.Writer; var readResult = await reader.ReadAsync(); if ((readResult.IsCompleted && readResult.Buffer.Length == 0) || readResult.IsCanceled) { // FIN break; } var outputBuffer = writer.GetMemory(_minAllocBufferSize); var copyAmount = (int)Math.Min(outputBuffer.Length, readResult.Buffer.Length); var bufferSlice = readResult.Buffer.Slice(0, copyAmount); bufferSlice.CopyTo(outputBuffer.Span); reader.AdvanceTo(bufferSlice.End); writer.Advance(copyAmount); var result = await writer.FlushAsync(); if (result.IsCompleted || result.IsCanceled) { // flushResult should not be canceled. break; } } } catch (Exception ex) { // Don't rethrow the exception. It should be handled by the Pipeline consumer. error = ex; } finally { await _context.Transport.Input.CompleteAsync(); _input.Writer.Complete(error); } } private enum RequestHeaderParsingState { Ready, PseudoHeaderFields, Headers, Trailers } [Flags] private enum PseudoHeaderFields { None = 0x0, Authority = 0x1, Method = 0x2, Path = 0x4, Scheme = 0x8, Status = 0x10, Unknown = 0x40000000 } private static class GracefulCloseInitiator { public const int None = 0; public const int Server = 1; public const int Client = 2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace System.Diagnostics { /// <summary> /// DiagnosticSourceEventSource serves two purposes /// /// 1) It allows debuggers to inject code via Function evaluation. This is the purpose of the /// BreakPointWithDebuggerFuncEval function in the 'OnEventCommand' method. Basically even in /// release code, debuggers can place a breakpoint in this method and then trigger the /// DiagnosticSourceEventSource via ETW. Thus from outside the process you can get a hook that /// is guaranteed to happen BEFORE any DiangosticSource events (if the process is just starting) /// or as soon as possible afterward if it is on attach. /// /// 2) It provides a 'bridge' that allows DiagnosticSource messages to be forwarded to EventListers /// or ETW. You can do this by enabling the Microsoft-Diagnostics-DiagnosticSource with the /// 'Events' keyword (for diagnostics purposes, you should also turn on the 'Messages' keyword. /// /// This EventSource defines a EventSource argument called 'FilterAndPayloadSpecs' that defines /// what DiagnsoticSources to enable and what parts of the payload to serialize into the key-value /// list that will be forwarded to the EventSource. If it is empty, all serializable parts of /// every DiagnosticSource event will be forwarded (this is NOT recommended for monitoring but /// can be useful for discovery). /// /// The FilterAndPayloadSpecs is one long string with the following structures /// /// * It is a newline separated list of FILTER_AND_PAYLOAD_SPEC /// * a FILTER_AND_PAYLOAD_SPEC can be /// * EVENT_NAME : TRANSFORM_SPECS /// * EMPTY - turns on all sources with implicit payload elements. /// * an EVENTNAME can be /// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME @ EVENT_SOURCE_EVENTNAME - give the name as well as the EventSource event to log it under. /// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME /// * DIAGNOSTIC_SOURCE_NAME - which wildcards every event in the Diagnostic source or /// * EMPTY - which turns on all sources /// * TRANSFORM_SPEC is a semicolon separated list of TRANSFORM_SPEC, which can be /// * - TRANSFORM_SPEC - the '-' indicates that implicit payload elements should be suppressed /// * VARIABLE_NAME = PROPERTY_SPEC - indicates that a payload element 'VARIABLE_NAME' is created from PROPERTY_SPEC /// * PROPERTY_SPEC - This is a shortcut where VARIABLE_NAME is the LAST property name /// * a PROPERTY_SPEC is basically a list of names separated by '.' /// * PROPERTY_NAME - fetches a property from the DiagnosticSource payload object /// * PROPERTY_NAME . PROPERTY NAME - fetches a sub-property of the object. /// /// Example1: /// /// "BridgeTestSource1/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" + /// "BridgeTestSource2/TestEvent2:-cls.Url" /// /// This indicates that two events should be turned on, The 'TestEvent1' event in BridgeTestSource1 and the /// 'TestEvent2' in BridgeTestSource2. In the first case, because the transform did not begin with a - /// any primitive type/string of 'TestEvent1's payload will be serialized into the output. In addition if /// there a property of the payload object called 'cls' which in turn has a property 'Point' which in turn /// has a property 'X' then that data is also put in the output with the name cls_Point_X. Similarly /// if cls.Point.Y exists, then that value will also be put in the output with the name cls_Point_Y. /// /// For the 'BridgeTestSource2/TestEvent2' event, because the - was specified NO implicit fields will be /// generated, but if there is a property call 'cls' which has a property 'Url' then that will be placed in /// the output with the name 'Url' (since that was the last property name used and no Variable= clause was /// specified. /// /// Example: /// /// "BridgeTestSource1\r\n" + /// "BridgeTestSource2" /// /// This will enable all events for the BridgeTestSource1 and BridgeTestSource2 sources. Any string/primitive /// properties of any of the events will be serialized into the output. /// /// Example: /// /// "" /// /// This turns on all DiagnosticSources Any string/primitive properties of any of the events will be serialized /// into the output. This is not likely to be a good idea as it will be very verbose, but is useful to quickly /// discover what is available. /// /// /// * How data is logged in the EventSource /// /// By default all data from Diagnostic sources is logged to the the DiagnosticEventSouce event called 'Event' /// which has three fields /// /// string SourceName, /// string EventName, /// IEnumerable[KeyValuePair[string, string]] Argument /// /// However to support start-stop activity tracking, there are six other events that can be used /// /// Activity1Start /// Activity1Stop /// Activity2Start /// Activity2Stop /// RecursiveActivity1Start /// RecursiveActivity1Stop /// /// By using the SourceName/EventName@EventSourceName syntax, you can force particular DiagnosticSource events to /// be logged with one of these EventSource events. This is useful because the events above have start-stop semantics /// which means that they create activity IDs that are attached to all logging messages between the start and /// the stop (see https://blogs.msdn.microsoft.com/vancem/2015/09/14/exploring-eventsource-activity-correlation-and-causation-features/) /// /// For example the specification /// /// "MyDiagnosticSource/RequestStart@Activity1Start\r\n" + /// "MyDiagnosticSource/RequestStop@Activity1Stop\r\n" + /// "MyDiagnosticSource/SecurityStart@Activity2Start\r\n" + /// "MyDiagnosticSource/SecurityStop@Activity2Stop\r\n" /// /// Defines that RequestStart will be logged with the EventSource Event Activity1Start (and the cooresponding stop) which /// means that all events caused between these two markers will have an activity ID assocatied with this start event. /// Simmilarly SecurityStart is mapped to Activity2Start. /// /// Note you can map many DiangosticSource events to the same EventSource Event (e.g. Activity1Start). As long as the /// activities don't nest, you can reuse the same event name (since the payloads have the DiagnosticSource name which can /// disambiguate). However if they nest you need to use another EventSource event because the rules of EventSource /// activities state that a start of the same event terminates any existing activity of the same name. /// /// As its name suggests RecursiveActivity1Start, is marked as recursive and thus can be used when the activity can nest with /// itself. This should not be a 'top most' activity because it is not 'self healing' (if you miss a stop, then the /// activity NEVER ends). /// /// See the DiagnosticSourceEventSourceBridgeTest.cs for more explicit examples of using this bridge. /// </summary> [EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")] internal class DiagnosticSourceEventSource : EventSource { public static DiagnosticSourceEventSource Logger = new DiagnosticSourceEventSource(); public class Keywords { /// <summary> /// Indicates diagnostics messages from DiagnosticSourceEventSource should be included. /// </summary> public const EventKeywords Messages = (EventKeywords)0x1; /// <summary> /// Indicates that all events from all diagnostic sources should be forwarded to the EventSource using the 'Event' event. /// </summary> public const EventKeywords Events = (EventKeywords)0x2; // Some ETW logic does not support passing arguments to the EventProvider. To get around // this in common cases, we define some keywords that basically stand in for particular common argumnents // That way at least the common cases can be used by everyone (and it also compresses things). // We start these keywords at 0x1000. See below for the values these keywords represent // Because we want all keywords on to still mean 'dump everything by default' we have another keyword // IgnoreShorcutKeywords which must be OFF in order for the shortcuts to work thus the all 1s keyword // still means what you expect. public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)0x0800; public const EventKeywords AspNetCoreHosting = (EventKeywords)0x1000; public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)0x2000; }; // Setting AspNetCoreHosting is like having this in the FilterAndPayloadSpecs string // It turns on basic hostig events. private readonly string AspNetCoreHostingKeywordValue = "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.BeginRequest@Activity1Start:-" + "httpContext.Request.Method;" + "httpContext.Request.Host;" + "httpContext.Request.Path;" + "httpContext.Request.QueryString" + "\n" + "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.EndRequest@Activity1Stop:-"; // Setting EntityFrameworkCoreCommands is like having this in the FilterAndPayloadSpecs string // It turns on basic SQL commands. private readonly string EntityFrameworkCoreCommandsKeywordValue = "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.BeforeExecuteCommand@Activity2Start:-" + "Command.Connection.DataSource;" + "Command.Connection.Database;" + "Command.CommandText" + "\n" + "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.AfterExecuteCommand@Activity2Stop:-"; /// <summary> /// Used to send ad-hoc diagnostics to humans. /// </summary> [Event(1, Keywords = Keywords.Messages)] public void Message(string Message) { WriteEvent(1, Message); } #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Events from DiagnosticSource can be forwarded to EventSource using this event. /// </summary> [Event(2, Keywords = Keywords.Events)] private void Event(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(2, SourceName, EventName, Arguments); } #endif /// <summary> /// This is only used on V4.5 systems that don't have the ability to log KeyValuePairs directly. /// It will eventually go away, but we should always reserve the ID for this. /// </summary> [Event(3, Keywords = Keywords.Events)] private void EventJson(string SourceName, string EventName, string ArgmentsJson) { WriteEvent(3, SourceName, EventName, ArgmentsJson); } #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(4, Keywords = Keywords.Events)] private void Activity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(4, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity /// </summary> [Event(5, Keywords = Keywords.Events)] private void Activity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(5, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(6, Keywords = Keywords.Events)] private void Activity2Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(6, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity that can be recursive. /// </summary> [Event(7, Keywords = Keywords.Events)] private void Activity2Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(7, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(8, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)] private void RecursiveActivity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(8, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity that can be recursive. /// </summary> [Event(9, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)] private void RecursiveActivity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(9, SourceName, EventName, Arguments); } #endif /// <summary> /// Fires when a new DiagnosticSource becomes available. /// </summary> /// <param name="SourceName"></param> [Event(10, Keywords = Keywords.Events)] private void NewDiagnosticListener(string SourceName) { WriteEvent(10, SourceName); } #region private #if NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Converts a keyvalue bag to JSON. Only used on V4.5 EventSources. /// </summary> private static string ToJson(IEnumerable<KeyValuePair<string, string>> keyValues) { StringBuilder sb = new StringBuilder(); sb.AppendLine("{"); bool first = true; foreach (var keyValue in keyValues) { if (!first) sb.Append(',').AppendLine(); first = false; sb.Append('"').Append(keyValue.Key).Append("\":\""); // Write out the value characters, escaping things as needed. foreach(var c in keyValue.Value) { if (Char.IsControl(c)) { if (c == '\n') sb.Append("\\n"); else if (c == '\r') sb.Append("\\r"); else sb.Append("\\u").Append(((int)c).ToString("x").PadLeft(4, '0')); } else { if (c == '"' || c == '\\') sb.Append('\\'); sb.Append(c); } } sb.Append('"'); // Close the string. } sb.AppendLine().AppendLine("}"); return sb.ToString(); } #endif #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// This constructor uses EventSourceSettings which is only available on V4.6 and above /// systems. We use the EventSourceSettings to turn on support for complex types. /// </summary> private DiagnosticSourceEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { } #endif /// <summary> /// Called when the EventSource gets a command from a EventListener or ETW. /// </summary> [NonEvent] protected override void OnEventCommand(EventCommandEventArgs command) { // On every command (which the debugger can force by turning on this EventSource with ETW) // call a function that the debugger can hook to do an arbitrary func evaluation. BreakPointWithDebuggerFuncEval(); lock (this) { if ((command.Command == EventCommand.Update || command.Command == EventCommand.Enable) && IsEnabled(EventLevel.Informational, Keywords.Events)) { string filterAndPayloadSpecs; command.Arguments.TryGetValue("FilterAndPayloadSpecs", out filterAndPayloadSpecs); if (!IsEnabled(EventLevel.Informational, Keywords.IgnoreShortCutKeywords)) { if (IsEnabled(EventLevel.Informational, Keywords.AspNetCoreHosting)) filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, AspNetCoreHostingKeywordValue); if (IsEnabled(EventLevel.Informational, Keywords.EntityFrameworkCoreCommands)) filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, EntityFrameworkCoreCommandsKeywordValue); } FilterAndTransform.CreateFilterAndTransformList(ref _specs, filterAndPayloadSpecs, this); } else if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable) { FilterAndTransform.DestroyFilterAndTransformList(ref _specs); } } } // trivial helper to allow you to join two strings the first of which can be null. private static string NewLineSeparate(string str1, string str2) { Debug.Assert(str2 != null); if (string.IsNullOrEmpty(str1)) return str2; return str1 + "\n" + str2; } #region debugger hooks private volatile bool _false; // A value that is always false but the compiler does not know this. /// <summary> /// A function which is fully interruptible even in release code so we can stop here and /// do function evaluation in the debugger. Thus this is just a place that is useful /// for the debugger to place a breakpoint where it can inject code with function evaluation /// </summary> [NonEvent, MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void BreakPointWithDebuggerFuncEval() { new object(); // This is only here because it helps old desktop runtimes emit a GC safe point at the start of the method while (_false) { _false = false; } } #endregion #region EventSource hooks /// <summary> /// FilterAndTransform represents on transformation specification from a DiagnosticsSource /// to EventSource's 'Event' method. (e.g. MySource/MyEvent:out=prop1.prop2.prop3). /// Its main method is 'Morph' which takes a DiagnosticSource object and morphs it into /// a list of string,string key value pairs. /// /// This method also contains that static 'Create/Destroy FilterAndTransformList, which /// simply parse a series of transformation specifications. /// </summary> internal class FilterAndTransform { /// <summary> /// Parses filterAndPayloadSpecs which is a list of lines each of which has the from /// /// DiagnosticSourceName/EventName:PAYLOAD_SPEC /// /// where PAYLOADSPEC is a semicolon separated list of specifications of the form /// /// OutputName=Prop1.Prop2.PropN /// /// Into linked list of FilterAndTransform that together forward events from the given /// DiagnosticSource's to 'eventSource'. Sets the 'specList' variable to this value /// (destroying anything that was there previously). /// /// By default any serializable properties of the payload object are also included /// in the output payload, however this feature and be tuned off by prefixing the /// PAYLOADSPEC with a '-'. /// </summary> public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList); // Stop anything that was on before. if (filterAndPayloadSpecs == null) filterAndPayloadSpecs = ""; // Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string. int endIdx = filterAndPayloadSpecs.Length; for (;;) { // Skip trailing whitespace. while (0 < endIdx && Char.IsWhiteSpace(filterAndPayloadSpecs[endIdx - 1])) --endIdx; int newlineIdx = filterAndPayloadSpecs.LastIndexOf('\n', endIdx - 1, endIdx); int startIdx = 0; if (0 <= newlineIdx) startIdx = newlineIdx + 1; // starts after the newline, or zero if we don't find one. // Skip leading whitespace while (startIdx < endIdx && Char.IsWhiteSpace(filterAndPayloadSpecs[startIdx])) startIdx++; specList = new FilterAndTransform(filterAndPayloadSpecs, startIdx, endIdx, eventSource, specList); endIdx = newlineIdx; if (endIdx < 0) break; } } /// <summary> /// This destroys (turns off) the FilterAndTransform stopping the forwarding started with CreateFilterAndTransformList /// </summary> /// <param name="specList"></param> public static void DestroyFilterAndTransformList(ref FilterAndTransform specList) { var curSpec = specList; specList = null; // Null out the list while (curSpec != null) // Dispose everything in the list. { curSpec.Dispose(); curSpec = curSpec.Next; } } /// <summary> /// Creates one FilterAndTransform specification from filterAndPayloadSpec starting at 'startIdx' and ending just before 'endIdx'. /// This FilterAndTransform will subscribe to DiagnosticSources specified by the specification and forward them to 'eventSource. /// For convenience, the 'Next' field is set to the 'next' parameter, so you can easily form linked lists. /// </summary> public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next) { #if DEBUG string spec = filterAndPayloadSpec.Substring(startIdx, endIdx - startIdx); #endif Next = next; _eventSource = eventSource; string listenerNameFilter = null; // Means WildCard. string eventNameFilter = null; // Means WildCard. string activityName = null; var startTransformIdx = startIdx; var endEventNameIdx = endIdx; var colonIdx = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx); if (0 <= colonIdx) { endEventNameIdx = colonIdx; startTransformIdx = colonIdx + 1; } // Parse the Source/Event name into listenerNameFilter and eventNameFilter var slashIdx = filterAndPayloadSpec.IndexOf('/', startIdx, endEventNameIdx - startIdx); if (0 <= slashIdx) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, slashIdx - startIdx); var atIdx = filterAndPayloadSpec.IndexOf('@', slashIdx + 1, endEventNameIdx - slashIdx - 1); if (0 <= atIdx) { activityName = filterAndPayloadSpec.Substring(atIdx + 1, endEventNameIdx - atIdx - 1); eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, atIdx - slashIdx - 1); } else { eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, endEventNameIdx - slashIdx - 1); } } else if (startIdx < endEventNameIdx) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, endEventNameIdx - startIdx); } _eventSource.Message("DiagnosticSource: Enabling '" + (listenerNameFilter ?? "*") + "/" + (eventNameFilter ?? "*") + "'"); // If the transform spec begins with a - it means you don't want implicit transforms. if (startTransformIdx < endIdx && filterAndPayloadSpec[startTransformIdx] == '-') { _eventSource.Message("DiagnosticSource: suppressing implicit transforms."); _noImplicitTransforms = true; startTransformIdx++; } // Parse all the explicit transforms, if present if (startTransformIdx < endIdx) { for (;;) { int specStartIdx = startTransformIdx; int semiColonIdx = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - startTransformIdx); if (0 <= semiColonIdx) specStartIdx = semiColonIdx + 1; // Ignore empty specifications. if (specStartIdx < endIdx) { if (_eventSource.IsEnabled(EventLevel.Informational, Keywords.Messages)) _eventSource.Message("DiagnosticSource: Parsing Explicit Transform '" + filterAndPayloadSpec.Substring(specStartIdx, endIdx - specStartIdx) + "'"); _explicitTransforms = new TransformSpec(filterAndPayloadSpec, specStartIdx, endIdx, _explicitTransforms); } if (startTransformIdx == specStartIdx) break; endIdx = semiColonIdx; } } Action<string, string, IEnumerable<KeyValuePair<string, string>>> writeEvent = null; if (activityName != null && activityName.Contains("Activity")) { MethodInfo writeEventMethodInfo = typeof(DiagnosticSourceEventSource).GetTypeInfo().GetDeclaredMethod(activityName); if (writeEventMethodInfo != null) { // This looks up the activityName (which needs to be a name of an event on DiagnosticSourceEventSource // like Activity1Start and returns that method). This allows us to have a number of them and this code // just works. try { writeEvent = (Action<string, string, IEnumerable<KeyValuePair<string, string>>>) writeEventMethodInfo.CreateDelegate(typeof(Action<string, string, IEnumerable<KeyValuePair<string, string>>>), _eventSource); } catch (Exception) { } } if (writeEvent == null) _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName); } if (writeEvent == null) { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT writeEvent = _eventSource.Event; #else writeEvent = delegate (string sourceName, string eventName, IEnumerable<KeyValuePair<string, string>> arguments) { _eventSource.EventJson(sourceName, eventName, ToJson(arguments)); }; #endif } // Set up a subscription that watches for the given Diagnostic Sources and events which will call back // to the EventSource. _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(delegate (DiagnosticListener newListener) { if (listenerNameFilter == null || listenerNameFilter == newListener.Name) { _eventSource.NewDiagnosticListener(newListener.Name); Predicate<string> eventNameFilterPredicate = null; if (eventNameFilter != null) eventNameFilterPredicate = (string eventName) => eventNameFilter == eventName; var subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object>>(delegate (KeyValuePair<string, object> evnt) { // The filter given to the DiagnosticSource may not work if users don't is 'IsEnabled' as expected. // Thus we look for any events that may have snuck through and filter them out before forwarding. if (eventNameFilter != null && eventNameFilter != evnt.Key) return; var outputArgs = this.Morph(evnt.Value); var eventName = evnt.Key; writeEvent(newListener.Name, eventName, outputArgs); }), eventNameFilterPredicate); _liveSubscriptions = new Subscriptions(subscription, _liveSubscriptions); } })); } private void Dispose() { if (_diagnosticsListenersSubscription != null) { _diagnosticsListenersSubscription.Dispose(); _diagnosticsListenersSubscription = null; } if (_liveSubscriptions != null) { var subscr = _liveSubscriptions; _liveSubscriptions = null; while (subscr != null) { subscr.Subscription.Dispose(); subscr = subscr.Next; } } } public List<KeyValuePair<string, string>> Morph(object args) { // Transform the args into a bag of key-value strings. var outputArgs = new List<KeyValuePair<string, string>>(); if (args != null) { if (!_noImplicitTransforms) { Type argType = args.GetType(); if (_expectedArgType != argType) { // Figure out the default properties to send on to EventSource. These are all string or primitive properties. _implicitTransforms = null; TransformSpec newSerializableArgs = null; TypeInfo curTypeInfo = argType.GetTypeInfo(); foreach (var property in curTypeInfo.DeclaredProperties) { var propertyType = property.PropertyType; if (propertyType == typeof(string) || propertyType.GetTypeInfo().IsPrimitive) newSerializableArgs = new TransformSpec(property.Name, 0, property.Name.Length, newSerializableArgs); } _expectedArgType = argType; _implicitTransforms = Reverse(newSerializableArgs); } // Fetch all the fields that are already serializable if (_implicitTransforms != null) { for (var serializableArg = _implicitTransforms; serializableArg != null; serializableArg = serializableArg.Next) outputArgs.Add(serializableArg.Morph(args)); } } if (_explicitTransforms != null) { for (var explicitTransform = _explicitTransforms; explicitTransform != null; explicitTransform = explicitTransform.Next) { var keyValue = explicitTransform.Morph(args); if (keyValue.Value != null) outputArgs.Add(keyValue); } } } return outputArgs; } public FilterAndTransform Next; #region private // Reverses a linked list (of TransformSpecs) in place. private static TransformSpec Reverse(TransformSpec list) { TransformSpec ret = null; while (list != null) { var next = list.Next; list.Next = ret; ret = list; list = next; } return ret; } private IDisposable _diagnosticsListenersSubscription; // This is our subscription that listens for new Diagnostic source to appear. private Subscriptions _liveSubscriptions; // These are the subscriptions that we are currently forwarding to the EventSource. private bool _noImplicitTransforms; // Listener can say they don't want implicit transforms. private Type _expectedArgType; // This is the type where 'implicitTransforms is built for' private TransformSpec _implicitTransforms; // payload to include because the DiagnosticSource's object fields are already serializable private TransformSpec _explicitTransforms; // payload to include because the user explicitly indicated how to fetch the field. private DiagnosticSourceEventSource _eventSource; // Where the data is written to. #endregion } /// <summary> /// Transform spec represents a string that describes how to extract a piece of data from /// the DiagnosticSource payload. An example string is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 /// It has a Next field so they can be chained together in a linked list. /// </summary> internal class TransformSpec { /// <summary> /// parse the strings 'spec' from startIdx to endIdx (points just beyond the last considered char) /// The syntax is ID1=ID2.ID3.ID4 .... Where ID1= is optional. /// </summary> public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSpec next = null) { #if DEBUG string spec = transformSpec.Substring(startIdx, endIdx - startIdx); #endif Debug.Assert(transformSpec != null && startIdx < endIdx); Next = next; // Pick off the Var= int equalsIdx = transformSpec.IndexOf('=', startIdx, endIdx - startIdx); if (0 <= equalsIdx) { _outputName = transformSpec.Substring(startIdx, equalsIdx - startIdx); startIdx = equalsIdx + 1; } // Working from back to front, create a PropertySpec for each .ID in the string. while (startIdx < endIdx) { int dotIdx = transformSpec.LastIndexOf('.', endIdx - 1, endIdx - startIdx); int idIdx = startIdx; if (0 <= dotIdx) idIdx = dotIdx + 1; string propertName = transformSpec.Substring(idIdx, endIdx - idIdx); _fetches = new PropertySpec(propertName, _fetches); // If the user did not explicitly set a name, it is the last one (first to be processed from the end). if (_outputName == null) _outputName = propertName; endIdx = dotIdx; // This works even when LastIndexOf return -1. } } /// <summary> /// Given the DiagnosticSourcePayload 'obj', compute a key-value pair from it. For example /// if the spec is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 and the ultimate value of PROP3 is /// 10 then the return key value pair is KeyValuePair("OUTSTR","10") /// </summary> public KeyValuePair<string, string> Morph(object obj) { for (PropertySpec cur = _fetches; cur != null; cur = cur.Next) { if (obj != null) obj = cur.Fetch(obj); } return new KeyValuePair<string, string>(_outputName, obj?.ToString()); } /// <summary> /// A public field that can be used to form a linked list. /// </summary> public TransformSpec Next; #region private /// <summary> /// A PropertySpec represents information needed to fetch a property from /// and efficiently. Thus it represents a '.PROP' in a TransformSpec /// (and a transformSpec has a list of these). /// </summary> internal class PropertySpec { /// <summary> /// Make a new PropertySpec for a property named 'propertyName'. /// For convenience you can set he 'next' field to form a linked /// list of PropertySpecs. /// </summary> public PropertySpec(string propertyName, PropertySpec next = null) { Next = next; _propertyName = propertyName; } /// <summary> /// Given an object fetch the property that this PropertySpec represents. /// </summary> public object Fetch(object obj) { Type objType = obj.GetType(); if (objType != _expectedType) { var typeInfo = objType.GetTypeInfo(); _fetchForExpectedType = PropertyFetch.FetcherForProperty(typeInfo.GetDeclaredProperty(_propertyName)); _expectedType = objType; } return _fetchForExpectedType.Fetch(obj); } /// <summary> /// A public field that can be used to form a linked list. /// </summary> public PropertySpec Next; #region private /// <summary> /// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how /// to efficiently fetch that property from a .NET object (See Fetch method). /// It hides some slightly complex generic code. /// </summary> class PropertyFetch { /// <summary> /// Create a property fetcher from a .NET Reflection PropertyInfo class that /// represents a property of a particular type. /// </summary> public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo) { if (propertyInfo == null) return new PropertyFetch(); // returns null on any fetch. var typedPropertyFetcher = typeof(TypedFetchProperty<,>); var instantiatedTypedPropertyFetcher = typedPropertyFetcher.GetTypeInfo().MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType); return (PropertyFetch)Activator.CreateInstance(instantiatedTypedPropertyFetcher, propertyInfo); } /// <summary> /// Given an object, fetch the property that this propertyFech represents. /// </summary> public virtual object Fetch(object obj) { return null; } #region private private class TypedFetchProperty<TObject, TProperty> : PropertyFetch { public TypedFetchProperty(PropertyInfo property) { _propertyFetch = (Func<TObject, TProperty>)property.GetMethod.CreateDelegate(typeof(Func<TObject, TProperty>)); } public override object Fetch(object obj) { return _propertyFetch((TObject)obj); } private readonly Func<TObject, TProperty> _propertyFetch; } #endregion } private string _propertyName; private Type _expectedType; private PropertyFetch _fetchForExpectedType; #endregion } private string _outputName; private PropertySpec _fetches; #endregion } /// <summary> /// CallbackObserver is a adapter class that creates an observer (which you can pass /// to IObservable.Subscribe), and calls the given callback every time the 'next' /// operation on the IObserver happens. /// </summary> /// <typeparam name="T"></typeparam> internal class CallbackObserver<T> : IObserver<T> { public CallbackObserver(Action<T> callback) { _callback = callback; } #region private public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(T value) { _callback(value); } private Action<T> _callback; #endregion } // A linked list of IObservable subscriptions (which are IDisposable). // We use this to keep track of the DiagnosticSource subscriptions. // We use this linked list for thread atomicity internal class Subscriptions { public Subscriptions(IDisposable subscription, Subscriptions next) { Subscription = subscription; Next = next; } public IDisposable Subscription; public Subscriptions Next; } #endregion private FilterAndTransform _specs; // Transformation specifications that indicate which sources/events are forwarded. #endregion } }
using System; using System.Text; using System.Web; using Umbraco.Core; using Umbraco.Core.Configuration; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Web { public static class UriUtility { static string _appPath; static string _appPathPrefix; static UriUtility() { SetAppDomainAppVirtualPath(HttpRuntime.AppDomainAppVirtualPath); } // internal for unit testing only internal static void SetAppDomainAppVirtualPath(string appPath) { _appPath = appPath ?? "/"; _appPathPrefix = _appPath; if (_appPathPrefix == "/") _appPathPrefix = String.Empty; } // will be "/" or "/foo" public static string AppPath { get { return _appPath; } } // will be "" or "/foo" public static string AppPathPrefix { get { return _appPathPrefix; } } // adds the virtual directory if any // see also VirtualPathUtility.ToAbsolute public static string ToAbsolute(string url) { //return ResolveUrl(url); url = url.TrimStart('~'); return _appPathPrefix + url; } // strips the virtual directory if any // see also VirtualPathUtility.ToAppRelative public static string ToAppRelative(string virtualPath) { if (virtualPath.InvariantStartsWith(_appPathPrefix) && (virtualPath.Length == _appPathPrefix.Length || virtualPath[_appPathPrefix.Length] == '/')) virtualPath = virtualPath.Substring(_appPathPrefix.Length); if (virtualPath.Length == 0) virtualPath = "/"; return virtualPath; } // maps an internal umbraco uri to a public uri // ie with virtual directory, .aspx if required... public static Uri UriFromUmbraco(Uri uri) { var path = uri.GetSafeAbsolutePath(); if (path != "/") { if (!GlobalSettings.UseDirectoryUrls) path += ".aspx"; else if (UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash) path += "/"; } path = ToAbsolute(path); return uri.Rewrite(path); } // maps a public uri to an internal umbraco uri // ie no virtual directory, no .aspx, lowercase... public static Uri UriToUmbraco(Uri uri) { // note: no need to decode uri here because we're returning a uri // so it will be re-encoded anyway var path = uri.GetSafeAbsolutePath(); path = path.ToLower(); path = ToAppRelative(path); // strip vdir if any //we need to check if the path is /default.aspx because this will occur when using a //web server pre IIS 7 when requesting the root document //if this is the case we need to change it to '/' if (path.StartsWith("/default.aspx", StringComparison.InvariantCultureIgnoreCase)) { string rempath = path.Substring("/default.aspx".Length, path.Length - "/default.aspx".Length); path = rempath.StartsWith("/") ? rempath : "/" + rempath; } if (path != "/") { path = path.TrimEnd('/'); } //if any part of the path contains .aspx, replace it with nothing. //sometimes .aspx is not at the end since we might have /home/sub1.aspx/customtemplate path = path.Replace(".aspx", ""); return uri.Rewrite(path); } #region ResolveUrl // http://www.codeproject.com/Articles/53460/ResolveUrl-in-ASP-NET-The-Perfect-Solution // note // if browsing http://example.com/sub/page1.aspx then // ResolveUrl("page2.aspx") returns "/page2.aspx" // Page.ResolveUrl("page2.aspx") returns "/sub/page2.aspx" (relative...) // public static string ResolveUrl(string relativeUrl) { if (relativeUrl == null) throw new ArgumentNullException("relativeUrl"); if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\') return relativeUrl; int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal); if (idxOfScheme != -1) { int idxOfQM = relativeUrl.IndexOf('?'); if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl; } StringBuilder sbUrl = new StringBuilder(); sbUrl.Append(_appPathPrefix); if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/'); // found question mark already? query string, do not touch! bool foundQM = false; bool foundSlash; // the latest char was a slash? if (relativeUrl.Length > 1 && relativeUrl[0] == '~' && (relativeUrl[1] == '/' || relativeUrl[1] == '\\')) { relativeUrl = relativeUrl.Substring(2); foundSlash = true; } else foundSlash = false; foreach (char c in relativeUrl) { if (!foundQM) { if (c == '?') foundQM = true; else { if (c == '/' || c == '\\') { if (foundSlash) continue; else { sbUrl.Append('/'); foundSlash = true; continue; } } else if (foundSlash) foundSlash = false; } } sbUrl.Append(c); } return sbUrl.ToString(); } #endregion #region Uri string utilities public static bool HasScheme(string uri) { return uri.IndexOf("://") > 0; } public static string StartWithScheme(string uri) { return StartWithScheme(uri, null); } public static string StartWithScheme(string uri, string scheme) { return HasScheme(uri) ? uri : String.Format("{0}://{1}", scheme ?? Uri.UriSchemeHttp, uri); } public static string EndPathWithSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.EnsureEndsWith('/'); if (pos > 0) path += uri.Substring(pos); return path; } public static string TrimPathEndSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.TrimEnd('/'); if (pos > 0) path += uri.Substring(pos); return path; } #endregion /// <summary> /// Returns an faull url with the host, port, etc... /// </summary> /// <param name="absolutePath">An absolute path (i.e. starts with a '/' )</param> /// <param name="httpContext"> </param> /// <returns></returns> /// <remarks> /// Based on http://stackoverflow.com/questions/3681052/get-absolute-url-from-relative-path-refactored-method /// </remarks> internal static Uri ToFullUrl(string absolutePath, HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (String.IsNullOrEmpty(absolutePath)) throw new ArgumentNullException("absolutePath"); if (!absolutePath.StartsWith("/")) throw new FormatException("The absolutePath specified does not start with a '/'"); return new Uri(absolutePath, UriKind.Relative).MakeAbsolute(httpContext.Request.Url); } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Identity and Access Management API Version v1alpha1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/iam/'>Google Identity and Access Management API</a> * <tr><th>API Version<td>v1alpha1 * <tr><th>API Rev<td>20160129 (393) * <tr><th>API Docs * <td><a href='https://cloud.google.com/iam/'> * https://cloud.google.com/iam/</a> * <tr><th>Discovery Name<td>iam * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Identity and Access Management API can be found at * <a href='https://cloud.google.com/iam/'>https://cloud.google.com/iam/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Iam.v1alpha1 { /// <summary>The Iam Service.</summary> public class IamService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1alpha1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public IamService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public IamService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "iam"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://iam.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } } ///<summary>A base abstract class for Iam requests.</summary> public abstract class IamBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new IamBaseServiceRequest instance.</summary> protected IamBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual string Xgafv { get; set; } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual string Alt { get; set; } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Iam parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } namespace Google.Apis.Iam.v1alpha1.Data { }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// StorageAccountsOperations operations. /// </summary> public partial interface IStorageAccountsOperations { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(StorageAccountCheckNameAvailabilityParameters accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the account type or tags for a storage account. It can also /// be used to add a custom domain (note that custom domains cannot be /// added via the Create operation). Only one custom domain is /// supported per storage account. In order to replace a custom domain, /// the old value must be cleared before a new value may be set. To /// clear a custom domain, simply update the custom domain with empty /// string. Then call update again with the new cutsom domain name. The /// update API can only be used to update one of tags, accountType, or /// customDomain per call. To update multiple of these properties, call /// the API multiple times with one change per call. This call does not /// change the storage keys for the account. If you want to change /// storage account keys, use the RegenerateKey operation. The location /// and name of the storage account cannot be changed after creation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one /// property can be changed at a time using this API. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys operation /// for this. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 /// for the default keys /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using Tibia.Addresses; namespace Tibia { public partial class Version { public static void SetVersion871() { BattleList.Start = 0x63FDE8; BattleList.StepCreatures = 0xAC; BattleList.MaxCreatures = 1300; BattleList.End = BattleList.Start + (BattleList.StepCreatures * BattleList.MaxCreatures); Client.StartTime = 0x80CAF0; Client.XTeaKey = 0x7C5CEC; Client.SocketStruct = 0x7C5CC0; Client.RecvPointer = 0x5B85E4; Client.SendPointer = 0x5B8610; Client.LastRcvPacket = 0x7C14A0; Client.DecryptCall = 0x45C6C5; Client.ParserFunc = 0x45C690; Client.GetNextPacketCall = 0x45C6C5; // Same as Client.DecryptCall = ParserFunc + 0x35 Client.RecvStream = 0x7C5CDC; Client.FrameRatePointer = 0x7C9DD4; Client.FrameRateCurrentOffset = 0x60; Client.FrameRateLimitOffset = 0x58; Client.MultiClient = 0x50BFC4; Client.Status = 0x7C928C; Client.SafeMode = 0x7C6114; Client.FollowMode = Client.SafeMode + 4; Client.AttackMode = Client.FollowMode + 4; Client.ActionState = 0x7C92EC; Client.ActionStateFreezer = 0x51EB10; Client.LastMSGText = 0x80CD60; Client.LastMSGAuthor = Client.LastMSGText - 0x28; Client.StatusbarText = Client.StartTime + 0x20; Client.StatusbarTime = Client.StatusbarText - 4; Client.ClickId = 0x7C932C; Client.ClickCount = Client.ClickId + 4; Client.ClickZ = Client.ClickId - 0x68; Client.SeeId = Client.ClickId + 12; Client.SeeCount = Client.SeeId + 4; Client.SeeZ = Client.SeeId - 0x68; Client.ClickContextMenuItemId = Client.SeeId; Client.ClickContextMenuCreatureId = Client.ClickContextMenuItemId + 0x0C; Client.LoginServerStart = 0x7C0C28; Client.StepLoginServer = 112; Client.DistancePort = 100; Client.MaxLoginServers = 10; Client.RSA = 0x5B8980; Client.LoginCharList = 0x7C9240; Client.LoginCharListLength = Client.LoginCharList + 4; Client.LoginSelectedChar = Client.LoginCharList - 4; Client.GameWindowRectPointer = 0x67868C; Client.GameWindowBar = 0x80CB00; Client.DatPointer = 0x7C5D0C; Client.EventTriggerPointer = 0x520620; Client.DialogPointer = 0x67B9F4; Client.DialogLeft = 0x14; Client.DialogTop = 0x18; Client.DialogWidth = 0x1C; Client.DialogHeight = 0x20; Client.DialogCaption = 0x50; Client.LoginAccountNum = 0; Client.LoginPassword = Client.LoginCharList + 8; Client.LoginAccount = Client.LoginPassword + 32; Client.LoginPatch = 0; Client.LoginPatch2 = 0; Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 }; Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 }; Container.Start = 0x679140; Container.StepContainer = 492; Container.StepSlot = 12; Container.MaxContainers = 16; Container.MaxStack = 100; Container.DistanceIsOpen = 0; Container.DistanceId = 4; Container.DistanceName = 16; Container.DistanceVolume = 48; Container.DistanceAmount = 56; Container.DistanceItemId = 60; Container.DistanceItemCount = 64; Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer); ContextMenus.AddContextMenuPtr = 0x452BC0; ContextMenus.OnClickContextMenuPtr = 0x44F780; ContextMenus.OnClickContextMenuVf = 0x5BDB80; ContextMenus.AddSetOutfitContextMenu = 0x453ADC; ContextMenus.AddPartyActionContextMenu = 0x453A04; ContextMenus.AddCopyNameContextMenu = 0x453B6E; ContextMenus.AddTradeWithContextMenu = 0x453769; ContextMenus.AddLookContextMenu = 0x45361F; Creature.DistanceId = 0; Creature.DistanceType = 3; Creature.DistanceName = 4; Creature.DistanceX = 36; Creature.DistanceY = 40; Creature.DistanceZ = 44; Creature.DistanceScreenOffsetHoriz = 48; Creature.DistanceScreenOffsetVert = 52; Creature.DistanceIsWalking = 76; Creature.DistanceDirection = 80; Creature.DistanceOutfit = 96; Creature.DistanceColorHead = 100; Creature.DistanceColorBody = 104; Creature.DistanceColorLegs = 108; Creature.DistanceColorFeet = 112; Creature.DistanceAddon = 116; Creature.DistanceMountId = 120; Creature.DistanceLight = 124; Creature.DistanceLightColor = 128; Creature.DistanceBlackSquare = 136; Creature.DistanceHPBar = 140; Creature.DistanceWalkSpeed = 144; Creature.DistanceIsVisible = 148; Creature.DistanceSkull = 152; Creature.DistanceParty = 156; Creature.DistanceWarIcon = 164; Creature.DistanceIsBlocking = 168; DatItem.StepItems = 0x4C; DatItem.Width = 0; DatItem.Height = 4; DatItem.MaxSizeInPixels = 8; DatItem.Layers = 12; DatItem.PatternX = 16; DatItem.PatternY = 20; DatItem.PatternDepth = 24; DatItem.Phase = 28; DatItem.Sprite = 32; DatItem.Flags = 36; DatItem.CanLookAt = 0; DatItem.WalkSpeed = 40; DatItem.TextLimit = 44; DatItem.LightRadius = 48; DatItem.LightColor = 52; DatItem.ShiftX = 56; DatItem.ShiftY = 60; DatItem.WalkHeight = 64; DatItem.Automap = 68; DatItem.LensHelp = 72; DrawItem.DrawItemFunc = 0x4B5930; DrawSkin.DrawSkinFunc = 0x4B9640; Hotkey.SendAutomaticallyStart = 0x7C6310; Hotkey.SendAutomaticallyStep = 0x01; Hotkey.TextStart = 0x7C6338; Hotkey.TextStep = 0x100; Hotkey.ObjectStart = 0x7C6280; Hotkey.ObjectStep = 0x04; Hotkey.ObjectUseTypeStart = 0x7C6160; Hotkey.ObjectUseTypeStep = 0x04; Hotkey.MaxHotkeys = 36; Map.MapPointer = 0x680548; Map.StepTile = 168; Map.StepTileObject = 12; Map.DistanceTileObjectCount = 0; Map.DistanceTileObjects = 4; Map.DistanceObjectId = 0; Map.DistanceObjectData = 4; Map.DistanceObjectDataEx = 8; Map.MaxTileObjects = 10; Map.MaxX = 18; Map.MaxY = 14; Map.MaxZ = 8; Map.MaxTiles = 2016; Map.ZAxisDefault = 7; Map.NameSpy1 = 0x4F2789; Map.NameSpy2 = 0x4F2793; Map.NameSpy1Default = 0x4C75; Map.NameSpy2Default = 0x4275; Map.LevelSpy1 = 0x4F467A; Map.LevelSpy2 = 0x4F477F; Map.LevelSpy3 = 0x4F4800; Map.LevelSpyPtr = Client.GameWindowRectPointer; Map.LevelSpyAdd1 = 28; Map.LevelSpyAdd2 = 0x5BC0; Map.FullLightNop = 0x4EACF9; Map.FullLightAdr = 0x4EACFC; Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 }; Map.FullLightNopEdited = new byte[] { 0x90, 0x90 }; Map.FullLightAdrDefault = 0x80; Map.FullLightAdrEdited = 0xFF; Player.Experience = 0x63FD50; Player.Flags = Player.Experience - 112; Player.Id = Player.Experience + 16; Player.Health = Player.Experience + 12; Player.HealthMax = Player.Experience + 8; Player.Level = Player.Experience - 8; Player.MagicLevel = Player.Experience - 12; Player.LevelPercent = Player.Experience - 16; Player.MagicLevelPercent = Player.Experience - 20; Player.Mana = Player.Experience - 24; Player.ManaMax = Player.Experience - 28; Player.Soul = Player.Experience - 32; Player.Stamina = Player.Experience - 36; Player.Capacity = Player.Experience - 40; Player.FistPercent = Player.Flags + 4; Player.ClubPercent = Player.FistPercent + 4; Player.SwordPercent = Player.FistPercent + 8; Player.AxePercent = Player.FistPercent + 12; Player.DistancePercent = Player.FistPercent + 16; Player.ShieldingPercent = Player.FistPercent + 20; Player.FishingPercent = Player.FistPercent + 24; Player.Fist = Player.FistPercent + 28; Player.Club = Player.FistPercent + 32; Player.Sword = Player.FistPercent + 36; Player.Axe = Player.FistPercent + 40; Player.Distance = Player.FistPercent + 44; Player.Shielding = Player.FistPercent + 48; Player.Fishing = Player.FistPercent + 52; Player.WhiteSquare = Player.Flags + 60; Player.GreenSquare = Player.Flags + 64; Player.RedSquare = Player.Flags + 68; Player.SlotHead = 0x6790C8; Player.SlotNeck = Player.SlotHead + 12; Player.SlotBackpack = Player.SlotHead + 24; Player.SlotArmor = Player.SlotHead + 36; Player.SlotRight = Player.SlotHead + 48; Player.SlotLeft = Player.SlotHead + 60; Player.SlotLegs = Player.SlotHead + 72; Player.SlotFeet = Player.SlotHead + 84; Player.SlotRing = Player.SlotHead + 96; Player.SlotAmmo = Player.SlotHead + 108; Player.MaxSlots = 10; Player.DistanceSlotCount = 4; Player.CurrentTileToGo = Player.Flags + 132; Player.TilesToGo = Player.CurrentTileToGo + 4; Player.GoToX = Player.Experience + 84; Player.GoToY = Player.GoToX - 4; Player.GoToZ = Player.GoToX - 8; Player.TargetId = Player.RedSquare; Player.TargetBattlelistId = Player.TargetId - 8; Player.TargetBattlelistType = Player.TargetId - 5; Player.TargetType = Player.TargetId + 3; Player.Z = 0x67BA30; Player.Y = Player.Z + 4; Player.X = Player.Z + 8; Player.AttackCount = 0x63D900; Player.FollowCount = Player.AttackCount + 0x20; TextDisplay.PrintName = 0x4F57E3; TextDisplay.PrintFPS = 0x45A6C8; TextDisplay.ShowFPS = 0x63D9FC; TextDisplay.PrintTextFunc = 0x4B4D70; TextDisplay.NopFPS = 0x45A604; Vip.Start = 0x63DA78; Vip.StepPlayers = 0x2C; Vip.MaxPlayers = 200; Vip.DistanceId = 0; Vip.DistanceName = 4; Vip.DistanceStatus = 34; Vip.DistanceIcon = 40; Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers); } } }
// 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.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost.Ipc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.TestHost { /// <summary> /// An <see cref="IServer"/> implementation for executing tests. /// </summary> public class TestServer : IServer { private readonly IWebHost? _hostInstance; private bool _disposed; private ApplicationWrapper? _application; /// <summary> /// For use with IHostBuilder. /// </summary> /// <param name="services"></param> /// <param name="optionsAccessor"></param> public TestServer(IServiceProvider services, IOptions<TestServerOptions> optionsAccessor) : this(services, new FeatureCollection(), optionsAccessor) { } /// <summary> /// For use with IHostBuilder. /// </summary> /// <param name="services"></param> /// <param name="featureCollection"></param> /// <param name="optionsAccessor"></param> public TestServer(IServiceProvider services, IFeatureCollection featureCollection, IOptions<TestServerOptions> optionsAccessor) { Services = services ?? throw new ArgumentNullException(nameof(services)); Features = featureCollection ?? throw new ArgumentNullException(nameof(featureCollection)); var options = optionsAccessor?.Value ?? throw new ArgumentNullException(nameof(optionsAccessor)); AllowSynchronousIO = options.AllowSynchronousIO; PreserveExecutionContext = options.PreserveExecutionContext; BaseAddress = options.BaseAddress; CurrentTestServer = this; } internal static TestServer CurrentTestServer { set; get; } /// <summary> /// For use with IHostBuilder. /// </summary> /// <param name="services"></param> public TestServer(IServiceProvider services) : this(services, new FeatureCollection()) { } /// <summary> /// For use with IHostBuilder. /// </summary> /// <param name="services"></param> /// <param name="featureCollection"></param> public TestServer(IServiceProvider services, IFeatureCollection featureCollection) : this(services, featureCollection, Options.Create(new TestServerOptions())) { Services = services ?? throw new ArgumentNullException(nameof(services)); Features = featureCollection ?? throw new ArgumentNullException(nameof(featureCollection)); } /// <summary> /// For use with IWebHostBuilder. /// </summary> /// <param name="builder"></param> public TestServer(IWebHostBuilder builder) : this(builder, new FeatureCollection()) { } /// <summary> /// For use with IWebHostBuilder. /// </summary> /// <param name="builder"></param> /// <param name="featureCollection"></param> public TestServer(IWebHostBuilder builder, IFeatureCollection featureCollection) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } Features = featureCollection ?? throw new ArgumentNullException(nameof(featureCollection)); var host = builder.UseServer(this).Build(); host.StartAsync().GetAwaiter().GetResult(); _hostInstance = host; Services = host.Services; } /// <summary> /// Gets or sets the base address associated with the HttpClient returned by the test server. Defaults to http://localhost/. /// </summary> public Uri BaseAddress { get; set; } = new Uri("http://localhost/"); /// <summary> /// Gets the <see cref="IWebHost" /> instance associated with the test server. /// </summary> public IWebHost Host { get { return _hostInstance ?? throw new InvalidOperationException("The TestServer constructor was not called with a IWebHostBuilder so IWebHost is not available."); } } /// <summary> /// Gets the service provider associated with the test server. /// </summary> public IServiceProvider Services { get; } /// <summary> /// Gets the collection of server features associated with the test server. /// </summary> public IFeatureCollection Features { get; } /// <summary> /// Gets or sets a value that controls whether synchronous IO is allowed for the <see cref="HttpContext.Request"/> and <see cref="HttpContext.Response"/>. The default value is <see langword="false" />. /// </summary> public bool AllowSynchronousIO { get; set; } /// <summary> /// Gets or sets a value that controls if <see cref="ExecutionContext"/> and <see cref="AsyncLocal{T}"/> values are preserved from the client to the server. The default value is <see langword="false" />. /// </summary> public bool PreserveExecutionContext { get; set; } internal ApplicationWrapper Application { get => _application ?? throw new InvalidOperationException("The server has not been started or no web application was configured."); } /// <summary> /// Creates a custom <see cref="HttpMessageHandler" /> for processing HTTP requests/responses with the test server. /// </summary> public HttpMessageHandler CreateHandler() { var pathBase = BaseAddress == null ? PathString.Empty : PathString.FromUriComponent(BaseAddress); return new ClientHandler(pathBase, Application) { AllowSynchronousIO = AllowSynchronousIO, PreserveExecutionContext = PreserveExecutionContext }; } /// <summary> /// Creates a <see cref="HttpClient" /> for processing HTTP requests/responses with the test server. /// </summary> public HttpClient CreateClient() { return new HttpClient(CreateHandler()) { BaseAddress = BaseAddress }; } /// <summary> /// Creates a <see cref="WebSocketClient" /> for interacting with the test server. /// </summary> public WebSocketClient CreateWebSocketClient() { var pathBase = BaseAddress == null ? PathString.Empty : PathString.FromUriComponent(BaseAddress); return new WebSocketClient(pathBase, Application) { AllowSynchronousIO = AllowSynchronousIO, PreserveExecutionContext = PreserveExecutionContext }; } /// <summary> /// Begins constructing a request message for submission. /// </summary> /// <param name="path"></param> /// <returns><see cref="RequestBuilder"/> to use in constructing additional request details.</returns> public RequestBuilder CreateRequest(string path) { return new RequestBuilder(this, path); } /// <summary> /// Creates, configures, sends, and returns a <see cref="HttpContext"/>. This completes as soon as the response is started. /// </summary> /// <returns></returns> public async Task<HttpContext> SendAsync(Action<HttpContext> configureContext, CancellationToken cancellationToken = default) { if (configureContext == null) { throw new ArgumentNullException(nameof(configureContext)); } var builder = new HttpContextBuilder(Application, AllowSynchronousIO, PreserveExecutionContext); builder.Configure((context, reader) => { var request = context.Request; request.Scheme = BaseAddress.Scheme; request.Host = HostString.FromUriComponent(BaseAddress); if (BaseAddress.IsDefaultPort) { request.Host = new HostString(request.Host.Host); } var pathBase = PathString.FromUriComponent(BaseAddress); if (pathBase.HasValue && pathBase.Value.EndsWith('/')) { pathBase = new PathString(pathBase.Value[..^1]); // All but the last character. } request.PathBase = pathBase; }); builder.Configure((context, reader) => configureContext(context)); // TODO: Wrap the request body if any? return await builder.SendAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Dispoes the <see cref="IWebHost" /> object associated with the test server. /// </summary> public void Dispose() { if (!_disposed) { _disposed = true; _hostInstance?.Dispose(); } } Task IServer.StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) { _application = new ApplicationWrapper<TContext>(application, () => { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } }); var ipcCore = Services.GetRequiredService<IpcCore>(); ipcCore.Start(); return Task.CompletedTask; } Task IServer.StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <devdoc> /// Listens to the system directory change notifications and /// raises events when a directory or file within a directory changes. /// </devdoc> public partial class FileSystemWatcher : IDisposable { /// <devdoc> /// Private instance variables /// </devdoc> // Directory being monitored private string _directory; // Filter for name matching private string _filter; // The watch filter for the API call. private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; private NotifyFilters _notifyFilters = c_defaultNotifyFilters; // Flag to watch subtree of this directory private bool _includeSubdirectories = false; // Flag to note whether we are attached to the thread pool and responding to changes private bool _enabled = false; // Buffer size private int _internalBufferSize = 8192; // Used for synchronization private bool _disposed; // Event handlers private FileSystemEventHandler _onChangedHandler = null; private FileSystemEventHandler _onCreatedHandler = null; private FileSystemEventHandler _onDeletedHandler = null; private RenamedEventHandler _onRenamedHandler = null; private ErrorEventHandler _onErrorHandler = null; // To validate the input for "path" private static readonly char[] s_wildcards = new char[] { '?', '*' }; private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size); #if DEBUG static FileSystemWatcher() { int s_notifyFiltersValidMask = 0; foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters))) s_notifyFiltersValidMask |= enumValue; Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum."); } #endif ~FileSystemWatcher() { this.Dispose(false); } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class. /// </devdoc> public FileSystemWatcher() { _directory = string.Empty; _filter = "*.*"; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory to monitor. /// </devdoc> public FileSystemWatcher(string path) : this(path, "*.*") { } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory and type of files to monitor. /// </devdoc> public FileSystemWatcher(string path, string filter) { if (path == null) throw new ArgumentNullException(nameof(path)); if (filter == null) throw new ArgumentNullException(nameof(filter)); // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0 || !Directory.Exists(path)) throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path)); _directory = path; _filter = filter; } /// <devdoc> /// Gets or sets the type of changes to watch for. /// </devdoc> public NotifyFilters NotifyFilter { get { return _notifyFilters; } set { if (((int)value & ~c_notifyFiltersValidMask) != 0) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "value", (int)value, nameof(NotifyFilters))); if (_notifyFilters != value) { _notifyFilters = value; Restart(); } } } /// <devdoc> /// Gets or sets a value indicating whether the component is enabled. /// </devdoc> public bool EnableRaisingEvents { get { return _enabled; } set { if (_enabled == value) { return; } if (value) { StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started } else { StopRaisingEvents(); // will set _enabled to false } } } /// <devdoc> /// Gets or sets the filter string, used to determine what files are monitored in a directory. /// </devdoc> public string Filter { get { return _filter; } set { if (string.IsNullOrEmpty(value)) { // Skip the string compare for "*.*" since it has no case-insensitive representation that differs from // the case-sensitive representation. _filter = "*.*"; } else if (!string.Equals(_filter, value, PathInternal.StringComparison)) { _filter = value; } } } /// <devdoc> /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. /// </devdoc> public bool IncludeSubdirectories { get { return _includeSubdirectories; } set { if (_includeSubdirectories != value) { _includeSubdirectories = value; Restart(); } } } /// <devdoc> /// Gets or sets the size of the internal buffer. /// </devdoc> public int InternalBufferSize { get { return _internalBufferSize; } set { if (_internalBufferSize != value) { if (value < 4096) { _internalBufferSize = 4096; } else { _internalBufferSize = value; } Restart(); } } } /// <summary>Allocates a buffer of the requested internal buffer size.</summary> /// <returns>The allocated buffer.</returns> private byte[] AllocateBuffer() { try { return new byte[_internalBufferSize]; } catch (OutOfMemoryException) { throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize)); } } /// <devdoc> /// Gets or sets the path of the directory to watch. /// </devdoc> public string Path { get { return _directory; } set { value = (value == null) ? string.Empty : value; if (!string.Equals(_directory, value, PathInternal.StringComparison)) { if (!Directory.Exists(value)) { throw new ArgumentException(SR.Format(SR.InvalidDirName, value)); } _directory = value; Restart(); } } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed. /// </devdoc> public event FileSystemEventHandler Changed { add { _onChangedHandler += value; } remove { _onChangedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created. /// </devdoc> public event FileSystemEventHandler Created { add { _onCreatedHandler += value; } remove { _onCreatedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted. /// </devdoc> public event FileSystemEventHandler Deleted { add { _onDeletedHandler += value; } remove { _onDeletedHandler -= value; } } /// <devdoc> /// Occurs when the internal buffer overflows. /// </devdoc> public event ErrorEventHandler Error { add { _onErrorHandler += value; } remove { _onErrorHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is renamed. /// </devdoc> public event RenamedEventHandler Renamed { add { _onRenamedHandler += value; } remove { _onRenamedHandler -= value; } } /// <devdoc> /// Disposes of the <see cref='System.IO.FileSystemWatcher'/>. /// </devdoc> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <devdoc> /// </devdoc> protected virtual void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources _onChangedHandler = null; _onCreatedHandler = null; _onDeletedHandler = null; _onRenamedHandler = null; _onErrorHandler = null; } else { FinalizeDispose(); } } finally { _disposed = true; } } /// <devdoc> /// Sees if the name given matches the name filter we have. /// </devdoc> /// <internalonly/> private bool MatchPattern(string relativePath) { string name = System.IO.Path.GetFileName(relativePath); return name != null ? PatternMatcher.StrictMatchPattern(_filter, name) : false; } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyInternalBufferOverflowEvent() { _onErrorHandler?.Invoke(this, new ErrorEventArgs( new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory)))); } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName) { // filter if there's no handler or neither new name or old name match a specified pattern RenamedEventHandler handler = _onRenamedHandler; if (handler != null && (MatchPattern(name) || MatchPattern(oldName))) { handler(this, new RenamedEventArgs(action, _directory, name, oldName)); } } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name) { FileSystemEventHandler handler = null; switch (changeType) { case WatcherChangeTypes.Created: handler = _onCreatedHandler; break; case WatcherChangeTypes.Deleted: handler = _onDeletedHandler; break; case WatcherChangeTypes.Changed: handler = _onChangedHandler; break; default: Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType); break; } if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name)); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnChanged(FileSystemEventArgs e) { _onChangedHandler?.Invoke(this, e); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnCreated(FileSystemEventArgs e) { _onCreatedHandler?.Invoke(this, e); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnDeleted(FileSystemEventArgs e) { _onDeletedHandler?.Invoke(this, e); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnError(ErrorEventArgs e) { _onErrorHandler?.Invoke(this, e); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnRenamed(RenamedEventArgs e) { _onRenamedHandler?.Invoke(this, e); } public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) => WaitForChanged(changeType, Timeout.Infinite); public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { // The full framework implementation doesn't do any argument validation, so // none is done here, either. var tcs = new TaskCompletionSource<WaitForChangedResult>(); FileSystemEventHandler fseh = null; RenamedEventHandler reh = null; // Register the event handlers based on what events are desired. The full framework // doesn't register for the Error event, so this doesn't either. if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0) { fseh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false)); } }; if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh; if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { reh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false)); } }; Renamed += reh; } try { // Enable the FSW if it wasn't already. bool wasEnabled = EnableRaisingEvents; if (!wasEnabled) { EnableRaisingEvents = true; } // Block until an appropriate event arrives or until we timeout. Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true"); tcs.Task.Wait(timeout); // Reset the enabled state to what it was. EnableRaisingEvents = wasEnabled; } finally { // Unregister the event handlers. if (reh != null) { Renamed -= reh; } if (fseh != null) { if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh; if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh; } } // Return the results. return tcs.Task.Status == TaskStatus.RanToCompletion ? tcs.Task.Result : WaitForChangedResult.TimedOutResult; } /// <devdoc> /// Stops and starts this object. /// </devdoc> /// <internalonly/> private void Restart() { if (_enabled) { StopRaisingEvents(); StartRaisingEventsIfNotDisposed(); } } private void StartRaisingEventsIfNotDisposed() { //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); StartRaisingEvents(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; using Internal.Runtime; using Internal.Runtime.Augments; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] public unsafe struct RuntimeTypeHandle : IEquatable<RuntimeTypeHandle>, ISerializable { // // Caution: There can be and are multiple EEType for the "same" type (e.g. int[]). That means // you can't use the raw IntPtr value for comparisons. // internal RuntimeTypeHandle(EETypePtr pEEType) { _value = pEEType.RawValue; } public override bool Equals(Object obj) { if (obj is RuntimeTypeHandle) { RuntimeTypeHandle handle = (RuntimeTypeHandle)obj; return Equals(handle); } return false; } public override int GetHashCode() { if (IsNull) return 0; return this.ToEETypePtr().GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(RuntimeTypeHandle handle) { if (_value == handle._value) { return true; } else if (this.IsNull || handle.IsNull) { return false; } else { return RuntimeImports.AreTypesEquivalent(this.ToEETypePtr(), handle.ToEETypePtr()); } } public static bool operator ==(object left, RuntimeTypeHandle right) { if (left is RuntimeTypeHandle) return right.Equals((RuntimeTypeHandle)left); return false; } public static bool operator ==(RuntimeTypeHandle left, object right) { if (right is RuntimeTypeHandle) return left.Equals((RuntimeTypeHandle)right); return false; } public static bool operator !=(object left, RuntimeTypeHandle right) { if (left is RuntimeTypeHandle) return !right.Equals((RuntimeTypeHandle)left); return true; } public static bool operator !=(RuntimeTypeHandle left, object right) { if (right is RuntimeTypeHandle) return !left.Equals((RuntimeTypeHandle)right); return true; } public IntPtr Value => _value; public ModuleHandle GetModuleHandle() { Type type = Type.GetTypeFromHandle(this); if (type == null) return default(ModuleHandle); return type.Module.ModuleHandle; } public RuntimeTypeHandle(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); try { Type type = (Type)info.GetValue("TypeObj", typeof(Type)); if (type == null) throw new SerializationException(SR.Serialization_InsufficientState); _value = type.TypeHandle.ToEETypePtr().RawValue; } catch (Exception e) when (!(e is SerializationException)) { throw new SerializationException(e.Message, e); } } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); try { if(_value == IntPtr.Zero) throw new SerializationException(SR.Serialization_InvalidFieldState); Type type = Type.GetTypeFromHandle(this); Debug.Assert(type != null); info.AddValue("TypeObj", type, typeof(Type)); } catch (Exception e) when (!(e is SerializationException)) { throw new SerializationException(e.Message, e); } } internal EETypePtr ToEETypePtr() { return new EETypePtr(_value); } internal bool IsNull { get { return _value == new IntPtr(0); } } // Last resort string for Type.ToString() when no metadata around. internal String LastResortToString { get { String s; EETypePtr eeType = this.ToEETypePtr(); IntPtr rawEEType = eeType.RawValue; IntPtr moduleBase = RuntimeImports.RhGetOSModuleFromEEType(rawEEType); if (moduleBase != IntPtr.Zero) { uint rva = (uint)(rawEEType.ToInt64() - moduleBase.ToInt64()); s = "EETypeRva:0x" + rva.LowLevelToString(); } else { s = "EETypePointer:0x" + rawEEType.LowLevelToString(); } ReflectionExecutionDomainCallbacks callbacks = RuntimeAugments.CallbacksIfAvailable; if (callbacks != null) { String penultimateLastResortString = callbacks.GetBetterDiagnosticInfoIfAvailable(this); if (penultimateLastResortString != null) s += "(" + penultimateLastResortString + ")"; } return s; } } [Intrinsic] internal static IntPtr GetValueInternal(RuntimeTypeHandle handle) { return handle.RawValue; } internal IntPtr RawValue { get { return _value; } } private IntPtr _value; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { internal partial class CSharpIntroduceVariableService { protected override async Task<Document> IntroduceLocalAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken) { var containerToGenerateInto = GetContainerToGenerateInto(document, expression, cancellationToken); var newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant, containerToGenerateInto, cancellationToken); var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); var modifiers = isConstant ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList); var options = await document.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers, SyntaxFactory.VariableDeclaration( this.GetTypeSyntax(document, options, expression, isConstant, cancellationToken), SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, SyntaxFactory.EqualsValueClause(expression.WithoutTrailingTrivia().WithoutLeadingTrivia()))))); switch (containerToGenerateInto) { case BlockSyntax block: return await IntroduceLocalDeclarationIntoBlockAsync( document, block, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false); case ArrowExpressionClauseSyntax arrowExpression: return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( document, arrowExpression, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); case LambdaExpressionSyntax lambda: return IntroduceLocalDeclarationIntoLambda( document, lambda, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } throw new InvalidOperationException(); } private SyntaxNode GetContainerToGenerateInto( SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken) { var anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken); var lambdas = anonymousMethodParameters.SelectMany(p => p.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).AsEnumerable()) .Where(n => n is ParenthesizedLambdaExpressionSyntax || n is SimpleLambdaExpressionSyntax) .ToSet(); var parentLambda = GetParentLambda(expression, lambdas); if (parentLambda != null) { return parentLambda; } else if (IsInExpressionBodiedMember(expression)) { return expression.GetAncestorOrThis<ArrowExpressionClauseSyntax>(); } else { return expression.GetAncestorsOrThis<BlockSyntax>().LastOrDefault(); } } private Document IntroduceLocalDeclarationIntoLambda( SemanticDocument document, SyntaxNode oldLambda, ExpressionSyntax expression, IdentifierNameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = oldLambda is ParenthesizedLambdaExpressionSyntax ? (ExpressionSyntax)((ParenthesizedLambdaExpressionSyntax)oldLambda).Body : (ExpressionSyntax)((SimpleLambdaExpressionSyntax)oldLambda).Body; var rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken); var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol; var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Block(declarationStatement) : SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)); newBody = newBody.WithAdditionalAnnotations(Formatter.Annotation); var newLambda = oldLambda is ParenthesizedLambdaExpressionSyntax ? ((ParenthesizedLambdaExpressionSyntax)oldLambda).WithBody(newBody) : (SyntaxNode)((SimpleLambdaExpressionSyntax)oldLambda).WithBody(newBody); var newRoot = document.Root.ReplaceNode(oldLambda, newLambda); return document.Document.WithSyntaxRoot(newRoot); } private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet<SyntaxNode> lambdas) { var current = expression; while (current != null) { if (lambdas.Contains(current.Parent)) { return current.Parent; } current = current.Parent as ExpressionSyntax; } return null; } private TypeSyntax GetTypeSyntax(SemanticDocument document, DocumentOptionSet options, ExpressionSyntax expression, bool isConstant, CancellationToken cancellationToken) { var typeSymbol = GetTypeSymbol(document, expression, cancellationToken); if (typeSymbol.ContainsAnonymousType()) { return SyntaxFactory.IdentifierName("var"); } if (!isConstant && CanUseVar(typeSymbol) && TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, options, cancellationToken)) { return SyntaxFactory.IdentifierName("var"); } return typeSymbol.GenerateTypeSyntax(); } private bool CanUseVar(ITypeSymbol typeSymbol) { return typeSymbol.TypeKind != TypeKind.Delegate && !typeSymbol.IsErrorType() && !typeSymbol.IsFormattableString(); } private static async Task<Tuple<SemanticDocument, ISet<ExpressionSyntax>>> ComplexifyParentingStatements( SemanticDocument semanticDocument, ISet<ExpressionSyntax> matches, CancellationToken cancellationToken) { // First, track the matches so that we can get back to them later. var newRoot = semanticDocument.Root.TrackNodes(matches); var newDocument = semanticDocument.Document.WithSyntaxRoot(newRoot); var newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); var newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); // Next, expand the topmost parenting expression of each match, being careful // not to expand the matches themselves. var topMostExpressions = newMatches .Select(m => m.AncestorsAndSelf().OfType<ExpressionSyntax>().Last()) .Distinct(); newRoot = await newSemanticDocument.Root .ReplaceNodesAsync( topMostExpressions, computeReplacementAsync: async (oldNode, newNode, ct) => { return await Simplifier .ExpandAsync( oldNode, newSemanticDocument.Document, expandInsideNode: node => { var expression = node as ExpressionSyntax; return expression == null || !newMatches.Contains(expression); }, cancellationToken: ct) .ConfigureAwait(false); }, cancellationToken: cancellationToken) .ConfigureAwait(false); newDocument = newSemanticDocument.Document.WithSyntaxRoot(newRoot); newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); return Tuple.Create(newSemanticDocument, newMatches); } private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( SemanticDocument document, ArrowExpressionClauseSyntax arrowExpression, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = arrowExpression; var oldParentingNode = oldBody.Parent; var leadingTrivia = oldBody.GetLeadingTrivia() .AddRange(oldBody.ArrowToken.TrailingTrivia); var newStatement = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken); var newBody = SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(newStatement)) .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(oldBody.GetTrailingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode newParentingNode = null; if (oldParentingNode is BasePropertyDeclarationSyntax) { var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, newBody); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor })); newParentingNode = ((BasePropertyDeclarationSyntax)oldParentingNode).RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia); if (newParentingNode.IsKind(SyntaxKind.PropertyDeclaration)) { var propertyDeclaration = ((PropertyDeclarationSyntax)newParentingNode); newParentingNode = propertyDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(propertyDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexerDeclaration = ((IndexerDeclarationSyntax)newParentingNode); newParentingNode = indexerDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(indexerDeclaration.SemicolonToken.TrailingTrivia); } } else if (oldParentingNode is BaseMethodDeclarationSyntax) { newParentingNode = ((BaseMethodDeclarationSyntax)oldParentingNode) .RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia) .WithBody(newBody); if (newParentingNode.IsKind(SyntaxKind.MethodDeclaration)) { var methodDeclaration = ((MethodDeclarationSyntax)newParentingNode); newParentingNode = methodDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(methodDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.OperatorDeclaration)) { var operatorDeclaration = ((OperatorDeclarationSyntax)newParentingNode); newParentingNode = operatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(operatorDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.ConversionOperatorDeclaration)) { var conversionOperatorDeclaration = ((ConversionOperatorDeclarationSyntax)newParentingNode); newParentingNode = conversionOperatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(conversionOperatorDeclaration.SemicolonToken.TrailingTrivia); } } var newRoot = document.Root.ReplaceNode(oldParentingNode, newParentingNode); return document.Document.WithSyntaxRoot(newRoot); } private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync( SemanticDocument document, BlockSyntax block, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var oldOutermostBlock = block; var matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken); Debug.Assert(matches.Contains(expression)); var complexified = await ComplexifyParentingStatements(document, matches, cancellationToken).ConfigureAwait(false); document = complexified.Item1; matches = complexified.Item2; // Our original expression should have been one of the matches, which were tracked as part // of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First(); var innermostStatements = new HashSet<StatementSyntax>( matches.Select(expr => expr.GetAncestorOrThis<StatementSyntax>())); if (innermostStatements.Count == 1) { // If there was only one match, or all the matches came from the same // statement, then we want to place the declaration right above that // statement. Note: we special case this because the statement we are going // to go above might not be in a block and we may have to generate it return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } var oldInnerMostCommonBlock = matches.FindInnermostCommonBlock(); var allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => expr.GetAncestorsOrThis<StatementSyntax>())); var firstStatementAffectedInBlock = oldInnerMostCommonBlock.Statements.First(allAffectedStatements.Contains); var firstStatementAffectedIndex = oldInnerMostCommonBlock.Statements.IndexOf(firstStatementAffectedInBlock); var newInnerMostBlock = Rewrite( document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken); var statements = new List<StatementSyntax>(); statements.AddRange(newInnerMostBlock.Statements.Take(firstStatementAffectedIndex)); statements.Add(declarationStatement); statements.AddRange(newInnerMostBlock.Statements.Skip(firstStatementAffectedIndex)); var finalInnerMostBlock = newInnerMostBlock.WithStatements( SyntaxFactory.List<StatementSyntax>(statements)); var newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock); return document.Document.WithSyntaxRoot(newRoot); } private Document IntroduceLocalForSingleOccurrenceIntoBlock( SemanticDocument document, ExpressionSyntax expression, NameSyntax localName, LocalDeclarationStatementSyntax localDeclaration, bool allOccurrences, CancellationToken cancellationToken) { var oldStatement = expression.GetAncestorOrThis<StatementSyntax>(); var newStatement = Rewrite( document, expression, localName, document, oldStatement, allOccurrences, cancellationToken); if (oldStatement.IsParentKind(SyntaxKind.Block)) { var oldBlock = oldStatement.Parent as BlockSyntax; var statementIndex = oldBlock.Statements.IndexOf(oldStatement); var newBlock = oldBlock.WithStatements(CreateNewStatementList( oldBlock.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldBlock, newBlock); return document.Document.WithSyntaxRoot(newRoot); } else if (oldStatement.IsParentKind(SyntaxKind.SwitchSection)) { var oldSwitchSection = oldStatement.Parent as SwitchSectionSyntax; var statementIndex = oldSwitchSection.Statements.IndexOf(oldStatement); var newSwitchSection = oldSwitchSection.WithStatements(CreateNewStatementList( oldSwitchSection.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldSwitchSection, newSwitchSection); return document.Document.WithSyntaxRoot(newRoot); } else { // we need to introduce a block to put the original statement, along with // the statement we're generating var newBlock = SyntaxFactory.Block(localDeclaration, newStatement).WithAdditionalAnnotations(Formatter.Annotation); var newRoot = document.Root.ReplaceNode(oldStatement, newBlock); return document.Document.WithSyntaxRoot(newRoot); } } private static SyntaxList<StatementSyntax> CreateNewStatementList( SyntaxList<StatementSyntax> oldStatements, LocalDeclarationStatementSyntax localDeclaration, StatementSyntax newStatement, int statementIndex) { return oldStatements.Take(statementIndex) .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia())) .Concat(newStatement.WithoutLeadingTrivia()) .Concat(oldStatements.Skip(statementIndex + 1)) .ToSyntaxList(); } } }
// 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; namespace System.Globalization { // Internal Contract for all Globalization APIs that are needed by lower levels of System.Private.CoreLib. // This is class acts as a gateway between everything in System.Private.CoreLib and System.Globalization. internal partial class FormatProvider { public static IFormatProvider InvariantCulture { get { return CultureInfo.InvariantCulture; } } #region Char/String Conversions public static string ToLower(string s) { return CultureInfo.CurrentCulture.TextInfo.ToLower(s); } public static char ToLower(char c) { return CultureInfo.CurrentCulture.TextInfo.ToLower(c); } public static string ToLowerInvariant(string s) { return CultureInfo.InvariantCulture.TextInfo.ToLower(s); } public static char ToLowerInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToLower(c); } public static string ToUpper(string s) { return CultureInfo.CurrentCulture.TextInfo.ToUpper(s); } public static char ToUpper(char c) { return CultureInfo.CurrentCulture.TextInfo.ToUpper(c); } public static string ToUpperInvariant(string s) { return CultureInfo.InvariantCulture.TextInfo.ToUpper(s); } public static char ToUpperInvariant(char c) { return CultureInfo.InvariantCulture.TextInfo.ToUpper(c); } public static UnicodeCategory GetUnicodeCategory(char c) { return CharUnicodeInfo.GetUnicodeCategory(c); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { return CharUnicodeInfo.GetUnicodeCategory(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(string s, int index) { return CharUnicodeInfo.GetNumericValue(s, index); } #endregion #region Culture Comparisons public static int GetHashCodeInvariantIgnoreCase(string source) { return CultureInfo.InvariantCulture.CompareInfo.GetHashCodeOfString(source, CompareOptions.IgnoreCase); } public static int GetHashCodeOrdinalIgnoreCase(string source) { return TextInfo.GetHashCodeOrdinalIgnoreCase(source); } public static int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2) { return CultureInfo.CurrentCulture.CompareInfo.Compare(string1, offset1, length1, string2, offset2, length2, CompareOptions.None); } public static int CompareIgnoreCase(String string1, int offset1, int length1, String string2, int offset2, int length2) { return CultureInfo.CurrentCulture.CompareInfo.Compare(string1, offset1, length1, string2, offset2, length2, CompareOptions.IgnoreCase); } public static int CompareOrdinalIgnoreCase(String string1, int offset1, int length1, String string2, int offset2, int length2) { return CompareInfo.CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2); } public static StringComparer GetCultureAwareStringComparer(bool ignoreCase) { return new CultureAwareComparer(CultureInfo.CurrentCulture, ignoreCase); } public static int IndexOf(String source, String value, int startIndex, int count) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf(source, value, startIndex, count, CompareOptions.None); } public static int IndexOfIgnoreCase(String source, String value, int startIndex, int count) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf(source, value, startIndex, count, CompareOptions.IgnoreCase); } public static bool IsPrefix(String source, String prefix) { return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(source, prefix, CompareOptions.None); } public static bool IsPrefixIgnoreCase(String source, String prefix) { return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(source, prefix, CompareOptions.IgnoreCase); } public static bool IsSuffix(String source, String suffix) { return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(source, suffix, CompareOptions.None); } public static bool IsSuffixIgnoreCase(String source, String suffix) { return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(source, suffix, CompareOptions.IgnoreCase); } public static int LastIndexOf(String source, String value, int startIndex, int count) { return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public static int LastIndexOfIgnoreCase(String source, String value, int startIndex, int count) { return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(source, value, startIndex, count, CompareOptions.IgnoreCase); } public static int OrdinalIndexOf(String source, String value, int startIndex, int count) { return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, startIndex, count, CompareOptions.Ordinal); } public static int OrdinalIndexOfIgnoreCase(String source, String value, int startIndex, int count) { return TextInfo.IndexOfStringOrdinalIgnoreCase(source, value, startIndex, count); } public static int OrdinalLastIndexOf(String source, String value, int startIndex, int count) { return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(source, value, startIndex, count, CompareOptions.Ordinal); } public static int OrdinalLastIndexOfIgnoreCase(String source, String value, int startIndex, int count) { return TextInfo.LastIndexOfStringOrdinalIgnoreCase(source, value, startIndex, count); } #endregion #region Formatting // provider if null means we use NumberFormatInfo.CurrenctInfo otherwise we use NumberFormatInfo.GetInstance(provider) public static String FormatDateTime(DateTime value, String format, IFormatProvider provider) { return DateTimeFormat.Format(value, format, provider); } public static String FormatDateTime(DateTime value, String format, IFormatProvider provider, TimeSpan offSet) { return DateTimeFormat.Format(value, format, provider, offSet); } public static String FormatDecimal(Decimal value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatDecimal(value, format, provider); } public static String FormatDouble(double value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatDouble(value, format, provider); } public static String FormatInt32(int value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatInt32(value, format, provider); } public static String FormatInt64(long value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatInt64(value, format, provider); } public static String FormatSingle(float value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatSingle(value, format, provider); } public static String FormatTimeSpan(TimeSpan value, String format, IFormatProvider provider) { return FormatProvider.TimeSpanFormat.Format(value, format, provider); } public static String FormatUInt32(uint value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatUInt32(value, format, provider); } public static String FormatUInt64(ulong value, String format, IFormatProvider provider) { return FormatProvider.Number.FormatUInt64(value, format, provider); } public static string[] GetAllDateTimes(DateTime value, char format, IFormatProvider provider) { if (format == (char)0) return FormatProvider.DateTimeFormat.GetAllDateTimes(value, provider); else return FormatProvider.DateTimeFormat.GetAllDateTimes(value, format, provider); } #endregion #region Parsing public static DateTime ParseDateTime(String value, IFormatProvider provider, DateTimeStyles styles) { return FormatProvider.DateTimeParse.Parse(value, provider, styles); } public static DateTime ParseDateTime(String value, IFormatProvider provider, DateTimeStyles styles, out TimeSpan offset) { return FormatProvider.DateTimeParse.Parse(value, provider, styles, out offset); } public static DateTime ParseDateTimeExact(String value, String format, IFormatProvider provider, DateTimeStyles styles) { return FormatProvider.DateTimeParse.ParseExact(value, format, provider, styles); } public static DateTime ParseDateTimeExact(String value, String format, IFormatProvider provider, DateTimeStyles styles, out TimeSpan offset) { return FormatProvider.DateTimeParse.ParseExact(value, format, provider, styles, out offset); } public static DateTime ParseDateTimeExactMultiple(String value, String[] formats, IFormatProvider provider, DateTimeStyles styles) { return FormatProvider.DateTimeParse.ParseExactMultiple(value, formats, provider, styles); } public static DateTime ParseDateTimeExactMultiple(String value, String[] formats, IFormatProvider provider, DateTimeStyles styles, out TimeSpan offset) { return FormatProvider.DateTimeParse.ParseExactMultiple(value, formats, provider, styles, out offset); } public static Decimal ParseDecimal(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseDecimal(value, options, provider); } public static Double ParseDouble(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseDouble(value, options, provider); } public static int ParseInt32(String s, NumberStyles styles, IFormatProvider provider) { return FormatProvider.Number.ParseInt32(s, styles, provider); } public static Int64 ParseInt64(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseInt64(value, options, provider); } public static Single ParseSingle(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseSingle(value, options, provider); } public static TimeSpan ParseTimeSpan(String value, IFormatProvider provider) { return FormatProvider.TimeSpanParse.Parse(value, provider); } public static TimeSpan ParseTimeSpanExact(String value, String format, IFormatProvider provider, TimeSpanStyles styles) { return FormatProvider.TimeSpanParse.ParseExact(value, format, provider, styles); } public static TimeSpan ParseTimeSpanExactMultiple(String value, String[] formats, IFormatProvider provider, TimeSpanStyles styles) { return FormatProvider.TimeSpanParse.ParseExactMultiple(value, formats, provider, styles); } public static UInt32 ParseUInt32(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseUInt32(value, options, provider); } public static UInt64 ParseUInt64(String value, NumberStyles options, IFormatProvider provider) { return FormatProvider.Number.ParseUInt64(value, options, provider); } public static Boolean TryParseDateTime(String value, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { return FormatProvider.DateTimeParse.TryParse(value, provider, styles, out result); } public static Boolean TryParseDateTime(String value, IFormatProvider provider, DateTimeStyles styles, out DateTime result, out TimeSpan offset) { return FormatProvider.DateTimeParse.TryParse(value, provider, styles, out result, out offset); } public static Boolean TryParseDateTimeExact(String value, String format, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { return FormatProvider.DateTimeParse.TryParseExact(value, format, provider, styles, out result); } public static Boolean TryParseDateTimeExact(String value, String format, IFormatProvider provider, DateTimeStyles styles, out DateTime result, out TimeSpan offset) { return FormatProvider.DateTimeParse.TryParseExact(value, format, provider, styles, out result, out offset); } public static Boolean TryParseDateTimeExactMultiple(String value, String[] formats, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { return FormatProvider.DateTimeParse.TryParseExactMultiple(value, formats, provider, styles, out result); } public static Boolean TryParseDateTimeExactMultiple(String value, String[] formats, IFormatProvider provider, DateTimeStyles styles, out DateTime result, out TimeSpan offset) { return FormatProvider.DateTimeParse.TryParseExactMultiple(value, formats, provider, styles, out result, out offset); } public static Boolean TryParseDecimal(String value, NumberStyles options, IFormatProvider provider, out Decimal result) { return FormatProvider.Number.TryParseDecimal(value, options, provider, out result); } public static Boolean TryParseDouble(String value, NumberStyles options, IFormatProvider provider, out Double result) { return FormatProvider.Number.TryParseDouble(value, options, provider, out result); } public static Boolean TryParseInt32(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { return FormatProvider.Number.TryParseInt32(s, style, provider, out result); } public static Boolean TryParseInt64(String s, NumberStyles style, IFormatProvider provider, out Int64 result) { return FormatProvider.Number.TryParseInt64(s, style, provider, out result); } public static Boolean TryParseSingle(String value, NumberStyles options, IFormatProvider provider, out Single result) { return FormatProvider.Number.TryParseSingle(value, options, provider, out result); } public static Boolean TryParseTimeSpan(String value, IFormatProvider provider, out TimeSpan result) { return FormatProvider.TimeSpanParse.TryParse(value, provider, out result); } public static Boolean TryParseTimeSpanExact(String value, String format, IFormatProvider provider, TimeSpanStyles styles, out TimeSpan result) { return FormatProvider.TimeSpanParse.TryParseExact(value, format, provider, styles, out result); } public static Boolean TryParseTimeSpanExactMultiple(String value, String[] formats, IFormatProvider provider, TimeSpanStyles styles, out TimeSpan result) { return FormatProvider.TimeSpanParse.TryParseExactMultiple(value, formats, provider, styles, out result); } public static Boolean TryParseUInt32(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) { return FormatProvider.Number.TryParseUInt32(s, style, provider, out result); } public static Boolean TryParseUInt64(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) { return FormatProvider.Number.TryParseUInt64(s, style, provider, out result); } public static bool IsPositiveInfinity(string s, IFormatProvider provider) { return FormatProvider.Number.IsPositiveInfinity(s, provider); } public static bool IsNegativeInfinity(string s, IFormatProvider provider) { return FormatProvider.Number.IsNegativeInfinity(s, provider); } public static bool IsNaNSymbol(string s, IFormatProvider provider) { return FormatProvider.Number.IsNaNSymbol(s, provider); } #endregion } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Data; using System.Collections; using System.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Collections.Generic; using Alachisoft.NCache.Config; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Management; using Alachisoft.NCache.ServiceControl; using Alachisoft.NCache.Common; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Common.Enum; using System.Net; using Alachisoft.NCache.Config.Dom; using System.Diagnostics; using Alachisoft.NCache.Common.Net; using System.Threading; using Alachisoft.NCache.Common.Configuration; using Alachisoft.NCache.Tools.Common; using System.Text; using System.IO; using System.IO.Compression; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Management.ServiceControl; namespace Alachisoft.NCache.Tools.RemoveQueryIndex { class Application { [STAThread] static void Main(string[] args) { try { RemoveQueryIndexTool.Run(args); } catch (Exception e) { Console.WriteLine(e); } } } /// <summary> /// Summary description for ConfigureQueryIndexTool. /// </summary> /// public class RemoveQueryIndexParam : Alachisoft.NCache.Tools.Common.CommandLineParamsBase { private string _asmPath = string.Empty; private string _class = string.Empty; private string _attributes = string.Empty; private string _cacheId = string.Empty; private string _server = string.Empty; private int _port = -1; public RemoveQueryIndexParam() { } [ArgumentAttribute("", "")] public string CacheId { get { return _cacheId; } set { _cacheId = value; } } [ArgumentAttribute(@"/c", @"/class")] public string Class { get { return _class; } set { _class = value; } } [ArgumentAttribute(@"/L", @"/attrib-list")] public string Attributes { get { return _attributes; } set { _attributes = value; } } [ArgumentAttribute(@"/s", @"/server")] public string Server { get { return _server; } set { _server = value; } } [ArgumentAttribute(@"/p", @"/port")] public int Port { get { return _port; } set { _port = value; } } } sealed class RemoveQueryIndexTool { static private RemoveQueryIndexParam cParam = new RemoveQueryIndexParam(); static private NCacheRPCService NCache = new NCacheRPCService(""); static private ICacheServer cacheServer; /// <summary> /// Validate all parameters in property string. /// </summary> private static bool ValidateParameters() { // Validating CacheId if (string.IsNullOrEmpty(cParam.CacheId)) { Console.Error.WriteLine("Error: Cache name not specified."); return false; } if (string.IsNullOrEmpty(cParam.Class)) { Console.Error.WriteLine("Error: Class name not specified."); return false; } AssemblyUsage.PrintLogo(cParam.IsLogo); return true; } ////<summary> ////Log an event in event viewer. ////</summary> private static void LogEvent(string msg) { EventLogEntryType type = EventLogEntryType.Error; using (EventLog ncLog = new EventLog("Application")) { ncLog.Source = "NCache:RemoveQueryIndex Tool"; ncLog.WriteEntry(msg, type); } } /// <summary> /// The main entry point for the tool. /// </summary>ju static public void Run(string[] args) { System.Reflection.Assembly asm = null; Alachisoft.NCache.Config.Dom.Class[] queryClasses = null; string failedNodes = string.Empty; bool sucessful = false; string serverName = string.Empty; try { object param = new RemoveQueryIndexParam(); CommandLineArgumentParser.CommandLineParser(ref param, args); cParam = (RemoveQueryIndexParam)param; if (cParam.IsUsage) { AssemblyUsage.PrintLogo(cParam.IsLogo); AssemblyUsage.PrintUsage(); return; } if (!ValidateParameters()) return; if (cParam.Port == -1) NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort; if (cParam.Server != null && cParam.Server != string.Empty) { NCache.ServerName = cParam.Server; } if (cParam.Port != -1) { NCache.Port = cParam.Port; } cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer != null) { Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(cParam.CacheId); serverName = cacheServer.GetClusterIP(); if (cacheServer.IsRunning(cParam.CacheId)) throw new Exception(cParam.CacheId + " is Running on " + serverName + "Stop the cache first."); if (serverConfig == null) throw new Exception("Specified cache is not registered on given server."); Console.WriteLine("Removing query indexes on node '{0}' from cache '{1}'.", serverName, cParam.CacheId); if (serverConfig.CacheSettings.QueryIndices != null) { if (serverConfig.CacheSettings.QueryIndices.Classes != null) { queryClasses = serverConfig.CacheSettings.QueryIndices.Classes; } else return; if (queryClasses != null) { serverConfig.CacheSettings.QueryIndices.Classes = GetSourceClass(GetClass(queryClasses)); if (serverConfig.CacheSettings.QueryIndices.Classes != null) { for (int i = 0; i < serverConfig.CacheSettings.QueryIndices.Classes.Length; i++) { if (serverConfig.CacheSettings.QueryIndices.Classes[i].AttributesTable.Count < 1) serverConfig.CacheSettings.QueryIndices.Classes[i] = null; } bool NoClasses = true; foreach (Class cls in serverConfig.CacheSettings.QueryIndices.Classes) { if (cls != null) { NoClasses = false; break; } } if (NoClasses) serverConfig.CacheSettings.QueryIndices = null; } else { } } } else { throw new Exception("No such Query Index class found. "); return; } if (serverConfig.CacheSettings.CacheType == "clustered-cache") { foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes()) { NCache.ServerName = node.IpAddress.ToString(); try { cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer.IsRunning(cParam.CacheId)) throw new Exception(cParam.CacheId + " is Running on " + serverName + "Stop the cache first."); cacheServer.RegisterCache(cParam.CacheId, serverConfig, "", true, cParam.IsHotApply); } catch (Exception ex) { Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message); failedNodes = failedNodes + "/n" + node.IpAddress.ToString(); LogEvent(ex.Message); sucessful = false; } finally { cacheServer.Dispose(); } } } else { try { cacheServer.RegisterCache(cParam.CacheId, serverConfig, "", true, cParam.IsHotApply); } catch (Exception ex) { Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message); LogEvent(ex.Message); sucessful = false; } finally { cacheServer.Dispose(); } } } sucessful = true; } catch (Exception e) { Console.Error.WriteLine("Failed to Remove Query Index on node '{0}'. ", serverName); Console.Error.WriteLine("Error : {0}", e.Message); LogEvent(e.Message); sucessful = false; } finally { NCache.Dispose(); if (sucessful && !cParam.IsUsage) { Console.WriteLine("Query indexes successfully removed."); } } } static public Hashtable GetAttributes(Hashtable attrib) { string[] str = cParam.Attributes.Split(new char[] { '$' }); if (attrib.Count != 0 && attrib != null) { foreach (string st in str) { if (attrib.Contains(st)) attrib.Remove(st); } } return attrib; } static public Attrib[] GetClassAttributes(Hashtable attrib) { Attrib[] a = new Attrib[attrib.Count]; IDictionaryEnumerator enu = attrib.GetEnumerator(); int index = 0; Attrib attribValue=new Attrib(); while (enu.MoveNext()) { a[index] = new Attrib(); attribValue=(Attrib)enu.Value; a[index].Name = (string)attribValue.Name; a[index].ID = (string)attribValue.ID; a[index].Type = (string)attribValue.Type; index++; } return a; } static public Hashtable GetClass(Alachisoft.NCache.Config.Dom.Class[] cl) { Hashtable hash = new Hashtable(); Hashtable att = new Hashtable(); Alachisoft.NCache.Config.Dom.Class c = new Alachisoft.NCache.Config.Dom.Class(); if (cl != null) { hash = ClassToHashtable(cl); } Class existingClass = null; if (cParam.Attributes == null || cParam.Attributes == string.Empty) { if (hash.Contains(cParam.Class)) { hash.Remove(cParam.Class); } else { throw new Exception("No query index found against class " + cParam.Class + "."); } } else if (cParam.Attributes != null && cParam.Attributes != string.Empty) { if (hash.Contains(cParam.Class)) { existingClass = (Class)hash[cParam.Class]; att = AttribToHashtable(existingClass.Attributes); } existingClass.Attributes = GetClassAttributes(GetAttributes(att)); hash[existingClass.Name] = existingClass; } return hash; } static public Class[] GetSourceClass(Hashtable pParams) { Class[] param = new Class[pParams.Count]; IDictionaryEnumerator enu = pParams.GetEnumerator(); int index = 0; while (enu.MoveNext()) { param[index] = new Class(); param[index].Name = (string)enu.Key; param[index] = (Class)enu.Value; index++; } return param; } static public bool ValidateClass(string cl, ArrayList cc) { foreach (Class c in cc) { if (c.Name.Equals(cl)) return false; } return true; } static public Hashtable ClassToHashtable(Alachisoft.NCache.Config.Dom.Class[] cl) { Hashtable hash = new Hashtable(); for (int i = 0; i < cl.Length; i++) { hash.Add(cl[i].Name, cl[i]); } return hash; } static public Hashtable AttribToHashtable(Alachisoft.NCache.Config.Dom.Attrib[] cl) { Hashtable hash = new Hashtable(); for (int i = 0; i < cl.Length; i++) { hash.Add(cl[i].Name, cl[i]); } return hash; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Baseline; using Marten.Generation; using Marten.Services; using Marten.Util; namespace Marten.Schema { public class DocumentSchemaObjects : IDocumentSchemaObjects { public static DocumentSchemaObjects For<T>() { return new DocumentSchemaObjects(DocumentMapping.For<T>()); } private readonly DocumentMapping _mapping; private bool _hasCheckedSchema; private readonly object _lock = new object(); public DocumentSchemaObjects(DocumentMapping mapping) { _mapping = mapping; } public readonly IList<Type> DependentTypes = new List<Type>(); public readonly IList<string> DependentScripts = new List<string>(); public Type DocumentType => _mapping.DocumentType; public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer) { var table = StorageTable(); var rules = schema.StoreOptions.DdlRules; table.Write(rules, writer); writer.WriteLine(); writer.WriteLine(); var function = new UpsertFunction(_mapping); function.WriteFunctionSql(rules, writer); _mapping.ForeignKeys.Each(x => { writer.WriteLine(); writer.WriteLine((string) x.ToDDL()); }); _mapping.Indexes.Each(x => { writer.WriteLine(); writer.WriteLine(x.ToDDL()); }); DependentScripts.Each(script => { writer.WriteLine(); writer.WriteLine(); writer.WriteSql(_mapping.DatabaseSchemaName, script); }); writer.WriteLine(); writer.WriteLine(); var template = _mapping.DdlTemplate.IsNotEmpty() ? rules.Templates[_mapping.DdlTemplate.ToLower()] : rules.Templates["default"]; table.WriteTemplate(template, writer); var body = function.ToBody(rules); body.WriteTemplate(template, writer); writer.WriteLine(); writer.WriteLine(); } public void RemoveSchemaObjects(IManagedConnection connection) { _hasCheckedSchema = false; connection.Execute($"DROP TABLE IF EXISTS {_mapping.Table} CASCADE;"); RemoveUpsertFunction(connection); } /// <summary> /// Only for testing scenarios /// </summary> /// <param name="connection"></param> public void RemoveUpsertFunction(IManagedConnection connection) { var dropTargets = DocumentCleaner.DropFunctionSql.ToFormat(_mapping.UpsertFunction.Name, _mapping.UpsertFunction.Schema); var drops = connection.GetStringList(dropTargets); drops.Each(drop => connection.Execute(drop)); } public void ResetSchemaExistenceChecks() { _hasCheckedSchema = false; } private void assertIdentifierLengths(StoreOptions options) { foreach (var index in _mapping.Indexes) { options.AssertValidIdentifier(index.IndexName); } options.AssertValidIdentifier(_mapping.UpsertFunction.Name); options.AssertValidIdentifier(_mapping.Table.Name); } public void GenerateSchemaObjectsIfNecessary(AutoCreate autoCreateSchemaObjectsMode, IDocumentSchema schema, SchemaPatch patch) { if (_hasCheckedSchema) return; assertIdentifierLengths(schema.StoreOptions); DependentTypes.Each(schema.EnsureStorageExists); var diff = CreateSchemaDiff(schema); if (!diff.HasDifferences()) { _hasCheckedSchema = true; return; } lock (_lock) { if (_hasCheckedSchema) return; buildOrModifySchemaObjects(diff, autoCreateSchemaObjectsMode, schema, patch); _hasCheckedSchema = true; } } public SchemaDiff CreateSchemaDiff(IDocumentSchema schema) { var objects = schema.DbObjects.FindSchemaObjects(_mapping); return new SchemaDiff(objects, _mapping, schema.StoreOptions.DdlRules); } private void runDependentScripts(SchemaPatch runner) { DependentScripts.Each(script => { var sql = SchemaBuilder.GetSqlScript(_mapping.DatabaseSchemaName, script); runner.Updates.Apply(this, sql); }); } private void buildOrModifySchemaObjects(SchemaDiff diff, AutoCreate autoCreateSchemaObjectsMode, IDocumentSchema schema, SchemaPatch runner) { if (autoCreateSchemaObjectsMode == AutoCreate.None) { var className = nameof(StoreOptions); var propName = nameof(StoreOptions.AutoCreateSchemaObjects); string message = $"No document storage exists for type {_mapping.DocumentType.FullName} and cannot be created dynamically unless the {className}.{propName} is greater than \"None\". See http://jasperfx.github.io/marten/documentation/documents/ for more information"; throw new InvalidOperationException(message); } if (diff.AllMissing) { rebuildAll(schema, runner); return; } if (autoCreateSchemaObjectsMode == AutoCreate.CreateOnly) { throw new InvalidOperationException( $"The table for document type {_mapping.DocumentType.FullName} is different than the current schema table, but AutoCreateSchemaObjects = '{nameof(AutoCreate.CreateOnly)}'"); } if (diff.CanPatch()) { diff.CreatePatch(schema.StoreOptions, runner); } else if (autoCreateSchemaObjectsMode == AutoCreate.All) { rebuildAll(schema, runner); } else { throw new InvalidOperationException( $"The table for document type {_mapping.DocumentType.FullName} is different than the current schema table, but AutoCreateSchemaObjects = '{autoCreateSchemaObjectsMode}'"); } runDependentScripts(runner); } private void rebuildAll(IDocumentSchema schema, SchemaPatch runner) { rebuildTableAndUpsertFunction(schema, runner); runDependentScripts(runner); } private void rebuildTableAndUpsertFunction(IDocumentSchema schema, SchemaPatch runner) { assertIdentifierLengths(schema.StoreOptions); var writer = new StringWriter(); WriteSchemaObjects(schema, writer); var sql = writer.ToString(); runner.Updates.Apply(this, sql); } public TableDefinition StorageTable() { var pgIdType = TypeMappings.GetPgType(_mapping.IdMember.GetMemberType()); var table = new TableDefinition(_mapping.Table, new TableColumn("id", pgIdType)); table.Columns.Add(new TableColumn("data", "jsonb") { Directive = "NOT NULL" }); table.Columns.Add(new TableColumn(DocumentMapping.LastModifiedColumn, "timestamp with time zone") { Directive = "DEFAULT transaction_timestamp()" }); table.Columns.Add(new TableColumn(DocumentMapping.VersionColumn, "uuid") { Directive = "NOT NULL default(md5(random()::text || clock_timestamp()::text)::uuid)" }); table.Columns.Add(new TableColumn(DocumentMapping.DotNetTypeColumn, "varchar")); _mapping.DuplicatedFields.Select(x => x.ToColumn()).Each(x => table.Columns.Add(x)); if (_mapping.IsHierarchy()) { table.Columns.Add(new TableColumn(DocumentMapping.DocumentTypeColumn, "varchar") { Directive = $"DEFAULT '{_mapping.AliasFor(_mapping.DocumentType)}'" }); } if (_mapping.DeleteStyle == DeleteStyle.SoftDelete) { table.Columns.Add(new TableColumn(DocumentMapping.DeletedColumn, "boolean") { Directive = "DEFAULT FALSE" }); table.Columns.Add(new TableColumn(DocumentMapping.DeletedAtColumn, "timestamp with time zone") { Directive = "NULL" }); } return table; } public void WritePatch(IDocumentSchema schema, SchemaPatch patch) { assertIdentifierLengths(schema.StoreOptions); var diff = CreateSchemaDiff(schema); if (!diff.HasDifferences()) return; if (diff.AllMissing) { patch.Rollbacks.Drop(this, _mapping.Table); WriteSchemaObjects(schema, patch.UpWriter); } else if (diff.CanPatch()) { diff.CreatePatch(schema.StoreOptions, patch); } } public string Name => _mapping.Alias.ToLowerInvariant(); public override string ToString() { return "Storage Table and Upsert Function for " + _mapping.DocumentType.FullName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; using static System.Tests.Utf8TestUtilities; namespace System.Tests { public partial class Utf8ExtensionsTests { [Fact] public unsafe void AsBytes_FromSpan_Default() { // First, a default span should become a default span. Assert.True(default(ReadOnlySpan<byte>) == new ReadOnlySpan<Char8>().AsBytes()); // Next, an empty but non-default span should become an empty but non-default span. Assert.True(new ReadOnlySpan<byte>((void*)0x12345, 0) == new ReadOnlySpan<Char8>((void*)0x12345, 0).AsBytes()); // Finally, a span wrapping data should become a span wrapping that same data. Utf8String theString = u8("Hello"); Assert.True(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in theString.GetPinnableReference()), 5) == (theString.AsMemory().Span).AsBytes()); } [Fact] public void AsBytes_FromUtf8String() { Assert.True(default(ReadOnlySpan<byte>) == ((Utf8String)null).AsBytes()); Utf8String theString = u8("Hello"); Assert.True(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in theString.GetPinnableReference()), 5) == theString.AsBytes()); } [Fact] public void AsBytes_FromUtf8String_WithStart() { Assert.True(default(ReadOnlySpan<byte>) == ((Utf8String)null).AsBytes(0)); Assert.True(u8("Hello").AsBytes(5).IsEmpty); SpanAssert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l', (byte)'o' }, u8("Hello").AsBytes(1)); } [Fact] public void AsBytes_FromUtf8String_WithStart_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsBytes(1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsBytes(-1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsBytes(6)); } [Fact] public void AsBytes_FromUtf8String_WithStartAndLength() { Assert.True(default(ReadOnlySpan<byte>) == ((Utf8String)null).AsBytes(0, 0)); Assert.True(u8("Hello").AsBytes(5, 0).IsEmpty); SpanAssert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l' }, u8("Hello").AsBytes(1, 3)); } [Fact] public void AsBytes_FromUtf8String_WithStartAndLength_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsBytes(0, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsBytes(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsBytes(5, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsBytes(4, -2)); } [Fact] public void AsMemory_FromUtf8String() { Assert.True(default(ReadOnlyMemory<Char8>).Equals(((Utf8String)null).AsMemory())); Utf8String theString = u8("Hello"); Assert.True(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<byte, Char8>(ref Unsafe.AsRef(in theString.GetPinnableReference())), 5) == theString.AsMemory().Span); } [Fact] public void AsMemory_FromUtf8String_WithStart() { Assert.True(default(ReadOnlyMemory<Char8>).Equals(((Utf8String)null).AsMemory(0))); Assert.True(u8("Hello").AsMemory(5).IsEmpty); SpanAssert.Equal(new Char8[] { (Char8)'e', (Char8)'l', (Char8)'l', (Char8)'o' }, u8("Hello").AsMemory(1).Span); } [Fact] public void AsMemory_FromUtf8String_WithStart_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemory(1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemory(-1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemory(6)); } [Fact] public void AsMemory_FromUtf8String_WithStartAndLength() { Assert.True(default(ReadOnlyMemory<Char8>).Equals(((Utf8String)null).AsMemory(0, 0))); Assert.True(u8("Hello").AsMemory(5, 0).IsEmpty); SpanAssert.Equal(new Char8[] { (Char8)'e', (Char8)'l', (Char8)'l' }, u8("Hello").AsMemory(1, 3).Span); } [Fact] public void AsMemory_FromUtf8String_WithStartAndLength_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemory(0, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemory(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemory(5, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemory(4, -2)); } [Fact] public void AsMemoryBytes_FromUtf8String() { Assert.True(default(ReadOnlyMemory<byte>).Equals(((Utf8String)null).AsMemoryBytes())); Utf8String theString = u8("Hello"); Assert.True(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in theString.GetPinnableReference()), 5) == theString.AsMemoryBytes().Span); } [Fact] public void AsMemoryBytes_FromUtf8String_WithStart() { Assert.True(default(ReadOnlyMemory<byte>).Equals(((Utf8String)null).AsMemoryBytes(0))); Assert.True(u8("Hello").AsMemoryBytes(5).IsEmpty); SpanAssert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l', (byte)'o' }, u8("Hello").AsMemoryBytes(1).Span); } [Fact] public void AsMemoryBytes_FromUtf8String_WithStart_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemoryBytes(1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemoryBytes(-1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemoryBytes(6)); } [Fact] public void AsMemoryBytes_FromUtf8String_WithStartAndLength() { Assert.True(default(ReadOnlyMemory<byte>).Equals(((Utf8String)null).AsMemoryBytes(0, 0))); Assert.True(u8("Hello").AsMemoryBytes(5, 0).IsEmpty); SpanAssert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l' }, u8("Hello").AsMemoryBytes(1, 3).Span); } [Fact] public void AsMemoryBytes_FromUtf8String_WithStartAndLength_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemoryBytes(0, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsMemoryBytes(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemoryBytes(5, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsMemoryBytes(4, -2)); } [Fact] public void AsSpan_FromUtf8String() { Assert.True(((Utf8String)null).AsSpan().Bytes == default); // referential equality check Utf8String theString = u8("Hello"); Assert.True(Unsafe.AreSame(ref Unsafe.AsRef(in theString.GetPinnableReference()), ref Unsafe.AsRef(in theString.AsSpan().GetPinnableReference()))); Assert.Equal(5, theString.AsSpan().Length); } [Fact] public void AsSpan_FromUtf8String_WithStart() { Assert.True(((Utf8String)null).AsSpan(0).Bytes == default); // referential equality check Assert.True(u8("Hello").AsSpan(5).IsEmpty); Assert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l', (byte)'o' }, u8("Hello").AsSpan(1).Bytes.ToArray()); } [Fact] public void AsSpan_FromUtf8String_WithStart_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsSpan(1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsSpan(-1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsSpan(6)); } [Fact] public void AsSpan_FromUtf8String_WithStartAndLength() { Assert.True(((Utf8String)null).AsSpan(0, 0).Bytes == default); // referential equality check Assert.True(u8("Hello").AsSpan(5, 0).IsEmpty); Assert.Equal(new byte[] { (byte)'e', (byte)'l', (byte)'l' }, u8("Hello").AsSpan(1, 3).Bytes.ToArray()); } [Fact] public void AsSpan_FromUtf8String_WithStartAndLength_ArgOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsSpan(0, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ((Utf8String)null).AsSpan(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsSpan(5, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => u8("Hello").AsSpan(4, -2)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ShiftRightLogical128BitLaneInt161() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.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 (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int RetElementCount = VectorSize / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector128<Int16> _clsVar; private Vector128<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftRightLogical128BitLane( Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 7 ? result[i] != 0 : result[i] != 2048)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<Int16>(Vector128<Int16><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Threading; using System.Collections.Generic; using Sensus.Context; using Sensus.UI.Inputs; using Xamarin.Forms; namespace Sensus.UI { public class PromptForInputsPage : ContentPage { public enum Result { NavigateBackward, NavigateForward, Cancel } private bool _canNavigateBack; private Action<Result> _finishedCallback; private int _displayedInputCount; public int DisplayedInputCount { get { return _displayedInputCount; } } public PromptForInputsPage(InputGroup inputGroup, int stepNumber, int totalSteps, bool canNavigateBack, bool showCancelButton, string nextButtonTextOverride, CancellationToken? cancellationToken, string cancelConfirmation, string incompleteSubmissionConfirmation, string submitConfirmation, bool displayProgress, Action<Result> finishedCallback) { _canNavigateBack = canNavigateBack; _finishedCallback = finishedCallback; _displayedInputCount = 0; StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(10, 20, 10, 20), Children = { new Label { Text = inputGroup.Name, FontSize = 20, HorizontalOptions = LayoutOptions.CenterAndExpand } } }; if (displayProgress) { float progress = (stepNumber - 1) / (float)totalSteps; contentLayout.Children.Add(new Label { Text = "Progress: " + Math.Round(100 * progress) + "%", FontSize = 15, HorizontalOptions = LayoutOptions.CenterAndExpand }); contentLayout.Children.Add(new ProgressBar { Progress = progress, HorizontalOptions = LayoutOptions.FillAndExpand }); } // indicate required fields if (inputGroup.Inputs.Any(input => input.Display && input.Required)) { contentLayout.Children.Add(new Label { Text = "Required fields are indicated with *", FontSize = 15, TextColor = Color.Red, HorizontalOptions = LayoutOptions.Start }); } // add inputs to the page List<Input> displayedInputs = new List<Input>(); int viewNumber = 1; int inputSeparatorHeight = 10; foreach (Input input in inputGroup.Inputs) { if (input.Display) { View inputView = input.GetView(viewNumber); if (inputView != null) { // frame all enabled inputs that request a frame if (input.Enabled && input.Frame) { inputView = new Frame { Content = inputView, OutlineColor = Color.Accent, VerticalOptions = LayoutOptions.Start, HasShadow = true, Padding = new Thickness(10) }; } // add some vertical separation between inputs if (_displayedInputCount > 0) { contentLayout.Children.Add(new BoxView { Color = Color.Transparent, HeightRequest = inputSeparatorHeight }); } contentLayout.Children.Add(inputView); displayedInputs.Add(input); if (input.DisplayNumber) { ++viewNumber; } ++_displayedInputCount; } } } // add final separator if we displayed any inputs if (_displayedInputCount > 0) { contentLayout.Children.Add(new BoxView { Color = Color.Transparent, HeightRequest = inputSeparatorHeight }); } StackLayout navigationStack = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand, }; #region previous/next buttons StackLayout previousNextStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand }; // add a prevous button if we're allowed to navigate back if (_canNavigateBack) { Button previousButton = new Button { HorizontalOptions = LayoutOptions.FillAndExpand, FontSize = 20, Text = "Previous" }; previousButton.Clicked += (o, e) => { _finishedCallback(Result.NavigateBackward); }; previousNextStack.Children.Add(previousButton); } Button nextButton = new Button { HorizontalOptions = LayoutOptions.FillAndExpand, FontSize = 20, Text = stepNumber < totalSteps ? "Next" : "Submit" #if UI_TESTING // set style id so that we can retrieve the button when UI testing , StyleId = "NextButton" #endif }; if (nextButtonTextOverride != null) { nextButton.Text = nextButtonTextOverride; } nextButton.Clicked += async (o, e) => { if (!inputGroup.Valid && inputGroup.ForceValidInputs) { await DisplayAlert("Mandatory", "You must provide values for all required fields before proceeding.", "Back"); } else { string confirmationMessage = ""; if (!string.IsNullOrWhiteSpace(incompleteSubmissionConfirmation) && !inputGroup.Valid) { confirmationMessage += incompleteSubmissionConfirmation; } else if (nextButton.Text == "Submit" && !string.IsNullOrWhiteSpace(submitConfirmation)) { confirmationMessage += submitConfirmation; } if (string.IsNullOrWhiteSpace(confirmationMessage) || await DisplayAlert("Confirm", confirmationMessage, "Yes", "No")) { _finishedCallback(Result.NavigateForward); } } }; previousNextStack.Children.Add(nextButton); navigationStack.Children.Add(previousNextStack); #endregion #region cancel button and token if (showCancelButton) { Button cancelButton = new Button { HorizontalOptions = LayoutOptions.FillAndExpand, FontSize = 20, Text = "Cancel" }; // separate cancel button from previous/next with a thin visible separator navigationStack.Children.Add(new BoxView { Color = Color.Gray, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 0.5 }); navigationStack.Children.Add(cancelButton); cancelButton.Clicked += async (o, e) => { if (string.IsNullOrWhiteSpace(cancelConfirmation) || await DisplayAlert("Confirm", cancelConfirmation, "Yes", "No")) { _finishedCallback(Result.Cancel); } }; } contentLayout.Children.Add(navigationStack); if (cancellationToken.HasValue) { cancellationToken.Value.Register(() => { // it is possible for the token to be canceled from a thread other than the UI thread. the finished callback will do // things with the UI, so ensure that the finished callback is run on the UI thread. SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() => { SensusServiceHelper.Get().Logger.Log("Cancellation token has been cancelled.", LoggingLevel.Normal, GetType()); _finishedCallback(Result.Cancel); }); }); } #endregion Appearing += (o, e) => { // the page has appeared so mark all inputs as viewed foreach (Input input in displayedInputs) { input.Viewed = true; } }; Content = new ScrollView { Content = contentLayout }; } /// <summary> /// Disable the device's back button. The user must complete the form. /// </summary> /// <returns>True</returns> protected override bool OnBackButtonPressed() { if (_canNavigateBack) { _finishedCallback(Result.NavigateBackward); } 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.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Transactions; namespace System.Data.Common { internal static partial class ADP { // The class ADP defines the exceptions that are specific to the Adapters. // 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. // 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. internal static Exception ExceptionWithStackTrace(Exception e) { try { throw e; } catch (Exception caught) { return caught; } } // // COM+ exceptions // internal static IndexOutOfRangeException IndexOutOfRange(int value) { IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture)); return e; } internal static IndexOutOfRangeException IndexOutOfRange() { IndexOutOfRangeException e = new IndexOutOfRangeException(); return e; } internal static TimeoutException TimeoutException(string error) { TimeoutException e = new TimeoutException(error); return e; } internal static InvalidOperationException InvalidOperation(string error, Exception inner) { InvalidOperationException e = new InvalidOperationException(error, inner); return e; } internal static OverflowException Overflow(string error) { return Overflow(error, null); } internal static OverflowException Overflow(string error, Exception inner) { OverflowException e = new OverflowException(error, inner); return e; } internal static TypeLoadException TypeLoad(string error) { TypeLoadException e = new TypeLoadException(error); TraceExceptionAsReturnValue(e); return e; } internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) { PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); return e; } internal static InvalidCastException InvalidCast() { InvalidCastException e = new InvalidCastException(); return e; } internal static IOException IO(string error) { IOException e = new IOException(error); return e; } internal static IOException IO(string error, Exception inner) { IOException e = new IOException(error, inner); return e; } internal static ObjectDisposedException ObjectDisposed(object instance) { ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); return e; } internal static Exception DataTableDoesNotExist(string collectionName) { return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName)); } internal static InvalidOperationException MethodCalledTwice(string method) { InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method)); return e; } // IDbCommand.CommandType internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value) { #if DEBUG switch (value) { case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: Debug.Assert(false, "valid CommandType " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(CommandType), (int)value); } // IDbConnection.BeginTransaction, OleDbTransaction.Begin internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) { #if DEBUG switch (value) { case IsolationLevel.Unspecified: case IsolationLevel.Chaos: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: Debug.Fail("valid IsolationLevel " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); } // IDataParameter.Direction internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) { #if DEBUG switch (value) { case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: Debug.Assert(false, "valid ParameterDirection " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); } internal static Exception TooManyRestrictions(string collectionName) { return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName)); } // IDbCommand.UpdateRowSource internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) { #if DEBUG switch (value) { case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); } // // DbConnectionOptions, DataAccess // internal static ArgumentException InvalidMinMaxPoolSizeValues() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues)); } // // DbConnection // internal static InvalidOperationException NoConnectionString() { return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString)); } internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "") { return NotImplemented.ByDesignWithMessage(methodName); } internal static Exception QueryFailed(string collectionName, Exception e) { return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e); } // // : DbConnectionOptions, DataAccess, SqlClient // internal static Exception InvalidConnectionOptionValueLength(string key, int limit) { return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit)); } internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) { return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); } // // DbConnectionPool and related // internal static Exception PooledOpenTimeout() { return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout)); } internal static Exception NonPooledOpenTimeout() { return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout)); } // // DbProviderException // internal static InvalidOperationException TransactionConnectionMismatch() { return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch)); } internal static InvalidOperationException TransactionRequired(string method) { return Provider(SR.GetString(SR.ADP_TransactionRequired, method)); } internal static Exception CommandTextRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method)); } internal static Exception NoColumns() { return Argument(SR.GetString(SR.MDF_NoColumns)); } internal static InvalidOperationException ConnectionRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method)); } internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); } internal static Exception OpenReaderExists() { return OpenReaderExists(null); } internal static Exception OpenReaderExists(Exception e) { return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e); } // // DbDataReader // internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) { return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); } internal static Exception InvalidXml() { return Argument(SR.GetString(SR.MDF_InvalidXml)); } internal static Exception NegativeParameter(string parameterName) { return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName)); } internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName) { return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName)); } // // SqlMetaData, SqlTypes, SqlClient // internal static Exception InvalidMetaDataValue() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue)); } internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) { return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName) { return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName)); } internal static Exception CollectionNameIsNotUnique(string collectionName) { return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName)); } // // : IDbCommand // internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") { return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); } internal static Exception UninitializedParameterSize(int index, Type dataType) { return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); } internal static Exception UnableToBuildCollection(string collectionName) { return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName)); } internal static Exception PrepareParameterType(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name)); } internal static Exception UndefinedCollection(string collectionName) { return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName)); } internal static Exception UnsupportedVersion(string collectionName) { return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName)); } internal static Exception AmbigousCollectionName(string collectionName) { return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName)); } internal static Exception PrepareParameterSize(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name)); } internal static Exception PrepareParameterScale(DbCommand cmd, string type) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type)); } internal static Exception MissingDataSourceInformationColumn() { return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn)); } internal static Exception IncorrectNumberOfDataSourceInformationRows() { return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows)); } internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) { return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); } // // : ConnectionUtil // internal static Exception ClosedConnectionError() { return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError)); } internal static Exception ConnectionAlreadyOpen(ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); } internal static Exception TransactionPresent() { return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent)); } internal static Exception LocalTransactionPresent() { return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent)); } internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); } internal static Exception EmptyDatabaseName() { return Argument(SR.GetString(SR.ADP_EmptyDatabaseName)); } internal enum ConnectionError { BeginGetConnectionReturnsNull, GetConnectionReturnsNull, ConnectionOptionsMissing, CouldNotSwitchToClosedPreviouslyOpenedState, } internal static Exception MissingRestrictionColumn() { return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn)); } internal static Exception InternalConnectionError(ConnectionError internalError) { return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError)); } internal static Exception InvalidConnectRetryCountValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue)); } internal static Exception MissingRestrictionRow() { return Argument(SR.GetString(SR.MDF_MissingRestrictionRow)); } internal static Exception InvalidConnectRetryIntervalValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue)); } // // : DbDataReader // internal static InvalidOperationException AsyncOperationPending() { return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation)); } // // : Stream // internal static IOException ErrorReadingFromStream(Exception internalException) { return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException); } internal static ArgumentException InvalidDataType(TypeCode typecode) { return Argument(SR.GetString(SR.ADP_InvalidDataType, typecode.ToString())); } internal static ArgumentException UnknownDataType(Type dataType) { return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName)); } internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype) { return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); } internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) { return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); } internal static ArgumentException InvalidOffsetValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException InvalidSizeValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException ParameterValueOutOfRange(decimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); } internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString())); } internal static ArgumentException VersionDoesNotSupportDataType(string typeName) { return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName)); } internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Debug.Assert(null != value, "null value on conversion failure"); Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); } else if (inner is FormatException) { e = new FormatException(message, inner); } else if (inner is InvalidCastException) { e = new InvalidCastException(message, inner); } else if (inner is OverflowException) { e = new OverflowException(message, inner); } else { e = inner; } return e; } // // : IDataParameterCollection // internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection) { return CollectionIndexInt32(index, collection.GetType(), collection.Count); } internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType) { return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); } internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType) { return CollectionNullValue(parameter, collection.GetType(), parameterType); } internal static Exception UndefinedPopulationMechanism(string populationMechanism) { throw new NotImplementedException(); } internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue) { return CollectionInvalidType(collection.GetType(), parameterType, invalidValue); } // // : IDbTransaction // internal static Exception ParallelTransactionsNotSupported(DbConnection obj) { return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); } internal static Exception TransactionZombied(DbTransaction obj) { return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name)); } // global constant strings internal const string Parameter = "Parameter"; internal const string ParameterName = "ParameterName"; internal const string ParameterSetPosition = "set_Position"; internal const int DefaultCommandTimeout = 30; internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections // security issue, don't rely upon public static readonly values internal static readonly string StrEmpty = ""; // String.Empty internal const int CharSize = sizeof(char); internal static Delegate FindBuilder(MulticastDelegate mcd) { if (null != mcd) { foreach (Delegate del in mcd.GetInvocationList()) { if (del.Target is DbCommandBuilder) return del; } } return null; } internal static void TimerCurrent(out long ticks) { ticks = DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerCurrent() { return DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerFromSeconds(int seconds) { long result = checked((long)seconds * TimeSpan.TicksPerSecond); return result; } internal static long TimerFromMilliseconds(long milliseconds) { long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); return result; } internal static bool TimerHasExpired(long timerExpire) { bool result = TimerCurrent() > timerExpire; return result; } internal static long TimerRemaining(long timerExpire) { long timerNow = TimerCurrent(); long result = checked(timerExpire - timerNow); return result; } internal static long TimerRemainingMilliseconds(long timerExpire) { long result = TimerToMilliseconds(TimerRemaining(timerExpire)); return result; } internal static long TimerRemainingSeconds(long timerExpire) { long result = TimerToSeconds(TimerRemaining(timerExpire)); return result; } internal static long TimerToMilliseconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerMillisecond; return result; } private static long TimerToSeconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerSecond; return result; } internal static string MachineName() { return Environment.MachineName; } internal static Transaction GetCurrentTransaction() { return Transaction.Current; } internal static bool IsDirection(DbParameter value, ParameterDirection condition) { #if DEBUG IsDirectionValid(condition); #endif return (condition == (condition & value.Direction)); } #if DEBUG private static void IsDirectionValid(ParameterDirection value) { switch (value) { // @perfnote: Enum.IsDefined case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: break; default: throw ADP.InvalidParameterDirection(value); } } #endif internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) { if ((value == null) || (value == DBNull.Value)) { isNull = true; isSqlType = false; } else { INullable nullable = (value as INullable); if (nullable != null) { isNull = nullable.IsNull; // Duplicated from DataStorage.cs // For back-compat, SqlXml is not in this list isSqlType = ((value is SqlBinary) || (value is SqlBoolean) || (value is SqlByte) || (value is SqlBytes) || (value is SqlChars) || (value is SqlDateTime) || (value is SqlDecimal) || (value is SqlDouble) || (value is SqlGuid) || (value is SqlInt16) || (value is SqlInt32) || (value is SqlInt64) || (value is SqlMoney) || (value is SqlSingle) || (value is SqlString)); } else { isNull = false; isSqlType = false; } } } private static Version s_systemDataVersion; internal static Version GetAssemblyVersion() { // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time if (s_systemDataVersion == null) { s_systemDataVersion = new Version(ThisAssembly.InformationalVersion); } return s_systemDataVersion; } internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint), SR.GetString(SR.AZURESQL_GermanEndpoint), SR.GetString(SR.AZURESQL_UsGovEndpoint), SR.GetString(SR.AZURESQL_ChinaEndpoint)}; // This method assumes dataSource parameter is in TCP connection string format. internal static bool IsAzureSqlServerEndpoint(string dataSource) { // remove server port int i = dataSource.LastIndexOf(','); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // check for the instance name i = dataSource.LastIndexOf('\\'); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // trim redundant whitespace dataSource = dataSource.Trim(); // check if servername end with any azure endpoints for (i = 0; i < AzureSqlServerEndpoints.Length; i++) { if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) { #if DEBUG switch (value) { case DataRowVersion.Default: case DataRowVersion.Current: case DataRowVersion.Original: case DataRowVersion.Proposed: Debug.Fail($"Invalid DataRowVersion {value}"); break; } #endif return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); } internal static ArgumentException SingleValuedProperty(string propertyName, string value) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidPrefixSuffix() { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) { Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString()); return InvalidEnumerationValue(typeof(CommandBehavior), (int)value); } internal static void ValidateCommandBehavior(CommandBehavior value) { if (((int)value < 0) || (0x3F < (int)value)) { throw InvalidCommandBehavior(value); } } internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) { return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method); } internal static ArgumentException BadParameterName(string parameterName) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName)); TraceExceptionAsReturnValue(e); return e; } internal static Exception DeriveParametersNotSupported(IDbCommand value) { return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); } internal static Exception NoStoredProcedureExists(string sproc) { return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc)); } // // DbProviderException // internal static InvalidOperationException TransactionCompletedButNotDisposed() { return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed)); } internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value) { return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int)value); } internal static ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method) { return NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method); } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) { ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidArgumentLength(string argumentName, int limit) { return Argument(SR.GetString(SR.ADP_InvalidArgumentLength, argumentName, limit)); } internal static ArgumentException MustBeReadOnly(string argumentName) { return Argument(SR.GetString(SR.ADP_MustBeReadOnly, argumentName)); } internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() { return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential)); } internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() { return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential)); } internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() { return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); } internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() { return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); } internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() { return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); } static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() { return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); } static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() { return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; namespace NUnit.Framework { /// <summary> /// RangeAttribute is used to supply a range of _values to an /// individual parameter of a parameterized test. /// </summary> public class RangeAttribute : ValuesAttribute { #region Ints /// <summary> /// Construct a range of ints using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> public RangeAttribute(int from, int to) : this(from, to, from > to ? -1 : 1) { } /// <summary> /// Construct a range of ints specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(int from, int to, int step) { Guard.ArgumentValid(step > 0 && to >= from || step < 0 && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); int count = (to - from) / step + 1; this.data = new object[count]; int index = 0; for (int val = from; index < count; val += step) this.data[index++] = val; } #endregion #region Unsigned Ints /// <summary> /// Construct a range of unsigned ints using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> [CLSCompliant(false)] public RangeAttribute(uint from, uint to) : this(from, to, 1u) { } /// <summary> /// Construct a range of unsigned ints specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> [CLSCompliant(false)] public RangeAttribute(uint from, uint to, uint step) { Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step"); Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to"); uint count = (to - from) / step + 1; this.data = new object[count]; uint index = 0; for (uint val = from; index < count; val += step) this.data[index++] = val; } #endregion #region Longs /// <summary> /// Construct a range of longs using a default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> public RangeAttribute(long from, long to) : this(from, to, from > to ? -1L : 1L) { } /// <summary> /// Construct a range of longs /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(long from, long to, long step) { Guard.ArgumentValid(step > 0L && to >= from || step < 0L && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); long count = (to - from) / step + 1; this.data = new object[count]; int index = 0; for (long val = from; index < count; val += step) this.data[index++] = val; } #endregion #region Unsigned Longs /// <summary> /// Construct a range of unsigned longs using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> [CLSCompliant(false)] public RangeAttribute(ulong from, ulong to) : this(from, to, 1ul) { } /// <summary> /// Construct a range of unsigned longs specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> [CLSCompliant(false)] public RangeAttribute(ulong from, ulong to, ulong step) { Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step"); Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to"); ulong count = (to - from) / step + 1; this.data = new object[count]; ulong index = 0; for (ulong val = from; index < count; val += step) this.data[index++] = val; } #endregion #region Doubles /// <summary> /// Construct a range of doubles /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(double from, double to, double step) { Guard.ArgumentValid(step > 0.0D && to >= from || step < 0.0D && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); double aStep = Math.Abs(step); double tol = aStep / 1000; int count = (int)(Math.Abs(to - from) / aStep + tol + 1); this.data = new object[count]; int index = 0; for (double val = from; index < count; val += step) this.data[index++] = val; } #endregion #region Floats /// <summary> /// Construct a range of floats /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(float from, float to, float step) { Guard.ArgumentValid(step > 0.0F && to >= from || step < 0.0F && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); float aStep = Math.Abs(step); float tol = aStep / 1000; int count = (int)(Math.Abs(to - from) / aStep + tol + 1); this.data = new object[count]; int index = 0; for (float val = from; index < count; val += step) this.data[index++] = val; } #endregion } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Diagnostics; using System.Net; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Belikov.Common.ThreadProcessing; using Belikov.GenuineChannels.Connection; using Belikov.GenuineChannels.DotNetRemotingLayer; using Belikov.GenuineChannels.Logbook; using Belikov.GenuineChannels.Messaging; using Belikov.GenuineChannels.Parameters; using Belikov.GenuineChannels.Security; using Belikov.GenuineChannels.TransportContext; namespace Belikov.GenuineChannels.Connection { /// <summary> /// Represents a connection to the remote host. /// </summary> internal abstract class GeneralConnection { /// <summary> /// Constructs an instance of the GeneralConnection class. /// </summary> /// <param name="iTransportContext">The Transport Context.</param> public GeneralConnection(ITransportContext iTransportContext) { this.ITransportContext = iTransportContext; this.HostIdAsString = iTransportContext.HostIdentifier; } /// <summary> /// A queue of the messages arranged to be sent through this connection. /// </summary> public MessageContainer MessageContainer; /// <summary> /// The connection id in string format. /// </summary> public string HostIdAsString; /// <summary> /// The remote host. /// </summary> public HostInformation Remote; /// <summary> /// The transport context. /// </summary> public ITransportContext ITransportContext; /// <summary> /// The type of this connection. /// </summary> public GenuineConnectionType GenuineConnectionType; /// <summary> /// To guarantee atomic access to local members. /// </summary> protected object _accessToLocalMembers = new object(); /// <summary> /// Connection Manager must obtain the lock for this object in order to modify data /// related to reconnection stuff. /// </summary> public object ReconnectionLock = new object(); /// <summary> /// A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last sending of a message to the remote host. /// </summary> public int LastTimeContentWasSent { get { lock (_accessToLocalMembers) return _lastTimeContentWasSent; } set { lock (_accessToLocalMembers) _lastTimeContentWasSent = value; } } private int _lastTimeContentWasSent = GenuineUtility.TickCount; #region -- Disposing ----------------------------------------------------------------------- /// <summary> /// Indicates whether this instance was disposed. /// </summary> internal bool IsDisposed { get { using (new ReaderAutoLocker(this.DisposeLock)) return this.__disposed; } set { using (new WriterAutoLocker(this.DisposeLock)) this.__disposed = value; } } private bool __disposed = false; /// <summary> /// The reason of the disposing. /// </summary> internal Exception _disposeReason = null; /// <summary> /// Dispose lock. /// </summary> internal ReaderWriterLock DisposeLock = new ReaderWriterLock(); /// <summary> /// Releases all resources. /// </summary> /// <param name="reason">The reason of disposing.</param> public void Dispose(Exception reason) { if (this.IsDisposed) return ; if (reason == null) reason = GenuineExceptions.Get_Processing_TransportConnectionFailed(); // stop the processing using (new WriterAutoLocker(this.DisposeLock)) { if (this.IsDisposed) return ; this.IsDisposed = true; this._disposeReason = reason; } InternalDispose(reason); } /// <summary> /// Releases resources. /// </summary> /// <param name="reason">The reason of disposing.</param> public abstract void InternalDispose(Exception reason); #endregion #region -- Signalling ---------------------------------------------------------------------- /// <summary> /// The state controller. /// </summary> private ConnectionStateSignaller _connectionStateSignaller; /// <summary> /// The state controller lock. /// </summary> private object _connectionStateSignallerLock = new object(); /// <summary> /// Sets the state of the connection. /// </summary> /// <param name="genuineEventType">The state of the connection.</param> /// <param name="reason">The exception.</param> /// <param name="additionalInfo">The additional info.</param> public void SignalState(GenuineEventType genuineEventType, Exception reason, object additionalInfo) { lock (this._connectionStateSignallerLock) { if (this._connectionStateSignaller == null) this._connectionStateSignaller = new ConnectionStateSignaller(this.Remote, this.ITransportContext.IGenuineEventProvider); this._connectionStateSignaller.SetState(genuineEventType, reason, additionalInfo); } } #endregion #region -- Renewing ------------------------------------------------------------------------ /// <summary> /// The time span to close persistent connection after this period of inactivity. /// </summary> public int CloseConnectionAfterInactivity; /// <summary> /// The time after which the socket will be shut down automatically, or a DateTime.MaxValue value. /// </summary> public int ShutdownTime { get { lock (this._accessToLocalMembers) return this._shutdownTime; } } private int _shutdownTime = GenuineUtility.FurthestFuture; /// <summary> /// Renews socket activity for the CloseConnectionAfterInactivity value. /// </summary> public void Renew() { lock (this._accessToLocalMembers) this._shutdownTime = GenuineUtility.GetTimeout(this.CloseConnectionAfterInactivity); this.Remote.Renew(this.CloseConnectionAfterInactivity, false); } #endregion #region -- Establishing -------------------------------------------------------------------- /// <summary> /// Establishes Connection Level Security Session and gather their output into specified stream. /// </summary> /// <param name="senderInput">The input stream.</param> /// <param name="listenerInput">The input stream.</param> /// <param name="output">The output stream.</param> /// <param name="sender">The sender's Security Session.</param> /// <param name="listener">The listener's Security Session.</param> /// <returns>True if at least one Security Session requested sending of data.</returns> public bool GatherContentOfConnectionLevelSecuritySessions(Stream senderInput, Stream listenerInput, GenuineChunkedStream output, SecuritySession sender, SecuritySession listener) { bool clssDataPresents = false; Stream clsseStream; // CLSSE info using (new GenuineChunkedStreamSizeLabel(output)) { if (sender != null && ! sender.IsEstablished) { clsseStream = sender.EstablishSession(senderInput, true); if (clsseStream != null) { clssDataPresents = true; GenuineUtility.CopyStreamToStream(clsseStream, output); } } } // CLSSE info using (new GenuineChunkedStreamSizeLabel(output)) { if (listener != null && ! listener.IsEstablished) { clsseStream = listener.EstablishSession(listenerInput, true); if (clsseStream != null) { clssDataPresents = true; GenuineUtility.CopyStreamToStream(clsseStream, output); } } } return clssDataPresents; } #endregion } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Nio.Channels.Spi.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. #pragma warning disable 1717 namespace Java.Nio.Channels.Spi { /// <summary> /// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectionKey /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)] public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectionKey </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractSelectionKey() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isValid /// </java-name> [Dot42.DexImport("isValid", "()Z", AccessFlags = 17)] public override bool IsValid() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para> /// </summary> /// <java-name> /// cancel /// </java-name> [Dot42.DexImport("cancel", "()V", AccessFlags = 17)] public override void Cancel() /* MethodBuilder.Create */ { } } /// <summary> /// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectableChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)] public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para> /// </summary> /// <returns> /// <para>this channel's selector provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isRegistered /// </java-name> [Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)] public override bool IsRegistered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets this channel's selection key for the specified selector.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para> /// </returns> /// <java-name> /// keyFor /// </java-name> [Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)] public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for this registration. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" + "", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)] protected internal override void ImplCloseChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseSelectableChannel /// </java-name> [Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Indicates whether this channel is in blocking mode.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isBlocking /// </java-name> [Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)] public override bool IsBlocking() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para> /// </summary> /// <returns> /// <para>the synchronization object. </para> /// </returns> /// <java-name> /// blockingLock /// </java-name> [Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)] public override object BlockingLock() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para> /// </summary> /// <returns> /// <para>this channel. </para> /// </returns> /// <java-name> /// configureBlocking /// </java-name> [Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectableChannel); } /// <summary> /// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para> /// </summary> /// <java-name> /// implConfigureBlocking /// </java-name> [Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)] protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ; [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractInterruptibleChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)] public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if this channel is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)] public bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 17)] public void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "(Z)V", AccessFlags = 20)] protected internal void End(bool success) /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ; } /// <summary> /// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelector /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)] public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 49)] public override void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing of this channel. </para> /// </summary> /// <java-name> /// implCloseSelector /// </java-name> [Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if this selector is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)] public override bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this selector's provider. </para> /// </summary> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Returns this channel's set of canceled selection keys. </para> /// </summary> /// <java-name> /// cancelledKeys /// </java-name> [Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")] protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>); } /// <summary> /// <para>Registers <c> channel </c> with this selector.</para><para></para> /// </summary> /// <returns> /// <para>the key related to the channel and this selector. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" + "hannels/SelectionKey;", AccessFlags = 1028)] protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ; /// <summary> /// <para>Deletes the key from the channel's key set. </para> /// </summary> /// <java-name> /// deregister /// </java-name> [Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)] protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "()V", AccessFlags = 20)] protected internal void End() /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/SelectorProvider /// </java-name> [Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)] public abstract partial class SelectorProvider /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> SelectorProvider </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal SelectorProvider() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para> /// </summary> /// <returns> /// <para>the provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)] public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openDatagramChannel /// </java-name> [Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new <c> Pipe </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new pipe. </para> /// </returns> /// <java-name> /// openPipe /// </java-name> [Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new selector.</para><para></para> /// </summary> /// <returns> /// <para>the new selector. </para> /// </returns> /// <java-name> /// openSelector /// </java-name> [Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openServerSocketChannel /// </java-name> [Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Create a new open <c> SocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openSocketChannel /// </java-name> [Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para> /// </summary> /// <returns> /// <para>the channel. </para> /// </returns> /// <java-name> /// inheritedChannel /// </java-name> [Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)] public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.IChannel); } } }
using System; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.TestingHost; using Tester; using UnitTests.GrainInterfaces; using UnitTests.Tester; using Xunit; namespace UnitTests.CancellationTests { public class GrainCancellationTokenTests : OrleansTestingBase, IClassFixture<GrainCancellationTokenTests.Fixture> { private class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { return new TestCluster(new TestClusterOptions(2)); } } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] disabled until resolve of the https://github.com/dotnet/orleans/issues/1891 // [InlineData(10)] [InlineData(300)] public async Task GrainTaskCancellation(int delay) { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10)); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] // [InlineData(10)] [InlineData(300)] public async Task MultipleGrainsTaskCancellation(int delay) { var tcs = new GrainCancellationTokenSource(); var grainTasks = Enumerable.Range(0, 5) .Select(i => GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()) .LongWait(tcs.Token, TimeSpan.FromSeconds(10))) .Select(task => Assert.ThrowsAsync<TaskCanceledException>(() => task)).ToList(); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Task.WhenAll(grainTasks); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] public async Task TokenPassingWithoutCancellation_NoExceptionShouldBeThrown() { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); try { await grain.LongWait(tcs.Token, TimeSpan.FromMilliseconds(1)); } catch (Exception ex) { Assert.True(false, "Expected no exception, but got: " + ex.Message); } } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] public async Task PreCancelledTokenPassing() { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); await tcs.Cancel(); var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10)); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] public async Task CancellationTokenCallbacksExecutionContext() { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CancellationTokenCallbackResolve(tcs.Token); await Task.Delay(TimeSpan.FromMilliseconds(100)); await tcs.Cancel(); var result = await grainTask; Assert.Equal(true, result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] public async Task CancellationTokenCallbacksTaskSchedulerContext() { var grains = await GetGrains<bool>(false); var tcs = new GrainCancellationTokenSource(); var grainTask = grains.Item1.CallOtherCancellationTokenCallbackResolve(grains.Item2); await tcs.Cancel(); var result = await grainTask; Assert.Equal(true, result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] public async Task CancellationTokenCallbacksThrow_ExceptionShouldBePropagated() { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid()); var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CancellationTokenCallbackThrow(tcs.Token); await Task.Delay(TimeSpan.FromMilliseconds(100)); try { await tcs.Cancel(); } catch (AggregateException ex) { Assert.True(ex.InnerException is InvalidOperationException, "Exception thrown has wrong type"); return; } Assert.True(false, "No exception was thrown"); } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] // [InlineData(10)] [InlineData(300)] public async Task InSiloGrainCancellation(int delay) { await GrainGrainCancellation(false, delay); } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] // [InlineData(10)] [InlineData(300)] public async Task InterSiloGrainCancellation(int delay) { await GrainGrainCancellation(true, delay); } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] // [InlineData(10)] [InlineData(300)] public async Task InterSiloClientCancellationTokenPassing(int delay) { await ClientGrainGrainTokenPassing(delay, true); } [Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")] // [InlineData(0)] // [InlineData(10)] [InlineData(300)] public async Task InSiloClientCancellationTokenPassing(int delay) { await ClientGrainGrainTokenPassing(delay, false); } private async Task ClientGrainGrainTokenPassing(int delay, bool interSilo) { var grains = await GetGrains<bool>(interSilo); var grain = grains.Item1; var target = grains.Item2; var tcs = new GrainCancellationTokenSource(); var grainTask = grain.CallOtherLongRunningTask(target, tcs.Token, TimeSpan.FromSeconds(10)); await Task.Delay(TimeSpan.FromMilliseconds(delay)); await tcs.Cancel(); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } private async Task GrainGrainCancellation(bool interSilo, int delay) { var grains = await GetGrains<bool>(interSilo); var grain = grains.Item1; var target = grains.Item2; var grainTask = grain.CallOtherLongRunningTaskWithLocalToken(target, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(delay)); await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask); } private async Task<Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>> GetGrains<T1>(bool placeOnDifferentSilos = true) { var grain = GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); var instanceId = await grain.GetRuntimeInstanceId(); var target = GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); var targetInstanceId = await target.GetRuntimeInstanceId(); var retriesCount = 0; var retriesLimit = 10; while ((placeOnDifferentSilos && instanceId.Equals(targetInstanceId)) || (!placeOnDifferentSilos && !instanceId.Equals(targetInstanceId))) { if (retriesCount >= retriesLimit) throw new Exception("Could not make requested grains placement"); target = GrainClient.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid()); targetInstanceId = await target.GetRuntimeInstanceId(); retriesCount++; } return new Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>(grain, target); } } }
// // MethodReference.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // 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 Mono.Collections.Generic; namespace Mono.Cecil { public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext { int hashCode = -1; static int instance_id; internal ParameterDefinitionCollection parameters; MethodReturnType return_type; bool has_this; bool explicit_this; MethodCallingConvention calling_convention; internal Collection<GenericParameter> generic_parameters; public virtual bool HasThis { get { return has_this; } set { has_this = value; } } public virtual bool ExplicitThis { get { return explicit_this; } set { explicit_this = value; } } public virtual MethodCallingConvention CallingConvention { get { return calling_convention; } set { calling_convention = value; } } public virtual bool HasParameters { get { return !Mixin.IsNullOrEmpty(parameters); } } public virtual Collection<ParameterDefinition> Parameters { get { if (parameters == null) parameters = new ParameterDefinitionCollection(this); return parameters; } } IGenericParameterProvider IGenericContext.Type { get { var declaring_type = this.DeclaringType; var instance = declaring_type as GenericInstanceType; if (instance != null) return instance.ElementType; return declaring_type; } } IGenericParameterProvider IGenericContext.Method { get { return this; } } GenericParameterType IGenericParameterProvider.GenericParameterType { get { return GenericParameterType.Method; } } public virtual bool HasGenericParameters { get { return !Mixin.IsNullOrEmpty(generic_parameters); } } public virtual Collection<GenericParameter> GenericParameters { get { if (generic_parameters != null) return generic_parameters; return generic_parameters = new GenericParameterCollection(this); } } public TypeReference ReturnType { get { var return_type = MethodReturnType; return return_type != null ? return_type.ReturnType : null; } set { var return_type = MethodReturnType; if (return_type != null) return_type.ReturnType = value; } } public virtual MethodReturnType MethodReturnType { get { return return_type; } set { return_type = value; } } public override string FullName { get { var builder = new StringBuilder(); builder.Append(ReturnType.FullName) .Append(" ") .Append(MemberFullName()); Mixin.MethodSignatureFullName(this, builder); return builder.ToString(); } } public override int GetHashCode() { if (hashCode == -1) hashCode = System.Threading.Interlocked.Add(ref instance_id, 1); return hashCode; } public virtual bool IsGenericInstance { get { return false; } } internal override bool ContainsGenericParameter { get { if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter) return true; var parameters = this.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters[i].ParameterType.ContainsGenericParameter) return true; return false; } } internal MethodReference() { this.return_type = new MethodReturnType(this); this.token = new MetadataToken(TokenType.MemberRef); } public MethodReference(string name, TypeReference returnType) : base(name) { if (returnType == null) throw new ArgumentNullException("returnType"); this.return_type = new MethodReturnType(this); this.return_type.ReturnType = returnType; this.token = new MetadataToken(TokenType.MemberRef); } public MethodReference(string name, TypeReference returnType, TypeReference declaringType) : this(name, returnType) { if (declaringType == null) throw new ArgumentNullException("declaringType"); this.DeclaringType = declaringType; } public virtual MethodReference GetElementMethod() { return this; } public virtual MethodDefinition Resolve() { var module = this.Module; if (module == null) throw new NotSupportedException(); return module.Resolve(this); } } static partial class Mixin { public static bool IsVarArg(IMethodSignature self) { return (self.CallingConvention & MethodCallingConvention.VarArg) != 0; } public static int GetSentinelPosition(IMethodSignature self) { if (!self.HasParameters) return -1; var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters[i].ParameterType.IsSentinel) return i; return -1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { public abstract class Stream : IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int DefaultCopyBufferSize = 81920; // To implement Async IO operations on streams that don't support async IO private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public virtual int WriteTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public Task CopyToAsync(Stream destination) { int bufferSize = DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // If we go down this branch, it means there are // no bytes left in this stream. // Ideally we would just return Task.CompletedTask here, // but CopyToAsync(Stream, int, CancellationToken) was already // virtual at the time this optimization was introduced. So // if it does things like argument validation (checking if destination // is null and throwing an exception), then await fooStream.CopyToAsync(null) // would no longer throw if there were no bytes left. On the other hand, // we also can't roll our own argument validation and return Task.CompletedTask, // because it would be a breaking change if the stream's override didn't throw before, // or in a different order. So for simplicity, we just set the bufferSize to 1 // (not 0 since the default implementation throws for 0) and forward to the virtual method. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } return CopyToAsync(destination, bufferSize); } public Task CopyToAsync(Stream destination, int bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ValidateCopyToArguments(destination, bufferSize); return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken) { Debug.Assert(destination != null); Debug.Assert(bufferSize > 0); Debug.Assert(CanRead); Debug.Assert(destination.CanWrite); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { int bufferSize = DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // No bytes left in stream // Call the other overload with a bufferSize of 1, // in case it's made virtual in the future bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } CopyTo(destination, bufferSize); } public void CopyTo(Stream destination, int bufferSize) { ValidateCopyToArguments(destination, bufferSize); byte[] buffer = new byte[bufferSize]; int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, read); } } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); public Task FlushAsync() { return FlushAsync(CancellationToken.None); } public virtual Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : Task.Factory.FromAsync( (localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginRead(localBuffer, localOffset, localCount, callback, state), iar => ((Stream)iar.AsyncState).EndRead(iar), buffer, offset, count, this); } public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsyncInternal(buffer, offset, count), callback, state); public virtual int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); private Task<int> ReadAsyncInternal(Byte[] buffer, int offset, int count) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will serialize the requests. return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) => { Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion); var state = (Tuple<Stream, byte[], int, int>)s; try { return state.Item1.Read(state.Item2, state.Item3, state.Item4); // this.Read(buffer, offset, count); } finally { state.Item1._asyncActiveSemaphore.Release(); } }, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : Task.Factory.FromAsync( (localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginWrite(localBuffer, localOffset, localCount, callback, state), iar => ((Stream)iar.AsyncState).EndWrite(iar), buffer, offset, count, this); } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsyncInternal(buffer, offset, count), callback, state); public virtual void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); private Task WriteAsyncInternal(Byte[] buffer, int offset, int count) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will serialize the requests. return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) => { Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion); var state = (Tuple<Stream, byte[], int, int>)s; try { state.Item1.Write(state.Item2, state.Item3, state.Item4); // this.Write(buffer, offset, count); } finally { state.Item1._asyncActiveSemaphore.Release(); } }, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read(byte[] buffer, int offset, int count); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) { return -1; } return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } internal void ValidateCopyToArguments(Stream destination, int bufferSize) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } if (!CanRead && !CanWrite) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); } if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (!destination.CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } } private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments for compat, since previously this // method was inherited from Stream, which did check its arguments. ValidateCopyToArguments(destination, bufferSize); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } #pragma warning disable 1998 // async method with no await public override async Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); } #pragma warning restore 1998 public override int Read(byte[] buffer, int offset, int count) { return 0; } #pragma warning disable 1998 // async method with no await public override async Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return 0; } #pragma warning restore 1998 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } #pragma warning disable 1998 // async method with no await public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); } #pragma warning restore 1998 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using System.Linq; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Chat.V2.Service { /// <summary> /// FetchChannelOptions /// </summary> public class FetchChannelOptions : IOptions<ChannelResource> { /// <summary> /// The SID of the Service to fetch the resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchChannelOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the resource </param> public FetchChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// DeleteChannelOptions /// </summary> public class DeleteChannelOptions : IOptions<ChannelResource> { /// <summary> /// The SID of the Service to delete the resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel resource to delete /// </summary> public string PathSid { get; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new DeleteChannelOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to delete </param> public DeleteChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// CreateChannelOptions /// </summary> public class CreateChannelOptions : IOptions<ChannelResource> { /// <summary> /// The SID of the Service to create the Channel resource under /// </summary> public string PathServiceSid { get; } /// <summary> /// A string to describe the new resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// An application-defined string that uniquely identifies the Channel resource /// </summary> public string UniqueName { get; set; } /// <summary> /// A valid JSON string that contains application-specific data /// </summary> public string Attributes { get; set; } /// <summary> /// The visibility of the channel /// </summary> public ChannelResource.ChannelTypeEnum Type { get; set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was updated /// </summary> public DateTime? DateUpdated { get; set; } /// <summary> /// The identity of the User that created the Channel /// </summary> public string CreatedBy { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new CreateChannelOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Channel resource under </param> public CreateChannelOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (Type != null) { p.Add(new KeyValuePair<string, string>("Type", Type.ToString())); } if (DateCreated != null) { p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated))); } if (DateUpdated != null) { p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated))); } if (CreatedBy != null) { p.Add(new KeyValuePair<string, string>("CreatedBy", CreatedBy)); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// ReadChannelOptions /// </summary> public class ReadChannelOptions : ReadOptions<ChannelResource> { /// <summary> /// The SID of the Service to read the resources from /// </summary> public string PathServiceSid { get; } /// <summary> /// The visibility of the channel to read /// </summary> public List<ChannelResource.ChannelTypeEnum> Type { get; set; } /// <summary> /// Construct a new ReadChannelOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> public ReadChannelOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; Type = new List<ChannelResource.ChannelTypeEnum>(); } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Type != null) { p.AddRange(Type.Select(prop => new KeyValuePair<string, string>("Type", prop.ToString()))); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// UpdateChannelOptions /// </summary> public class UpdateChannelOptions : IOptions<ChannelResource> { /// <summary> /// The SID of the Service to update the resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel resource to update /// </summary> public string PathSid { get; } /// <summary> /// A string to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// A valid JSON string that contains application-specific data /// </summary> public string Attributes { get; set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was updated /// </summary> public DateTime? DateUpdated { get; set; } /// <summary> /// The identity of the User that created the Channel /// </summary> public string CreatedBy { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new UpdateChannelOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to update </param> public UpdateChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (DateCreated != null) { p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated))); } if (DateUpdated != null) { p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated))); } if (CreatedBy != null) { p.Add(new KeyValuePair<string, string>("CreatedBy", CreatedBy)); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Mono.Cecil; using UtilityClasses; using Mono.Cecil.Cil; using EcmaCil.IL; using Mono.Cecil.Rocks; namespace MonoCecilToEcmaCil1 { public partial class Reader : IDisposable { private Dictionary<QueuedMethod, EcmaCil.MethodMeta> mMethods = new Dictionary<QueuedMethod, EcmaCil.MethodMeta>(); private Dictionary<QueuedType, EcmaCil.TypeMeta> mTypes = new Dictionary<QueuedType, EcmaCil.TypeMeta>(); private Dictionary<QueuedArrayType, EcmaCil.ArrayTypeMeta> mArrayTypes = new Dictionary<QueuedArrayType, EcmaCil.ArrayTypeMeta>(); private Dictionary<QueuedPointerType, EcmaCil.PointerTypeMeta> mPointerTypes = new Dictionary<QueuedPointerType, EcmaCil.PointerTypeMeta>(); private Dictionary<QueuedMethod, EcmaCil.MethodMeta> mVirtuals = new Dictionary<QueuedMethod, EcmaCil.MethodMeta>(); #region queueing system private Queue<object> mQueue = new Queue<object>(); private EcmaCil.MethodMeta EnqueueMethod(MethodReference aMethod, object aSource, string aSourceType) { if (mLogEnabled) { LogMapPoint(aSource, aSourceType, aMethod); } List<TypeReference> xTypeArgs = null; var xGenSpec = aMethod as GenericInstanceMethod; TypeDefinition xTypeDef; MethodDefinition xMethodDef; TypeReference xRefType; if (xGenSpec != null) { xMethodDef = ResolveMethod(xGenSpec.ElementMethod); xRefType = xGenSpec.DeclaringType; xTypeArgs = new List<TypeReference>(); foreach (TypeReference xArg in xGenSpec.GenericArguments) { xTypeArgs.Add(xArg); } } else { xMethodDef = ResolveMethod(aMethod); xRefType = aMethod.DeclaringType; } #region resolve type xTypeDef = xRefType as TypeDefinition; if (xTypeDef == null) { var xGenType = xRefType as GenericInstanceType; if (xGenType != null) { xTypeDef = ResolveType(xGenType.DeclaringType); if (xTypeArgs == null) { xTypeArgs = new List<TypeReference>(); } for (int i = 0; i < xGenType.GenericArguments.Count; i++) { xTypeArgs.Insert(i, xGenType.GenericArguments[i]); } } else { xTypeDef = ResolveType(xRefType); } } #endregion var xQueuedMethod = new QueuedMethod(xTypeDef, xMethodDef, (xTypeArgs == null ? null : xTypeArgs.ToArray())); EcmaCil.MethodMeta xMethodMeta; if(mMethods.TryGetValue(xQueuedMethod, out xMethodMeta)){ return xMethodMeta; } var xDeclaringType = EnqueueType(xRefType, aMethod, "Declaring type"); xMethodMeta = new EcmaCil.MethodMeta(); xMethodMeta.DeclaringType = xDeclaringType; xDeclaringType.Methods.Add(xMethodMeta); mMethods.Add(xQueuedMethod, xMethodMeta); mQueue.Enqueue(xQueuedMethod); return xMethodMeta; } private EcmaCil.TypeMeta EnqueueType(TypeReference aTypeRef, object aSource, string aSourceType) { if (mLogEnabled) { LogMapPoint(aSource, aSourceType, aTypeRef); } List<TypeReference> xTypeArgs = null; TypeDefinition xTypeDef; var xArrayType = aTypeRef as ArrayType; if (xArrayType != null) { var xQueuedArrayType = new QueuedArrayType(xArrayType); EcmaCil.ArrayTypeMeta xArrayMeta; if (mArrayTypes.TryGetValue(xQueuedArrayType, out xArrayMeta)) { return xArrayMeta; } var xElemMeta = EnqueueType(xQueuedArrayType.ArrayType.ElementType, aTypeRef, "Array element type"); xArrayMeta = new EcmaCil.ArrayTypeMeta { ElementType = xElemMeta }; mArrayTypes.Add(xQueuedArrayType, xArrayMeta); mQueue.Enqueue(xQueuedArrayType); return xArrayMeta; } var xPointerType = aTypeRef as PointerType; if (xPointerType != null) { var xQueuedPointerType = new QueuedPointerType(xPointerType); EcmaCil.PointerTypeMeta xPointerMeta; if (mPointerTypes.TryGetValue(xQueuedPointerType, out xPointerMeta)) { return xPointerMeta; } var xElemMeta = EnqueueType(xQueuedPointerType.PointerType.ElementType, aTypeRef, "Array element type"); xPointerMeta = new EcmaCil.PointerTypeMeta { ElementType = xElemMeta }; mPointerTypes.Add(xQueuedPointerType, xPointerMeta); mQueue.Enqueue(xQueuedPointerType); return xPointerMeta; } var xGenSpec = aTypeRef as GenericInstanceType; if (xGenSpec != null) { xTypeDef = ResolveType(xGenSpec.ElementType); xTypeArgs = new List<TypeReference>(); foreach (TypeReference xArg in xGenSpec.GenericArguments) { xTypeArgs.Add(xArg); } } else { xTypeDef = ResolveType(aTypeRef); } var xQueuedType = new QueuedType(xTypeDef, (xTypeArgs == null ? null : xTypeArgs.ToArray())); EcmaCil.TypeMeta xTypeMeta; if (mTypes.TryGetValue(xQueuedType, out xTypeMeta)) { return xTypeMeta; } xTypeMeta = new EcmaCil.TypeMeta(); if (xTypeDef.BaseType != null) { xTypeMeta.BaseType = EnqueueType(xTypeDef.BaseType, aTypeRef, "Base type"); } mTypes.Add(xQueuedType, xTypeMeta); mQueue.Enqueue(xQueuedType); return xTypeMeta; } #endregion public void Dispose() { GC.SuppressFinalize(this); } public void Clear() { mMethods.Clear(); mTypes.Clear(); mArrayTypes.Clear(); mPointerTypes.Clear(); } public IEnumerable<EcmaCil.TypeMeta> Execute(string assembly) { var xAssemblyDef = AssemblyDefinition.ReadAssembly(assembly); if (xAssemblyDef.EntryPoint == null) { throw new ArgumentException("Main assembly should have entry point!"); } if (xAssemblyDef.EntryPoint.GenericParameters.Count > 0 || xAssemblyDef.EntryPoint.DeclaringType.GenericParameters.Count > 0) { throw new ArgumentException("Main assembly's entry point has generic parameters. This is not supported!"); } EnqueueMethod(xAssemblyDef.EntryPoint, null, "entry point"); // handle queue while (mQueue.Count > 0) { var xItem = mQueue.Dequeue(); if (xItem is QueuedMethod) { var xMethod = (QueuedMethod)xItem; ScanMethod(xMethod, mMethods[xMethod]); continue; } if (xItem is QueuedArrayType) { var xType = (QueuedArrayType)xItem; ScanArrayType(xType, mArrayTypes[xType]); continue; } if (xItem is QueuedPointerType) { var xType = (QueuedPointerType)xItem; ScanPointerType(xType, mPointerTypes[xType]); continue; } if (xItem is QueuedType) { var xType = (QueuedType)xItem; ScanType(xType, mTypes[xType]); continue; } throw new Exception("Queue item not supported: '" + xItem.GetType().FullName + "'!"); } return mTypes.Values.Cast<EcmaCil.TypeMeta>() .Union(mArrayTypes.Values.Cast<EcmaCil.TypeMeta>()) .Union(mPointerTypes.Values.Cast<EcmaCil.TypeMeta>()); } private void ScanPointerType(QueuedPointerType xType, EcmaCil.PointerTypeMeta pointerTypeMeta) { #if DEBUG pointerTypeMeta.Data[EcmaCil.DataIds.DebugMetaId] = "&" + pointerTypeMeta.ElementType.ToString(); #endif } private void ScanArrayType(QueuedArrayType aType, EcmaCil.ArrayTypeMeta arrayTypeMeta) { arrayTypeMeta.Dimensions = aType.ArrayType.Dimensions.Count; // todo: fix? foreach (ArrayDimension xDimension in aType.ArrayType.Dimensions) { if (xDimension.LowerBound != 0 || xDimension.UpperBound != 0) { throw new Exception("Arrays with limited dimensions not supported"); } } #if DEBUG var xSB = new StringBuilder(); xSB.Append(arrayTypeMeta.ElementType.ToString()); xSB.Append("["); xSB.Append(new String(',', arrayTypeMeta.Dimensions - 1)); xSB.Append("]"); arrayTypeMeta.Data[EcmaCil.DataIds.DebugMetaId] = xSB.ToString(); #endif } private void ScanType(QueuedType aType, EcmaCil.TypeMeta aTypeMeta) { #if DEBUG var xSB = new StringBuilder(); xSB.Append(aType.Type.ToString()); if (aType.Args.Length > 0) { xSB.Append("<"); for (int i = 0; i < aType.Args.Length; i++) { xSB.Append(aType.Args[i].ToString()); if (i < (aType.Args.Length - 1)) { xSB.Append(", "); } } xSB.Append(">"); } aTypeMeta.Data[EcmaCil.DataIds.DebugMetaId] = xSB.ToString(); #endif } private void ScanMethod(QueuedMethod aMethod, EcmaCil.MethodMeta aMethodMeta) { // todo: add support for plugs #if DEBUG aMethodMeta.Data[EcmaCil.DataIds.DebugMetaId] = aMethod.Method.ToString(); #endif var xParamOffset = 0; if (!aMethod.Method.IsStatic) { xParamOffset = 1; } aMethodMeta.Parameters = new EcmaCil.MethodParameterMeta[aMethod.Method.Parameters.Count + xParamOffset]; if (!aMethod.Method.IsStatic) { aMethodMeta.Parameters[0] = new EcmaCil.MethodParameterMeta { IsByRef = aMethod.Method.DeclaringType.IsValueType, PropertyType = EnqueueType(aMethod.Method.DeclaringType, aMethod, "Declaring type") }; #if DEBUG aMethodMeta.Parameters[0].Data[EcmaCil.DataIds.DebugMetaId] = "$this"; #endif } for(int i = 0; i < aMethod.Method.Parameters.Count;i++){ var xParam = aMethod.Method.Parameters[i]; var xParamType = xParam.ParameterType; if (xParamType is GenericParameter) { // todo: resolve generics. throw new NotImplementedException(); } var xParamMeta = aMethodMeta.Parameters[i + xParamOffset] = new EcmaCil.MethodParameterMeta(); //if (xParamType is ReferenceType) //{ // xParamType = ((ReferenceType)xParamType).ElementType; // xParamMeta.IsByRef = true; //} var xType = EnqueueType(xParamType, aMethod, "parameter"); #if DEBUG var xSB = new StringBuilder(); xSB.Append(xParam.Name); xSB.Append(": "); if (xParamMeta.IsByRef) { xSB.Append("ref "); } xSB.Append(xParamType.ToString()); xParamMeta.Data[EcmaCil.DataIds.DebugMetaId] = xSB.ToString(); #endif xParamMeta.PropertyType = xType; } if (aMethod.Method.ReturnType.FullName != "System.Void") { aMethodMeta.ReturnType = EnqueueType(aMethod.Method.ReturnType, aMethod.Method, "Return Type"); } aMethodMeta.IsStatic = aMethod.Method.IsStatic; ScanMethodBody(aMethod, aMethodMeta); #region Virtuals scan if (aMethod.Method.IsVirtual) { if (aMethod.Method.HasGenericParameters) { throw new Exception("GEnerics not yet fully supported"); } // For virtuals we need to climb up the type tree // and find the top base method. We then add that top // node to the mVirtuals list. We don't need to add the // types becuase adding DeclaringType will already cause // all ancestor types to be added. var xVirtMethod = aMethod.Method; TypeReference xVirtType = aMethod.Method.DeclaringType; xVirtMethod = xVirtMethod.GetOriginalBaseMethod(); #region old code // MethodReference xNewVirtMethod = null; // while (true) // { // var xNewVirtType = xVirtType.Resolve(); // if (xNewVirtType.HasGenericParameters) // { // throw new Exception("Generics not fully supported yet!"); // } // if (xNewVirtType == null) // { // xVirtType = null; // } // else // { //#warning // todo: verify if next code works ok with generics // var xTempNewVirtMethod = xNewVirtType. .m.Methods..GetMethod(aMethod.Method.Name, aMethod.Method.Parameters); // if (xTempNewVirtMethod !=null) // { // if (xTempNewVirtMethod.IsVirtual) // { // xNewVirtMethod = xTempNewVirtMethod; // } // } // else // { // xNewVirtMethod = null; // } // } // if (xNewVirtMethod == null) // { // if (mVirtuals.ContainsKey(aMethod)) // { // xVirtMethod = null; // } // break; // } // xVirtMethod = xNewVirtMethod.Resolve(); // xVirtType = xNewVirtType.BaseType; // if (xVirtType == null) // { // break; // } // } #endregion old code if (xVirtMethod!=null) { EnqueueMethod(xVirtMethod, aMethod, "Virtual Base"); foreach (var xType in mTypes) { if (xType.Key.Type.IsSubclassOf(xVirtMethod.DeclaringType)) { //xType.Key.Type.res //var xNewMethod = xType.Key.Type.Methods.GetMethod(aMethod.Method.Name, aMethod.Method.Parameters); //if (xNewMethod != null) //{ // // We need to check IsVirtual, a non virtual could // // "replace" a virtual above it? // // MtW: correct // if (xNewMethod.IsVirtual) // { // EnqueueMethod(xNewMethod, aMethod, "Virtual Downscan"); // } //} throw new NotImplementedException(); } } } } #endregion } protected virtual void ScanMethodBody(QueuedMethod aMethod, EcmaCil.MethodMeta aMethodMeta) { if (aMethod.Method.HasBody) { var xBody = aMethod.Method.Body; var xBodyMeta = aMethodMeta.Body = new EcmaCil.MethodBodyMeta(); xBodyMeta.InitLocals = xBody.InitLocals; #region handle exception handling clauses if (xBody.HasExceptionHandlers) { throw new Exception("ExceptionHandlers are not supported yet"); } #endregion #region handle locals xBodyMeta.LocalVariables = new EcmaCil.LocalVariableMeta[xBody.Variables.Count]; for (int i = 0; i < xBody.Variables.Count; i++) { var xVar = xBody.Variables[i]; var xVarMeta = xBodyMeta.LocalVariables[i] = new EcmaCil.LocalVariableMeta(); xVarMeta.LocalType = EnqueueType(xVar.VariableType, aMethod, "Local variable"); #if DEBUG xVarMeta.Data[EcmaCil.DataIds.DebugMetaId] = xVar.Name + ":" + xVar.VariableType.ToString(); #endif } #endregion xBodyMeta.Instructions = new EcmaCil.IL.BaseInstruction[xBody.Instructions.Count]; var xILOffsetToInstructionOffset = new Dictionary<int, int>(); var xInstructionOffsetToILOffset = new Dictionary<int, int>(); var xSecondStageInits = new List<Action<EcmaCil.MethodMeta>>(); for (int i = 0; i < xBody.Instructions.Count; i++) { xILOffsetToInstructionOffset.Add(xBody.Instructions[i].Offset, i); xInstructionOffsetToILOffset.Add(i, xBody.Instructions[i].Offset); } for (int i = 0; i < xBody.Instructions.Count; i++) { var xInstr = xBody.Instructions[i]; xBodyMeta.Instructions[i] = CreateInstructionMeta(aMethod, aMethodMeta, xInstr, xILOffsetToInstructionOffset, xInstructionOffsetToILOffset, i, xSecondStageInits, i + 1); } if (xSecondStageInits.Count > 0) { foreach (var xInit in xSecondStageInits) { xInit(aMethodMeta); } } } } private BaseInstruction CreateInstructionMeta(QueuedMethod aMethod, EcmaCil.MethodMeta aMethodMeta, Instruction curInstruction, IDictionary<int, int> aILToInstructionOffset, IDictionary<int, int> aInstructionToILOffset, int aCurrentIndex, IList<Action<EcmaCil.MethodMeta>> aSecondStageInits, int aNextIndex) { switch (curInstruction.OpCode.Code) { case Code.Nop: return new InstructionNone(InstructionKindEnum.Nop, aCurrentIndex); case Code.Pop: return new InstructionNone(InstructionKindEnum.Pop, aCurrentIndex); case Code.Ldc_I4_S: return new InstructionInt32(GetInstructionKind(curInstruction.OpCode.Code), aCurrentIndex, (int)(sbyte)curInstruction.Operand); case Code.Stloc_0: return new InstructionInt32(InstructionKindEnum.Stloc, aCurrentIndex, 0); case Code.Stloc_1: return new InstructionInt32(InstructionKindEnum.Stloc, aCurrentIndex, 1); case Code.Ldloc_0: return new InstructionLocal(InstructionKindEnum.Ldloc, aCurrentIndex, aMethodMeta.Body.LocalVariables[0]); case Code.Ldloc_1: return new InstructionLocal(InstructionKindEnum.Ldloc, aCurrentIndex, aMethodMeta.Body.LocalVariables[1]); case Code.Ldloc_2: return new InstructionLocal(InstructionKindEnum.Ldloc, aCurrentIndex, aMethodMeta.Body.LocalVariables[2]); case Code.Call: return new InstructionMethod(InstructionKindEnum.Call, aCurrentIndex, EnqueueMethod(curInstruction.Operand as MethodReference, aMethod.Method, "Operand value")); case Code.Callvirt: return new InstructionMethod(InstructionKindEnum.Callvirt, aCurrentIndex, EnqueueMethod(curInstruction.Operand as MethodReference, aMethod.Method, "Operand value")); case Code.Stloc_2: return new InstructionLocal(InstructionKindEnum.Stloc, aCurrentIndex, aMethodMeta.Body.LocalVariables[2]); case Code.Stloc_3: return new InstructionLocal(InstructionKindEnum.Stloc, aCurrentIndex, aMethodMeta.Body.LocalVariables[3]); case Code.Ret: return new InstructionNone(InstructionKindEnum.Ret, aCurrentIndex); case Code.Ldarg_0: return new InstructionArgument(InstructionKindEnum.Ldarg, aCurrentIndex, aMethodMeta.Parameters[0]); case Code.Ldarg_1: return new InstructionArgument(InstructionKindEnum.Ldarg, aCurrentIndex, aMethodMeta.Parameters[1]); case Code.Add: return new InstructionNone(InstructionKindEnum.Add, aCurrentIndex); case Code.Ldstr: return new InstructionString(InstructionKindEnum.Ldstr, aCurrentIndex, (string)curInstruction.Operand); case Code.Newobj: return new InstructionMethod(InstructionKindEnum.Newobj, aCurrentIndex, EnqueueMethod(curInstruction.Operand as MethodReference, aMethod.Method, "Operand value")); case Code.Br_S: case Code.Brfalse_S: var xInstr = new InstructionBranch(GetInstructionKind(curInstruction.OpCode.Code), aCurrentIndex); var xTargetInstr = (Instruction)curInstruction.Operand; var xTargetOffset = xTargetInstr.Offset; aSecondStageInits.Add(delegate(EcmaCil.MethodMeta aTheMethod) { xInstr.Target = aTheMethod.Body.Instructions[aILToInstructionOffset[xTargetOffset]]; }); return xInstr; // case //case OperandType.InlineNone: // { // xInstrMeta = new InstructionNone(GetInstructionKind(xInstr.OpCode.Code), i + xOffset); // break; // } //case OperandType.ShortInlineI: // { // xInstrMeta = new InstructionInt32(GetInstructionKind(xInstr.OpCode.Code), i + xOffset, (int)(sbyte)xInstr.Operand); // break; // } default: throw new Exception("Op '" + curInstruction.OpCode.Code + "' not implemented!"); } } } }
// 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: List for exceptions. ** ** ===========================================================*/ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary that is empty and readonly. internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary { // Note that this class must be agile with respect to AppDomains. See its usage in // System.Exception to understand why this is the case. public EmptyReadOnlyDictionaryInternal() { } // IEnumerable members IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(); } // ICollection members public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); Contract.EndContractBlock(); // the actual copy is a NOP } public int Count { get { return 0; } } public Object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } // IDictionary members public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } Contract.EndContractBlock(); return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } public ICollection Keys { get { return Array.Empty<Object>(); } } public ICollection Values { get { return Array.Empty<Object>(); } } public bool Contains(Object key) { return false; } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public void Clear() { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(); } public void Remove(Object key) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } private sealed class NodeEnumerator : IDictionaryEnumerator { public NodeEnumerator() { } // IEnumerator members public bool MoveNext() { return false; } public Object Current { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public void Reset() { } // IDictionaryEnumerator members public Object Key { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public Object Value { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public DictionaryEntry Entry { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } } } }
// 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.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AbsByte() { var test = new SimpleUnaryOpTest__AbsByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleUnaryOpTest__AbsByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__AbsByte testClass) { var result = AdvSimd.Abs(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector64<SByte> _clsVar1; private Vector64<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__AbsByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleUnaryOpTest__AbsByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Abs( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Abs( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.Abs(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Abs(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__AbsByte(); var result = AdvSimd.Abs(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__AbsByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Abs(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Abs(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Abs( AdvSimd.LoadVector64((SByte*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)Math.Abs(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)Math.Abs(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<Byte>(Vector64<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookChartLineFormatRequest. /// </summary> public partial class WorkbookChartLineFormatRequest : BaseRequest, IWorkbookChartLineFormatRequest { /// <summary> /// Constructs a new WorkbookChartLineFormatRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookChartLineFormatRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChartLineFormat using POST. /// </summary> /// <param name="workbookChartLineFormatToCreate">The WorkbookChartLineFormat to create.</param> /// <returns>The created WorkbookChartLineFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartLineFormat> CreateAsync(WorkbookChartLineFormat workbookChartLineFormatToCreate) { return this.CreateAsync(workbookChartLineFormatToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChartLineFormat using POST. /// </summary> /// <param name="workbookChartLineFormatToCreate">The WorkbookChartLineFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartLineFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartLineFormat> CreateAsync(WorkbookChartLineFormat workbookChartLineFormatToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChartLineFormat>(workbookChartLineFormatToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChartLineFormat. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChartLineFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookChartLineFormat>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChartLineFormat. /// </summary> /// <returns>The WorkbookChartLineFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartLineFormat> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChartLineFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartLineFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartLineFormat> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChartLineFormat>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChartLineFormat using PATCH. /// </summary> /// <param name="workbookChartLineFormatToUpdate">The WorkbookChartLineFormat to update.</param> /// <returns>The updated WorkbookChartLineFormat.</returns> public System.Threading.Tasks.Task<WorkbookChartLineFormat> UpdateAsync(WorkbookChartLineFormat workbookChartLineFormatToUpdate) { return this.UpdateAsync(workbookChartLineFormatToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChartLineFormat using PATCH. /// </summary> /// <param name="workbookChartLineFormatToUpdate">The WorkbookChartLineFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartLineFormat.</returns> public async System.Threading.Tasks.Task<WorkbookChartLineFormat> UpdateAsync(WorkbookChartLineFormat workbookChartLineFormatToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChartLineFormat>(workbookChartLineFormatToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLineFormatRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLineFormatRequest Expand(Expression<Func<WorkbookChartLineFormat, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLineFormatRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLineFormatRequest Select(Expression<Func<WorkbookChartLineFormat, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookChartLineFormatToInitialize">The <see cref="WorkbookChartLineFormat"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChartLineFormat workbookChartLineFormatToInitialize) { } } }
using System; using System.Collections.Generic; using BTDB.Encrypted; using BTDB.EventStore2Layer; using BTDB.EventStoreLayer; using BTDB.FieldHandler; using Xunit; namespace BTDBTest; public class EventStoreMigrationTest { public class Item { public string Field { get; set; } } public class EventRoot { public List<Item> Items { get; set; } } [Fact] public void CanMigrateList() { var obj = PassThroughEventStorage(new EventRoot { Items = new List<Item> { new Item { Field = "A" } } }, new FullNameTypeMapper()); var serializer = new EventSerializer(); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); } static object PassThroughEventStorage(object @event, ITypeNameMapper mapper, bool ignoreIndirect = true) { var options = TypeSerializersOptions.Default; options.IgnoreIIndirect = ignoreIndirect; options.SymmetricCipher = new AesGcmSymmetricCipher(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }); var manager = new EventStoreManager(options); var storage = new MemoryEventFileStorage(); var appender = manager.AppendToStore(storage); var events = new[] { @event }; appender.Store(null, events); manager = new EventStoreManager(options); manager.SetNewTypeNameMapper(mapper); var eventObserver = new EventStoreTest.StoringEventObserver(); manager.OpenReadOnlyStore(storage).ReadFromStartToEnd(eventObserver); return eventObserver.Events[0][0]; } public class Item2 { public string Field { get; set; } public string Field2 { get; set; } } public class EventRoot2 { public List<Item2> Items { get; set; } } [Fact] public void CanMigrateListWithNewFields() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(Item2), parentMapper.ToName(typeof(Item)), new EventStoreTest.OverloadableTypeMapper(typeof(EventRoot2), parentMapper.ToName(typeof(EventRoot)), parentMapper )); var obj = PassThroughEventStorage(new EventRoot { Items = new List<Item> { new Item { Field = "A" } } }, mapper); var serializer = new EventSerializer(mapper); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(mapper); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); } public class EventDictListRoot { public IDictionary<ulong, IList<Item>> Items { get; set; } } [Fact] public void CanMigrateListInDict() { var obj = PassThroughEventStorage(new EventDictListRoot { Items = new Dictionary<ulong, IList<Item>> { { 1, new List<Item> { new Item { Field = "A" } } } } }, new FullNameTypeMapper()); var serializer = new EventSerializer(); var meta = serializer.Serialize(out _, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out _, obj); var deserializer = new EventDeserializer(); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); } public enum ItemEn { One = 1 } public class EventRootEn { public List<ItemEn> Items { get; set; } } public enum ItemEn2 { One = 1, Two = 2 } public class EventRootEn2 { public List<ItemEn2> Items { get; set; } } [Fact] public void CanMigrateListWithChangedEnum() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(ItemEn2), parentMapper.ToName(typeof(ItemEn)), new EventStoreTest.OverloadableTypeMapper(typeof(EventRootEn2), parentMapper.ToName(typeof(EventRootEn)), parentMapper )); var obj = PassThroughEventStorage(new EventRootEn { Items = new List<ItemEn> { ItemEn.One } }, mapper); var serializer = new EventSerializer(mapper); bool hasMetadata; var meta = serializer.Serialize(out hasMetadata, obj).ToAsyncSafe(); serializer.ProcessMetadataLog(meta); var data = serializer.Serialize(out hasMetadata, obj); var deserializer = new EventDeserializer(mapper); object obj2; Assert.False(deserializer.Deserialize(out obj2, data)); deserializer.ProcessMetadataLog(meta); Assert.True(deserializer.Deserialize(out obj2, data)); } public class EventWithInt { public int A { get; set; } } public class EventWithUlong { public ulong A { get; set; } } [Fact] public void CanMigrateIntToUlong() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(EventWithUlong), parentMapper.ToName(typeof(EventWithInt)), parentMapper ); var obj = (EventWithUlong)PassThroughEventStorage(new EventWithInt { A = 42 }, mapper); Assert.Equal(42ul, obj.A); var obj2 = (EventWithUlong)PassThroughEventStorage(new EventWithInt { A = -1 }, mapper); Assert.Equal(0xffffffff, obj2.A); } public class EventWithString { public string A { get; set; } } public class EventWithVersion { public Version A { get; set; } } [Fact] public void CanMigrateStringToVersion() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(EventWithVersion), parentMapper.ToName(typeof(EventWithString)), parentMapper ); var obj = (EventWithVersion)PassThroughEventStorage(new EventWithString { A = "1.2.3" }, mapper); Assert.Equal(new Version(1, 2, 3), obj.A); var obj2 = (EventWithVersion)PassThroughEventStorage(new EventWithString { A = null }, mapper); Assert.Null(obj2.A); } public class EventWithEncryptedString { public EncryptedString A { get; set; } } [Fact] public void CanMigrateStringToEncryptedString() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(EventWithEncryptedString), parentMapper.ToName(typeof(EventWithString)), parentMapper ); var obj = (EventWithEncryptedString)PassThroughEventStorage(new EventWithString { A = "pass" }, mapper); Assert.Equal("pass", obj.A); var obj2 = (EventWithEncryptedString)PassThroughEventStorage(new EventWithString { A = null }, mapper); Assert.Null(obj2.A.Secret); } public abstract class ItemBase { public int A { get; set; } } public class ItemBase1 : ItemBase { public int B { get; set; } } public class EventDictIndirectAbstract { public IDictionary<ulong, IIndirect<ItemBase>> Items { get; set; } } public class EventDictAbstract { public IDictionary<ulong, ItemBase> Items { get; set; } } [Fact] public void CanMigrateDictionaryValueOutOfIndirect() { var parentMapper = new FullNameTypeMapper(); var mapper = new EventStoreTest.OverloadableTypeMapper(typeof(EventDictAbstract), parentMapper.ToName(typeof(EventDictIndirectAbstract)), parentMapper ); var obj = PassThroughEventStorage(new EventDictIndirectAbstract { Items = new Dictionary<ulong, IIndirect<ItemBase>> {{1, new DBIndirect<ItemBase>(new ItemBase1 {A = 1, B = 2})}} }, mapper, false); Assert.IsType<EventDictAbstract>(obj); var res = (EventDictAbstract)obj; Assert.Equal(1, res.Items[1].A); Assert.Equal(2, ((ItemBase1)res.Items[1]).B); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Should; using Xunit; namespace AutoMapper.UnitTests { namespace Dictionaries { //[Explicit("Need to resolve the assignable collection bug as well")] //public class When_mapping_to_a_non_generic_dictionary : AutoMapperSpecBase //{ // private Destination _result; // public class Source // { // public Hashtable Values { get; set; } // } // public class Destination // { // public IDictionary Values { get; set; } // } // protected override void Establish_context() // { // Mapper.CreateMap<Source, Destination>(); // } // protected override void Because_of() // { // var source = new Source // { // Values = new Hashtable // { // {"Key1", "Value1"}, // {"Key2", 4} // } // }; // _result = Mapper.Map<Source, Destination>(source); // } // [Fact] // public void Should_map_the_source_dictionary_with_all_keys_and_values_preserved() // { // _result.Values.Count.ShouldEqual(2); // _result.Values["Key1"].ShouldEqual("Value1"); // _result.Values["Key2"].ShouldEqual(4); // } //} public class When_mapping_to_a_generic_dictionary_with_mapped_value_pairs : AutoMapperSpecBase { private Destination _result; public class Source { public Dictionary<string, SourceValue> Values { get; set; } } public class SourceValue { public int Value { get; set; } } public class Destination { public Dictionary<string, DestinationValue> Values { get; set; } } public class DestinationValue { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<SourceValue, DestinationValue>(); }); protected override void Because_of() { var source = new Source { Values = new Dictionary<string, SourceValue> { {"Key1", new SourceValue {Value = 5}}, {"Key2", new SourceValue {Value = 10}}, } }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].Value.ShouldEqual(5); _result.Values["Key2"].Value.ShouldEqual(10); } } public class When_mapping_to_a_generic_dictionary_interface_with_mapped_value_pairs : AutoMapperSpecBase { private Destination _result; public class Source { public Dictionary<string, SourceValue> Values { get; set; } } public class SourceValue { public int Value { get; set; } } public class Destination { public System.Collections.Generic.IDictionary<string, DestinationValue> Values { get; set; } } public class DestinationValue { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<SourceValue, DestinationValue>(); }); protected override void Because_of() { var source = new Source { Values = new Dictionary<string, SourceValue> { {"Key1", new SourceValue {Value = 5}}, {"Key2", new SourceValue {Value = 10}}, } }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].Value.ShouldEqual(5); _result.Values["Key2"].Value.ShouldEqual(10); } } public class When_mapping_from_a_source_with_a_null_dictionary_member : AutoMapperSpecBase { private FooDto _result; public class Foo { public System.Collections.Generic.IDictionary<string, Foo> Bar { get; set; } } public class FooDto { public System.Collections.Generic.IDictionary<string, FooDto> Bar { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.AllowNullDestinationValues = false; cfg.CreateMap<Foo, FooDto>(); cfg.CreateMap<FooDto, Foo>(); }); protected override void Because_of() { var foo1 = new Foo { Bar = new Dictionary<string, Foo> { {"lol", new Foo()} } }; _result = Mapper.Map<Foo, FooDto>(foo1); } [Fact] public void Should_fill_the_destination_with_an_empty_dictionary() { _result.Bar["lol"].Bar.ShouldNotBeNull(); _result.Bar["lol"].Bar.ShouldBeType<Dictionary<string, FooDto>>(); } } public class When_mapping_to_a_generic_dictionary_that_does_not_use_keyvaluepairs : AutoMapperSpecBase { private System.Collections.Generic.IDictionary<string, string> _dest; public class SourceDto { public System.Collections.Generic.IDictionary<string, string> Items { get; set; } } public class DestDto { public System.Collections.Generic.IDictionary<string, string> Items { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<SourceDto, DestDto>() .ForMember(d => d.Items, opt => opt.MapFrom(s => s.Items)); }); protected override void Because_of() { var source = new SourceDto() { Items = new GenericWrappedDictionary<string, string> { {"A", "AAA"}, {"B", "BBB"}, {"C", "CCC"} } }; _dest = Mapper.Map<System.Collections.Generic.IDictionary<string, string>, System.Collections.Generic.IDictionary<string, string>>(source.Items); } [Fact] public void Should_map_using_the_nongeneric_dictionaryentry() { _dest.Values.Count.ShouldEqual(3); } // A wrapper for an IDictionary that implements IDictionary<TKey, TValue> // // The important difference from a standard generic BCL dictionary is that: // // ((IEnumerable)GenericWrappedDictionary).GetEnumerator() returns DictionaryEntrys // GenericWrappedDictionary.GetEnumerator() returns KeyValuePairs // // This behaviour is demonstrated by NHibernate's PersistentGenericMap // (which wraps a nongeneric PersistentMap). public class GenericWrappedDictionary<TKey, TValue> : System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.IDictionary { System.Collections.IDictionary inner = new Dictionary<TKey, TValue>(); public void Add(TKey key, TValue value) { inner.Add(key, value); } public bool ContainsKey(TKey key) { throw new NotImplementedException(); } public ICollection<TKey> Keys { get { return inner.Keys.Cast<TKey>().ToList(); } } public bool Remove(TKey key) { throw new NotImplementedException(); } public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); } public ICollection<TValue> Values { get { return inner.Values.Cast<TValue>().ToList(); } } public TValue this[TKey key] { get { return (TValue)inner[key]; } set { inner[key] = value; } } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return inner.OfType<DictionaryEntry>() .Select(e => new KeyValuePair<TKey, TValue>((TKey)e.Key, (TValue)e.Value)) .GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return inner.GetEnumerator(); } public void Add(object key, object value) { inner.Add(key, value); } public bool Contains(object key) { throw new NotImplementedException(); } IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return ((System.Collections.IDictionary)inner).GetEnumerator(); } public bool IsFixedSize { get { throw new NotImplementedException(); } } ICollection System.Collections.IDictionary.Keys { get { return inner.Keys; } } public void Remove(object key) { throw new NotImplementedException(); } ICollection System.Collections.IDictionary.Values { get { return inner.Values; } } public object this[object key] { get { return inner[key]; } set { inner[key] = value; } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } } } public class When_mapping_from_a_list_of_object_to_generic_dictionary : AutoMapperSpecBase { private FooObject _result; public class FooDto { public DestinationValuePair[] Values { get; set; } } public class FooObject { public Dictionary<string, string> Values { get; set; } } public class DestinationValuePair { public string Key { get; set; } public string Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<FooDto, FooObject>(); cfg.CreateMap<DestinationValuePair, KeyValuePair<string, string>>() .ConvertUsing(src => new KeyValuePair<string, string>(src.Key, src.Value)); }); protected override void Because_of() { var source = new FooDto { Values = new List<DestinationValuePair> { new DestinationValuePair {Key = "Key1", Value = "Value1"}, new DestinationValuePair {Key = "Key2", Value = "Value2"} }.ToArray() }; _result = Mapper.Map<FooDto, FooObject>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].ShouldEqual("Value1"); _result.Values["Key2"].ShouldEqual("Value2"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Fabrikam.Module1.Uc1.Query.Services.WebApi.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); } } } }
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.ConsumePipeSpecifications { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using ConsumeConfigurators; using Context.Converters; using GreenPipes; using GreenPipes.Builders; using GreenPipes.Filters; using Metadata; using Pipeline; using Pipeline.Pipes; using Saga; using SagaConfigurators; public class ConsumePipeSpecification : IConsumePipeConfigurator, IConsumePipeSpecification { readonly IList<IPipeSpecification<ConsumeContext>> _consumeContextSpecifications; readonly ConsumerConfigurationObservable _consumerObservers; readonly HandlerConfigurationObservable _handlerObservers; readonly object _lock = new object(); readonly ConcurrentDictionary<Type, IMessageConsumePipeSpecification> _messageSpecifications; readonly ConsumePipeSpecificationObservable _observers; readonly SagaConfigurationObservable _sagaObservers; readonly IList<IPipeSpecification<ConsumeContext>> _specifications; public ConsumePipeSpecification() { _specifications = new List<IPipeSpecification<ConsumeContext>>(); _consumeContextSpecifications = new List<IPipeSpecification<ConsumeContext>>(); _messageSpecifications = new ConcurrentDictionary<Type, IMessageConsumePipeSpecification>(); _observers = new ConsumePipeSpecificationObservable(); _consumerObservers = new ConsumerConfigurationObservable(); _sagaObservers = new SagaConfigurationObservable(); _handlerObservers = new HandlerConfigurationObservable(); } public void AddPipeSpecification(IPipeSpecification<ConsumeContext> specification) { lock (_lock) { _specifications.Add(specification); foreach (var messageSpecification in _messageSpecifications.Values) messageSpecification.AddPipeSpecification(specification); } } public ConnectHandle ConnectConsumerConfigurationObserver(IConsumerConfigurationObserver observer) { return _consumerObservers.Connect(observer); } public ConnectHandle ConnectSagaConfigurationObserver(ISagaConfigurationObserver observer) { return _sagaObservers.Connect(observer); } public ConnectHandle ConnectHandlerConfigurationObserver(IHandlerConfigurationObserver observer) { return _handlerObservers.Connect(observer); } public void AddPipeSpecification<T>(IPipeSpecification<ConsumeContext<T>> specification) where T : class { IMessageConsumePipeSpecification<T> messageSpecification = GetMessageSpecification<T>(); messageSpecification.AddPipeSpecification(specification); } public void AddPrePipeSpecification(IPipeSpecification<ConsumeContext> specification) { _consumeContextSpecifications.Add(specification); } public void ConsumerConfigured<TConsumer>(IConsumerConfigurator<TConsumer> configurator) where TConsumer : class { _consumerObservers.ConsumerConfigured(configurator); } public void ConsumerMessageConfigured<TConsumer, TMessage>(IConsumerMessageConfigurator<TConsumer, TMessage> configurator) where TConsumer : class where TMessage : class { _consumerObservers.ConsumerMessageConfigured(configurator); } public void SagaConfigured<TSaga>(ISagaConfigurator<TSaga> configurator) where TSaga : class, ISaga { _sagaObservers.SagaConfigured(configurator); } public void SagaMessageConfigured<TSaga, TMessage>(ISagaMessageConfigurator<TSaga, TMessage> configurator) where TSaga : class, ISaga where TMessage : class { _sagaObservers.SagaMessageConfigured(configurator); } public void HandlerConfigured<TMessage>(IHandlerConfigurator<TMessage> configurator) where TMessage : class { _handlerObservers.HandlerConfigured(configurator); } public IEnumerable<ValidationResult> Validate() { return _specifications.SelectMany(x => x.Validate()) .Concat(_messageSpecifications.Values.SelectMany(x => x.Validate())); } public IMessageConsumePipeSpecification<T> GetMessageSpecification<T>() where T : class { var specification = _messageSpecifications.GetOrAdd(typeof(T), CreateMessageSpecification<T>); return specification.GetMessageSpecification<T>(); } public ConnectHandle Connect(IConsumePipeSpecificationObserver observer) { return _observers.Connect(observer); } public IConsumePipe BuildConsumePipe() { var filter = new DynamicFilter<ConsumeContext, Guid>(new ConsumeContextConverterFactory(), GetRequestId); foreach (var specification in _messageSpecifications.Values) specification.Connect(filter); var builder = new PipeBuilder<ConsumeContext>(); foreach (IPipeSpecification<ConsumeContext> specification in _consumeContextSpecifications) specification.Apply(builder); builder.AddFilter(filter); return new ConsumePipe(filter, builder.Build()); } static Guid GetRequestId(ConsumeContext context) { return context.RequestId ?? Guid.Empty; } IMessageConsumePipeSpecification CreateMessageSpecification<T>(Type type) where T : class { var specification = new MessageConsumePipeSpecification<T>(); foreach (IPipeSpecification<ConsumeContext> pipeSpecification in _specifications) specification.AddPipeSpecification(pipeSpecification); _observers.MessageSpecificationCreated(specification); var connector = new ImplementedMessageTypeConnector<T>(this, specification); ImplementedMessageTypeCache<T>.EnumerateImplementedTypes(connector); return specification; } class ImplementedMessageTypeConnector<TMessage> : IImplementedMessageType where TMessage : class { readonly MessageConsumePipeSpecification<TMessage> _messageSpecification; readonly IConsumePipeSpecification _specification; public ImplementedMessageTypeConnector(IConsumePipeSpecification specification, MessageConsumePipeSpecification<TMessage> messageSpecification) { _specification = specification; _messageSpecification = messageSpecification; } public void ImplementsMessageType<T>(bool direct) where T : class { IMessageConsumePipeSpecification<T> implementedTypeSpecification = _specification.GetMessageSpecification<T>(); _messageSpecification.AddImplementedMessageSpecification(implementedTypeSpecification); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // X509Certificate.cs // namespace System.Security.Cryptography.X509Certificates { using Microsoft.Win32; using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Util; using System.Text; using System.Runtime.Versioning; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public enum X509ContentType { Unknown = 0x00, Cert = 0x01 #if !FEATURE_CORECLR , SerializedCert = 0x02, #if !FEATURE_PAL Pfx = 0x03, Pkcs12 = Pfx, #endif // !FEATURE_PAL SerializedStore = 0x04, Pkcs7 = 0x05, Authenticode = 0x06 #endif // !FEATURE_CORECLR } // DefaultKeySet, UserKeySet and MachineKeySet are mutually exclusive [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum X509KeyStorageFlags { DefaultKeySet = 0x00 #if !FEATURE_CORECLR , UserKeySet = 0x01, MachineKeySet = 0x02, Exportable = 0x04, UserProtected = 0x08, PersistKeySet = 0x10 #endif // !FEATURE_CORECLR } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class X509Certificate : IDeserializationCallback, ISerializable { private const string m_format = "X509"; private string m_subjectName; private string m_issuerName; private byte[] m_serialNumber; private byte[] m_publicKeyParameters; private byte[] m_publicKeyValue; private string m_publicKeyOid; private byte[] m_rawData; private byte[] m_thumbprint; private DateTime m_notBefore; private DateTime m_notAfter; [System.Security.SecurityCritical] // auto-generated private SafeCertContextHandle m_safeCertContext; private bool m_certContextCloned = false; // // public constructors // [System.Security.SecuritySafeCritical] // auto-generated private void Init() { m_safeCertContext = SafeCertContextHandle.InvalidHandle; } public X509Certificate () { Init(); } public X509Certificate (byte[] data):this() { if ((data != null) && (data.Length != 0)) LoadCertificateFromBlob(data, null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate (byte[] rawData, string password):this() { #if FEATURE_LEGACYNETCF if ((rawData != null) && (rawData.Length != 0)) { #endif LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet); #if FEATURE_LEGACYNETCF } #endif } #if FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, SecureString password):this() { LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet); } #endif // FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags):this() { #if FEATURE_LEGACYNETCF if ((rawData != null) && (rawData.Length != 0)) { #endif LoadCertificateFromBlob(rawData, password, keyStorageFlags); #if FEATURE_LEGACYNETCF } #endif } #if FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate (string fileName):this() { LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate (string fileName, string password):this() { LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate (string fileName, SecureString password):this() { LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet); } #endif // FEATURE_X509_SECURESTRINGS #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate (string fileName, string password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromFile(fileName, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromFile(fileName, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS // Package protected constructor for creating a certificate from a PCCERT_CONTEXT [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif public X509Certificate (IntPtr handle):this() { if (handle == IntPtr.Zero) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle"); Contract.EndContractBlock(); X509Utils._DuplicateCertContext(handle, ref m_safeCertContext); } [System.Security.SecuritySafeCritical] // auto-generated public X509Certificate (X509Certificate cert):this() { if (cert == null) throw new ArgumentNullException("cert"); Contract.EndContractBlock(); if (cert.m_safeCertContext.pCertContext != IntPtr.Zero) { m_safeCertContext = cert.GetCertContextForCloning(); m_certContextCloned = true; } } public X509Certificate (SerializationInfo info, StreamingContext context):this() { byte[] rawData = (byte[]) info.GetValue("RawData", typeof(byte[])); if (rawData != null) LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static X509Certificate CreateFromCertFile (string filename) { return new X509Certificate(filename); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static X509Certificate CreateFromSignedFile (string filename) { return new X509Certificate(filename); } [System.Runtime.InteropServices.ComVisible(false)] public IntPtr Handle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif get { return m_safeCertContext.pCertContext; } } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { ThrowIfContextInvalid(); return X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, true); } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { ThrowIfContextInvalid(); return X509Utils._GetIssuerName(m_safeCertContext, true); } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetSerialNumber() { ThrowIfContextInvalid(); if (m_serialNumber == null) m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext); return (byte[]) m_serialNumber.Clone(); } public virtual string GetSerialNumberString() { return SerialNumber; } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfContextInvalid(); if (m_publicKeyParameters == null) m_publicKeyParameters = X509Utils._GetPublicKeyParameters(m_safeCertContext); return (byte[]) m_publicKeyParameters.Clone(); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string GetKeyAlgorithmParametersString() { ThrowIfContextInvalid(); return Hex.EncodeHexString(GetKeyAlgorithmParameters()); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string GetKeyAlgorithm() { ThrowIfContextInvalid(); if (m_publicKeyOid == null) m_publicKeyOid = X509Utils._GetPublicKeyOid(m_safeCertContext); return m_publicKeyOid; } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetPublicKey() { ThrowIfContextInvalid(); if (m_publicKeyValue == null) m_publicKeyValue = X509Utils._GetPublicKeyValue(m_safeCertContext); return (byte[]) m_publicKeyValue.Clone(); } public virtual string GetPublicKeyString() { return Hex.EncodeHexString(GetPublicKey()); } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetRawCertData() { return RawData; } public virtual string GetRawCertDataString() { return Hex.EncodeHexString(GetRawCertData()); } public virtual byte[] GetCertHash() { SetThumbprint(); return (byte[]) m_thumbprint.Clone(); } public virtual string GetCertHashString() { SetThumbprint(); return Hex.EncodeHexString(m_thumbprint); } public virtual string GetEffectiveDateString() { return NotBefore.ToString(); } public virtual string GetExpirationDateString() { return NotAfter.ToString(); } [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals (Object obj) { if (!(obj is X509Certificate)) return false; X509Certificate other = (X509Certificate) obj; return this.Equals(other); } [System.Security.SecuritySafeCritical] // auto-generated public virtual bool Equals (X509Certificate other) { if (other == null) return false; if (m_safeCertContext.IsInvalid) return other.m_safeCertContext.IsInvalid; if (!this.Issuer.Equals(other.Issuer)) return false; if (!this.SerialNumber.Equals(other.SerialNumber)) return false; return true; } [System.Security.SecuritySafeCritical] // auto-generated public override int GetHashCode() { if (m_safeCertContext.IsInvalid) return 0; SetThumbprint(); int value = 0; for (int i = 0; i < m_thumbprint.Length && i < 4; ++i) { value = value << 8 | m_thumbprint[i]; } return value; } public override string ToString() { return ToString(false); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string ToString (bool fVerbose) { if (fVerbose == false || m_safeCertContext.IsInvalid) return GetType().FullName; StringBuilder sb = new StringBuilder(); // Subject sb.Append("[Subject]" + Environment.NewLine + " "); sb.Append(this.Subject); // Issuer sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + " "); sb.Append(this.Issuer); // Serial Number sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + " "); sb.Append(this.SerialNumber); // NotBefore sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + " "); sb.Append(FormatDate(this.NotBefore)); // NotAfter sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + " "); sb.Append(FormatDate(this.NotAfter)); // Thumbprint sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + " "); sb.Append(this.GetCertHashString()); sb.Append(Environment.NewLine); return sb.ToString(); } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these these cases, we need to fall back to a calendar which can express the dates /// </summary> protected static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { #if !FEATURE_ONLY_CORE_CALENDARS // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else #endif // !FEATURE_ONLY_CORE_CALENDARS { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } public virtual string GetFormat() { return m_format; } public string Issuer { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_issuerName == null) m_issuerName = X509Utils._GetIssuerName(m_safeCertContext, false); return m_issuerName; } } public string Subject { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_subjectName == null) m_subjectName = X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, false); return m_subjectName; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #else [System.Security.SecurityCritical] #endif // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(byte[] rawData) { Reset(); LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #else [System.Security.SecurityCritical] #endif // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(string fileName) { Reset(); LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet); } [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromFile(fileName, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromFile(fileName, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public virtual byte[] Export(X509ContentType contentType) { return ExportHelper(contentType, null); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public virtual byte[] Export(X509ContentType contentType, string password) { return ExportHelper(contentType, password); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] Export(X509ContentType contentType, SecureString password) { return ExportHelper(contentType, password); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Reset () { m_subjectName = null; m_issuerName = null; m_serialNumber = null; m_publicKeyParameters = null; m_publicKeyValue = null; m_publicKeyOid = null; m_rawData = null; m_thumbprint = null; m_notBefore = DateTime.MinValue; m_notAfter = DateTime.MinValue; if (!m_safeCertContext.IsInvalid) { // Free the current certificate handle if (!m_certContextCloned) { m_safeCertContext.Dispose(); } m_safeCertContext = SafeCertContextHandle.InvalidHandle; } m_certContextCloned = false; } #if FEATURE_SERIALIZATION /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { if (m_safeCertContext.IsInvalid) info.AddValue("RawData", null); else info.AddValue("RawData", this.RawData); } /// <internalonly/> void IDeserializationCallback.OnDeserialization(Object sender) {} #endif // // internal. // internal SafeCertContextHandle CertContext { [System.Security.SecurityCritical] // auto-generated get { return m_safeCertContext; } } /// <summary> /// Returns the SafeCertContextHandle. Use this instead of the CertContext property when /// creating another X509Certificate object based on this one to ensure the underlying /// cert context is not released at the wrong time. /// </summary> [System.Security.SecurityCritical] internal SafeCertContextHandle GetCertContextForCloning() { m_certContextCloned = true; return m_safeCertContext; } // // private methods. // [System.Security.SecurityCritical] // auto-generated private void ThrowIfContextInvalid() { if (m_safeCertContext.IsInvalid) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHandle"), "m_safeCertContext"); } private DateTime NotAfter { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_notAfter == DateTime.MinValue) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(); X509Utils._GetDateNotAfter(m_safeCertContext, ref fileTime); m_notAfter = DateTime.FromFileTime(fileTime.ToTicks()); } return m_notAfter; } } private DateTime NotBefore { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_notBefore == DateTime.MinValue) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(); X509Utils._GetDateNotBefore(m_safeCertContext, ref fileTime); m_notBefore = DateTime.FromFileTime(fileTime.ToTicks()); } return m_notBefore; } } private byte[] RawData { [System.Security.SecurityCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_rawData == null) m_rawData = X509Utils._GetCertRawData(m_safeCertContext); return (byte[]) m_rawData.Clone(); } } private string SerialNumber { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_serialNumber == null) m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext); return Hex.EncodeHexStringFromInt(m_serialNumber); } } [System.Security.SecuritySafeCritical] // auto-generated private void SetThumbprint () { ThrowIfContextInvalid(); if (m_thumbprint == null) m_thumbprint = X509Utils._GetThumbprint(m_safeCertContext); } [System.Security.SecurityCritical] // auto-generated private byte[] ExportHelper (X509ContentType contentType, object password) { switch(contentType) { case X509ContentType.Cert: break; #if FEATURE_CORECLR case (X509ContentType)0x02 /* X509ContentType.SerializedCert */: case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"), new NotSupportedException()); #else // FEATURE_CORECLR case X509ContentType.SerializedCert: break; #if !FEATURE_PAL case X509ContentType.Pkcs12: KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); break; #endif // !FEATURE_PAL #endif // FEATURE_CORECLR else default: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType")); } #if !FEATURE_CORECLR IntPtr szPassword = IntPtr.Zero; byte[] encodedRawData = null; SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this); RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); safeCertStoreHandle.Dispose(); } if (encodedRawData == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed")); return encodedRawData; #else // !FEATURE_CORECLR return RawData; #endif // !FEATURE_CORECLR } [System.Security.SecuritySafeCritical] // auto-generated private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData"); Contract.EndContractBlock(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData)); #if !FEATURE_CORECLR && !FEATURE_PAL if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR && !FEATURE_PAL uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromBlob(rawData, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); string fullPath = Path.GetFullPathInternal(fileName); new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName)); #if !FEATURE_CORECLR && !FEATURE_PAL if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR && !FEATURE_PAL uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromFile(fileName, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } } #if FEATURE_LEGACYNETCF protected internal String CreateHexString(byte[] sArray) { return Hex.EncodeHexString(sArray); } #endif } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class GameManager { #region STATIC_ENUM_CONSTANTS public static readonly int MAX_TIME_IN_GAME = 600000; public static readonly string CHARACTER_GO_TAG = "Player"; public enum GAME_MODE{ NORMAL = 0, MODE_AR = 1 } #endregion #region FIELDS public event Action onEndGame = delegate { }; private Game currentGame; private GameStats currentGameStats; private GameObject characterGO; private GAME_MODE gameMode; private bool pauseFlag; private bool finishGameFlag; private bool winFlag = false; private CoroutineTask timeTask; private static GameManager instance = null; #endregion #region ACCESSORS public Game CurrentGame{ get{ if (currentGame == null){ currentGame = new Game(); currentGameStats = new GameStats(); Console.Warning("GAME IN EDIT MODE..."); } return currentGame; } } public bool IsPaused { get { return pauseFlag; } } public GameObject Character{ get{ return characterGO; } set{ characterGO = value; } } public GAME_MODE GameMode{ get { return gameMode; } set { gameMode = value; } } public int TimeGame{ get{ if (currentGameStats == null) { return 0; } else { return currentGameStats.timeGame; } } } public int Plasma { get { if (currentGameStats == null) { return 0; } else { return currentGameStats.plasma; } } } public int TotalSpiderKilled { get { return currentGameStats.totalSpiderKilled; } } public int TotalWaspKilled { get { return currentGameStats.totalWaspKilled; } } public bool WinGame{ get { return winFlag; } } public bool FinishedGame { get { return finishGameFlag; } } public static GameManager Instance{ get{ if (instance == null){ instance = new GameManager(); } return instance; } } #endregion #region METHODS_CONSTRUCTORS private GameManager(){} #endregion #region METHODS_CUSTOM public void SetGame(Game game){ currentGame = game; } public void StartGame(){ timeTask = TaskManager.Launch(TimeCounter()); finishGameFlag = false; winFlag = false; pauseFlag = false; characterGO = GameObject.FindGameObjectWithTag(CHARACTER_GO_TAG); ResetStats(); } public void ResetStats(){ currentGameStats = new GameStats (); } public void EnemyDestroyed(EnemyController.ENEMY_TYPE enemyType){ currentGameStats.totalEnemyDestroyed++; if (enemyType == EnemyController.ENEMY_TYPE.SPIDER) { currentGameStats.totalSpiderKilled++; } else { currentGameStats.totalWaspKilled++; } } public void AddPlasma(int plasma) { System.TimeSpan timeSpan = System.TimeSpan.FromMilliseconds ((double)currentGameStats.timeGame); currentGameStats.plasma += plasma * (timeSpan.Minutes+1); } public void Pause(){ if (pauseFlag) { pauseFlag = false; Time.timeScale = 1; } else { pauseFlag = true; Time.timeScale = 0; } } public void GameWin(){ Debug.Log("Gana el jugador"); winFlag = true; timeTask.Stop (); finishGameFlag = true; RootApp.Instance.ChangeState (StateReferenceApp.TYPE_STATE.END); } public void GameFail(){ if (!winFlag) { Debug.Log("Pierde el jugador"); winFlag = false; timeTask.Stop (); finishGameFlag = true; onEndGame(); AudioManager.Instance.StopFXSound(AudioManager.MOVE_TOWER); RootApp.Instance.ChangeState (StateReferenceApp.TYPE_STATE.END); } } private IEnumerator TimeCounter(){ while (true) { yield return new WaitForSeconds(0.1f); currentGameStats.timeGame += 100; if (currentGameStats.timeGame >= MAX_TIME_IN_GAME) { GameWin(); } } } #endregion #region METHODS_EVENT #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA2016: Forward CancellationToken to invocations. /// /// Conditions for positive cases: /// - The containing method signature receives a ct parameter. It can be a method, a nested method, an action or a func. /// - The invocation method is not receiving a ct argument, and... /// - The invocation method either: /// - Has no overloads but its current signature receives an optional ct=default, currently implicit, or... /// - Has a method overload with the exact same arguments in the same order, plus one ct parameter at the end. /// /// Conditions for negative cases: /// - The containing method signature does not receive a ct parameter. /// - The invocation method signature receives a ct and one is already being explicitly passed, or... /// - The invocation method does not have an overload with the exact same arguments that also receives a ct, or... /// - The invocation method only has overloads that receive more than one ct. /// </summary> public abstract class ForwardCancellationTokenToInvocationsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2016"; // Try to get the name of the method from the specified invocation protected abstract SyntaxNode? GetInvocationMethodNameNode(SyntaxNode invocationNode); // Check if any of the other arguments is implicit or a named argument protected abstract bool ArgumentsImplicitOrNamed(INamedTypeSymbol cancellationTokenType, ImmutableArray<IArgumentOperation> arguments); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ForwardCancellationTokenToInvocationsDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ForwardCancellationTokenToInvocationsMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ForwardCancellationTokenToInvocationsTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor ForwardCancellationTokenToInvocationsRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Reliability, RuleLevel.IdeSuggestion, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false ); internal const string ShouldFix = "ShouldFix"; internal const string ArgumentName = "ArgumentName"; internal const string ParameterName = "ParameterName"; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ForwardCancellationTokenToInvocationsRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(context => AnalyzeCompilationStart(context)); } private void AnalyzeCompilationStart(CompilationStartAnalysisContext context) { if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken, out INamedTypeSymbol? cancellationTokenType)) { return; } context.RegisterOperationAction(context => { IInvocationOperation invocation = (IInvocationOperation)context.Operation; if (context.ContainingSymbol is not IMethodSymbol containingMethod) { return; } if (!ShouldDiagnose( invocation, containingMethod, cancellationTokenType, out int shouldFix, out string? cancellationTokenArgumentName, out string? invocationTokenParameterName)) { return; } // Underline only the method name, if possible SyntaxNode? nodeToDiagnose = GetInvocationMethodNameNode(context.Operation.Syntax) ?? context.Operation.Syntax; ImmutableDictionary<string, string?>.Builder properties = ImmutableDictionary.CreateBuilder<string, string?>(StringComparer.Ordinal); properties.Add(ShouldFix, $"{shouldFix}"); properties.Add(ArgumentName, cancellationTokenArgumentName); // The new argument to pass to the invocation properties.Add(ParameterName, invocationTokenParameterName); // If the passed argument should be named, then this will be non-null context.ReportDiagnostic( nodeToDiagnose.CreateDiagnostic( rule: ForwardCancellationTokenToInvocationsRule, properties: properties.ToImmutable(), args: new object[] { cancellationTokenArgumentName, invocation.TargetMethod.Name })); }, OperationKind.Invocation); } // Determines if an invocation should trigger a diagnostic for this rule or not. private bool ShouldDiagnose( IInvocationOperation invocation, IMethodSymbol containingSymbol, INamedTypeSymbol cancellationTokenType, out int shouldFix, [NotNullWhen(returnValue: true)] out string? ancestorTokenParameterName, out string? invocationTokenParameterName) { shouldFix = 1; ancestorTokenParameterName = null; invocationTokenParameterName = null; IMethodSymbol method = invocation.TargetMethod; // Verify that the current invocation is not passing an explicit token already if (AnyArgument(invocation.Arguments, a => a.Parameter.Type.Equals(cancellationTokenType) && !a.IsImplicit)) { return false; } IMethodSymbol? overload = null; // Check if the invocation's method has either an optional implicit ct at the end not being used, or a params ct parameter at the end not being used if (InvocationMethodTakesAToken(method, invocation.Arguments, cancellationTokenType)) { if (ArgumentsImplicitOrNamed(cancellationTokenType, invocation.Arguments)) { invocationTokenParameterName = method.Parameters[^1].Name; } } // or an overload that takes a ct at the end else if (MethodHasCancellationTokenOverload(method, cancellationTokenType, out overload)) { if (ArgumentsImplicitOrNamed(cancellationTokenType, invocation.Arguments)) { invocationTokenParameterName = overload.Parameters[^1].Name; } } else { return false; } // Check if there is an ancestor method that has a ct that we can pass to the invocation if (!TryGetClosestAncestorThatTakesAToken( invocation, containingSymbol, cancellationTokenType, out shouldFix, out IMethodSymbol? ancestor, out ancestorTokenParameterName)) { return false; } // Finally, if the ct is in an overload method, but adding the ancestor's ct to the current // invocation would cause the new signature to become a recursive call, avoid creating a diagnostic if (overload != null && overload == ancestor) { ancestorTokenParameterName = null; return false; } return true; } // Try to find the most immediate containing symbol (anonymous or local function). Returns true. // If none is found, return the context containing symbol. Returns false. private static bool TryGetClosestAncestorThatTakesAToken( IInvocationOperation invocation, IMethodSymbol containingSymbol, INamedTypeSymbol cancellationTokenType, out int shouldFix, [NotNullWhen(returnValue: true)] out IMethodSymbol? ancestor, [NotNullWhen(returnValue: true)] out string? cancellationTokenParameterName) { shouldFix = 1; IOperation currentOperation = invocation.Parent; while (currentOperation != null) { ancestor = null; if (currentOperation.Kind == OperationKind.AnonymousFunction) { ancestor = ((IAnonymousFunctionOperation)currentOperation).Symbol; } else if (currentOperation.Kind == OperationKind.LocalFunction) { ancestor = ((ILocalFunctionOperation)currentOperation).Symbol; } // When the current ancestor does not contain a ct, will continue with the next ancestor if (ancestor != null) { if (TryGetTokenParamName(ancestor, cancellationTokenType, out cancellationTokenParameterName)) { return true; } // If no token param was found in the previous check, return false if the current operation is an anonymous function, // we don't want to keep checking the superior ancestors because the ct may be unrelated if (currentOperation.Kind == OperationKind.AnonymousFunction) { return false; } // If the current operation is a local static function, and is not passing a ct, but the parent is, then the // ct cannot be passed to the inner invocations of the static local method, but we want to continue trying // to find the ancestor method passing a ct so that we still trigger a diagnostic, we just won't offer a fix if (currentOperation.Kind == OperationKind.LocalFunction && ancestor.IsStatic) { shouldFix = 0; } } currentOperation = currentOperation.Parent; } // Last resort: fallback to the containing symbol ancestor = containingSymbol; return TryGetTokenParamName(ancestor, cancellationTokenType, out cancellationTokenParameterName); } // Check if the method only takes one ct and is the last parameter in the method signature. // We want to compare the current method signature to any others with the exact same arguments in the exact same order. private static bool TryGetTokenParamName( IMethodSymbol methodDeclaration, INamedTypeSymbol cancellationTokenType, [NotNullWhen(returnValue: true)] out string? cancellationTokenParameterName) { if (methodDeclaration.Parameters.Count(x => x.Type.Equals(cancellationTokenType)) == 1 && methodDeclaration.Parameters[^1] is IParameterSymbol lastParameter && lastParameter.Type.Equals(cancellationTokenType)) // Covers the case when using an alias for ct { cancellationTokenParameterName = lastParameter.Name; return true; } cancellationTokenParameterName = null; return false; } // Checks if the invocation has an optional ct argument at the end or a params ct array at the end. private static bool InvocationMethodTakesAToken( IMethodSymbol method, ImmutableArray<IArgumentOperation> arguments, INamedTypeSymbol cancellationTokenType) { return !method.Parameters.IsEmpty && method.Parameters[^1] is IParameterSymbol lastParameter && (InvocationIgnoresOptionalCancellationToken(lastParameter, arguments, cancellationTokenType) || InvocationIsUsingParamsCancellationToken(lastParameter, arguments, cancellationTokenType)); } // Checks if the arguments enumerable has any elements that satisfy the provided condition, // starting the lookup with the last element since tokens tend to be added as the last argument. private static bool AnyArgument(ImmutableArray<IArgumentOperation> arguments, Func<IArgumentOperation, bool> predicate) { for (int i = arguments.Length - 1; i >= 0; i--) { if (predicate(arguments[i])) { return true; } } return false; } // Check if the currently used overload is the one that takes the ct, but is utilizing the default value offered in the method signature. // We want to offer a diagnostic for this case, so the user explicitly passes the ancestor's ct. private static bool InvocationIgnoresOptionalCancellationToken( IParameterSymbol lastParameter, ImmutableArray<IArgumentOperation> arguments, INamedTypeSymbol cancellationTokenType) { if (lastParameter.Type.Equals(cancellationTokenType) && lastParameter.IsOptional) // Has a default value being used { // Find out if the ct argument is using the default value // Need to check among all arguments in case the user is passing them named and unordered (despite the ct being defined as the last parameter) return AnyArgument( arguments, a => a.Parameter.Type.Equals(cancellationTokenType) && a.ArgumentKind == ArgumentKind.DefaultValue); } return false; } // Checks if the method has a `params CancellationToken[]` argument in the last position and ensure no ct is being passed. private static bool InvocationIsUsingParamsCancellationToken( IParameterSymbol lastParameter, ImmutableArray<IArgumentOperation> arguments, INamedTypeSymbol cancellationTokenType) { if (lastParameter.IsParams && lastParameter.Type is IArrayTypeSymbol arrayTypeSymbol && arrayTypeSymbol.ElementType.Equals(cancellationTokenType)) { IArgumentOperation? paramsArgument = arguments.FirstOrDefault(a => a.ArgumentKind == ArgumentKind.ParamArray); if (paramsArgument?.Value is IArrayCreationOperation arrayOperation) { // Do not offer a diagnostic if the user already passed a ct to the params return arrayOperation.Initializer.ElementValues.IsEmpty; } } return false; } // Check if there's a method overload with the same parameters as this one, in the same order, plus a ct at the end. private static bool MethodHasCancellationTokenOverload( IMethodSymbol method, ITypeSymbol cancellationTokenType, [NotNullWhen(returnValue: true)] out IMethodSymbol? overload) { overload = method.ContainingType .GetMembers(method.Name) .OfType<IMethodSymbol>() .FirstOrDefault(methodToCompare => HasSameParametersPlusCancellationToken(cancellationTokenType, method, methodToCompare)); return overload != null; // Checks if the parameters of the two passed methods only differ in a ct. static bool HasSameParametersPlusCancellationToken(ITypeSymbol cancellationTokenType, IMethodSymbol originalMethod, IMethodSymbol methodToCompare) { // Avoid comparing to itself, or when there are no parameters, or when the last parameter is not a ct if (originalMethod.Equals(methodToCompare) || methodToCompare.Parameters.Count(p => p.Type.Equals(cancellationTokenType)) != 1 || !methodToCompare.Parameters[^1].Type.Equals(cancellationTokenType)) { return false; } IMethodSymbol originalMethodWithAllParameters = (originalMethod.ReducedFrom ?? originalMethod).OriginalDefinition; IMethodSymbol methodToCompareWithAllParameters = (methodToCompare.ReducedFrom ?? methodToCompare).OriginalDefinition; // Ensure parameters only differ by one - the ct if (originalMethodWithAllParameters.Parameters.Length != methodToCompareWithAllParameters.Parameters.Length - 1) { return false; } // Now compare the types of all parameters before the ct // The largest i is the number of parameters in the method that has fewer parameters for (int i = 0; i < originalMethodWithAllParameters.Parameters.Length; i++) { IParameterSymbol originalParameter = originalMethodWithAllParameters.Parameters[i]; IParameterSymbol comparedParameter = methodToCompareWithAllParameters.Parameters[i]; if (!originalParameter.Type.Equals(comparedParameter.Type)) { return false; } } return true; } } } }
// // UnityOSC - Open Sound Control interface for the Unity3d game engine // // Copyright (c) 2012 Jorge Garcia Martin // // 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. // // Inspired by http://www.unifycommunity.com/wiki/index.php?title=AManagerClass using System; using System.Net; using System.Collections.Generic; using UnityEngine; using UnityOSC; /// <summary> /// Models a log of a server composed by an OSCServer, a List of OSCPacket and a List of /// strings that represent the current messages in the log. /// </summary> public struct ServerLog { public OSCServer server; public List<OSCPacket> packets; public List<string> log; } /// <summary> /// Models a log of a client composed by an OSCClient, a List of OSCMessage and a List of /// strings that represent the current messages in the log. /// </summary> public struct ClientLog { public OSCClient client; public List<OSCMessage> messages; public List<string> log; } /// <summary> /// Handles all the OSC servers and clients of the current Unity game/application. /// Tracks incoming and outgoing messages. /// </summary> public class OSCHandler : MonoBehaviour { #region Singleton Constructors static OSCHandler() { } OSCHandler() { } public static OSCHandler Instance { get { if (_instance == null) { _instance = new GameObject ("OSCHandler").AddComponent<OSCHandler>(); } return _instance; } } #endregion #region Member Variables private static OSCHandler _instance = null; private Dictionary<string, ClientLog> _clients = new Dictionary<string, ClientLog>(); private Dictionary<string, ServerLog> _servers = new Dictionary<string, ServerLog>(); private const int _loglength = 25; #endregion /// <summary> /// Initializes the OSC Handler. /// Here you can create the OSC servers and clientes. /// </summary> public void Init() { //Initialize OSC clients (transmitters) //Example: CreateClient("SoundControl", IPAddress.Parse("169.254.187.186"), 4444); //Initialize OSC servers (listeners) //Example: //CreateServer("SoundControl", 6666); } #region Properties public Dictionary<string, ClientLog> Clients { get { return _clients; } } public Dictionary<string, ServerLog> Servers { get { return _servers; } } #endregion #region Methods /// <summary> /// Ensure that the instance is destroyed when the game is stopped in the Unity editor /// Close all the OSC clients and servers /// </summary> void OnApplicationQuit() { foreach(KeyValuePair<string,ClientLog> pair in _clients) { pair.Value.client.Close(); } foreach(KeyValuePair<string,ServerLog> pair in _servers) { pair.Value.server.Close(); } _instance = null; } /// <summary> /// Creates an OSC Client (sends OSC messages) given an outgoing port and address. /// </summary> /// <param name="clientId"> /// A <see cref="System.String"/> /// </param> /// <param name="destination"> /// A <see cref="IPAddress"/> /// </param> /// <param name="port"> /// A <see cref="System.Int32"/> /// </param> public void CreateClient(string clientId, IPAddress destination, int port) { ClientLog clientitem = new ClientLog(); clientitem.client = new OSCClient(destination, port); clientitem.log = new List<string>(); clientitem.messages = new List<OSCMessage>(); _clients.Add(clientId, clientitem); // Send test message string testaddress = "/test/alive/"; OSCMessage message = new OSCMessage(testaddress, destination.ToString()); message.Append(port); message.Append("OK"); _clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".", FormatMilliseconds(DateTime.Now.Millisecond), " : ", testaddress," ", DataToString(message.Data))); _clients[clientId].messages.Add(message); _clients[clientId].client.Send(message); } /// <summary> /// Creates an OSC Server (listens to upcoming OSC messages) given an incoming port. /// </summary> /// <param name="serverId"> /// A <see cref="System.String"/> /// </param> /// <param name="port"> /// A <see cref="System.Int32"/> /// </param> public void CreateServer(string serverId, int port) { OSCServer server = new OSCServer(port); server.PacketReceivedEvent += OnPacketReceived; ServerLog serveritem = new ServerLog(); serveritem.server = server; serveritem.log = new List<string>(); serveritem.packets = new List<OSCPacket>(); _servers.Add(serverId, serveritem); } void OnPacketReceived(OSCServer server, OSCPacket packet) { } /// <summary> /// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction), /// OSC address and a single value. Also updates the client log. /// </summary> /// <param name="clientId"> /// A <see cref="System.String"/> /// </param> /// <param name="address"> /// A <see cref="System.String"/> /// </param> /// <param name="value"> /// A <see cref="T"/> /// </param> public void SendMessageToClient<T>(string clientId, string address, T value) { List<object> temp = new List<object>(); temp.Add(value); SendMessageToClient(clientId, address, temp); } /// <summary> /// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction), /// OSC address and a list of values. Also updates the client log. /// </summary> /// <param name="clientId"> /// A <see cref="System.String"/> /// </param> /// <param name="address"> /// A <see cref="System.String"/> /// </param> /// <param name="values"> /// A <see cref="List<T>"/> /// </param> public void SendMessageToClient<T>(string clientId, string address, List<T> values) { if(_clients.ContainsKey(clientId)) { OSCMessage message = new OSCMessage(address); foreach(T msgvalue in values) { message.Append(msgvalue); } if(_clients[clientId].log.Count < _loglength) { _clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".", FormatMilliseconds(DateTime.Now.Millisecond), " : ", address, " ", DataToString(message.Data))); _clients[clientId].messages.Add(message); } else { _clients[clientId].log.RemoveAt(0); _clients[clientId].messages.RemoveAt(0); _clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".", FormatMilliseconds(DateTime.Now.Millisecond), " : ", address, " ", DataToString(message.Data))); _clients[clientId].messages.Add(message); } _clients[clientId].client.Send(message); } else { Debug.LogError(string.Format("Can't send OSC messages to {0}. Client doesn't exist.", clientId)); } } /// <summary> /// Updates clients and servers logs. /// </summary> public void UpdateLogs() { foreach(KeyValuePair<string,ServerLog> pair in _servers) { if(_servers[pair.Key].server.LastReceivedPacket != null) { //Initialization for the first packet received if(_servers[pair.Key].log.Count == 0) { _servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket); _servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".", FormatMilliseconds(DateTime.Now.Millisecond)," : ", _servers[pair.Key].server.LastReceivedPacket.Address," ", DataToString(_servers[pair.Key].server.LastReceivedPacket.Data))); break; } if(_servers[pair.Key].server.LastReceivedPacket.TimeStamp != _servers[pair.Key].packets[_servers[pair.Key].packets.Count - 1].TimeStamp) { if(_servers[pair.Key].log.Count > _loglength - 1) { _servers[pair.Key].log.RemoveAt(0); _servers[pair.Key].packets.RemoveAt(0); } _servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket); _servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".", FormatMilliseconds(DateTime.Now.Millisecond)," : ", _servers[pair.Key].server.LastReceivedPacket.Address," ", DataToString(_servers[pair.Key].server.LastReceivedPacket.Data))); } } } } /// <summary> /// Converts a collection of object values to a concatenated string. /// </summary> /// <param name="data"> /// A <see cref="List<System.Object>"/> /// </param> /// <returns> /// A <see cref="System.String"/> /// </returns> private string DataToString(List<object> data) { string buffer = ""; for(int i = 0; i < data.Count; i++) { buffer += data[i].ToString() + " "; } buffer += "\n"; return buffer; } /// <summary> /// Formats a milliseconds number to a 000 format. E.g. given 50, it outputs 050. Given 5, it outputs 005 /// </summary> /// <param name="milliseconds"> /// A <see cref="System.Int32"/> /// </param> /// <returns> /// A <see cref="System.String"/> /// </returns> private string FormatMilliseconds(int milliseconds) { if(milliseconds < 100) { if(milliseconds < 10) return String.Concat("00",milliseconds.ToString()); return String.Concat("0",milliseconds.ToString()); } return milliseconds.ToString(); } #endregion }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Security; using System.Xml; [ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)] abstract class PeerChannelListenerBase : TransportChannelListener, IPeerFactory { // settings passed to PeerNode IPAddress listenIPAddress; int port; PeerResolver resolver; PeerNode peerNode; PeerNodeImplementation privatePeerNode; PeerNodeImplementation.Registration registration; bool released = false; PeerSecurityManager securityManager; SecurityProtocol securityProtocol; XmlDictionaryReaderQuotas readerQuotas; ISecurityCapabilities securityCapabilities; static UriPrefixTable<ITransportManagerRegistration> transportManagerTable = new UriPrefixTable<ITransportManagerRegistration>(true); internal PeerChannelListenerBase(PeerTransportBindingElement bindingElement, BindingContext context, PeerResolver peerResolver) : base(bindingElement, context) { this.listenIPAddress = bindingElement.ListenIPAddress; this.port = bindingElement.Port; this.resolver = peerResolver; this.readerQuotas = new XmlDictionaryReaderQuotas(); BinaryMessageEncodingBindingElement encoder = context.Binding.Elements.Find<BinaryMessageEncodingBindingElement>(); if (encoder != null) encoder.ReaderQuotas.CopyTo(this.readerQuotas); else EncoderDefaults.ReaderQuotas.CopyTo(this.readerQuotas); securityManager = PeerSecurityManager.Create(bindingElement.Security, context, this.readerQuotas); this.securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context); } public IPAddress ListenIPAddress { get { return listenIPAddress; } } internal PeerNodeImplementation InnerNode { get { return peerNode != null ? peerNode.InnerNode : null; } } internal PeerNodeImplementation.Registration Registration { get { return registration; } } public PeerNodeImplementation PrivatePeerNode { get { return privatePeerNode; } set { privatePeerNode = value; } } public int Port { get { return port; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return this.readerQuotas; } } public PeerResolver Resolver { get { return resolver; } } public PeerSecurityManager SecurityManager { get { return this.securityManager; } set { this.securityManager = value; } } protected SecurityProtocol SecurityProtocol { get { return this.securityProtocol; } set { this.securityProtocol = value; } } public override string Scheme { get { return PeerStrings.Scheme; } } internal static UriPrefixTable<ITransportManagerRegistration> StaticTransportManagerTable { get { return transportManagerTable; } } internal override UriPrefixTable<ITransportManagerRegistration> TransportManagerTable { get { return transportManagerTable; } } public override T GetProperty<T>() { if (typeof(T) == typeof(PeerNode)) { return peerNode as T; } else if (typeof(T) == typeof(IOnlineStatus)) { return peerNode as T; } else if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)this.securityCapabilities; } return base.GetProperty<T>(); } protected override void OnAbort() { base.OnAbort(); if (this.State < CommunicationState.Closed && this.peerNode != null) { try { this.peerNode.InnerNode.Abort(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } } } void OnCloseCore(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); peerNode.OnClose(); peerNode.InnerNode.Close(timeoutHelper.RemainingTime()); base.OnClose(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) { OnCloseCore(timeout); } protected override void OnClosing() { base.OnClosing(); if (!this.released) { bool release = false; lock (ThisLock) { if (!this.released) { release = this.released = true; } } if (release && this.peerNode != null) { this.peerNode.InnerNode.Release(); } } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return new CompletedAsyncResult<TimeoutHelper>(timeoutHelper, callback, state); } protected override void OnEndClose(IAsyncResult result) { TimeoutHelper timeoutHelper = CompletedAsyncResult<TimeoutHelper>.End(result); OnCloseCore(timeoutHelper.RemainingTime()); } void OnOpenCore(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); peerNode.OnOpen(); peerNode.InnerNode.Open(timeoutHelper.RemainingTime(), false); } protected override void OnOpen(TimeSpan timeout) { OnOpenCore(timeout); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return new CompletedAsyncResult<TimeoutHelper>(timeoutHelper, callback, state); } protected override void OnEndOpen(IAsyncResult result) { TimeoutHelper timeoutHelper = CompletedAsyncResult<TimeoutHelper>.End(result); OnOpenCore(timeoutHelper.RemainingTime()); } protected override void OnFaulted() { OnAbort(); // Fault aborts the PeerNode } internal override IList<TransportManager> SelectTransportManagers() { //test override if (peerNode == null) { PeerNodeImplementation foundPeerNode = null; // use the private InnerNode if it has been configured and matches the channel if (privatePeerNode != null && this.Uri.Host == privatePeerNode.MeshId) { foundPeerNode = privatePeerNode; this.registration = null; } else { // find or create a InnerNode for the given Uri this.registration = new PeerNodeImplementation.Registration(this.Uri, this); foundPeerNode = PeerNodeImplementation.Get(this.Uri, registration); } // ensure that the max message size is compatible if (foundPeerNode.MaxReceivedMessageSize < MaxReceivedMessageSize) { foundPeerNode.Release(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.PeerMaxReceivedMessageSizeConflict, MaxReceivedMessageSize, foundPeerNode.MaxReceivedMessageSize, this.Uri))); } // associate with the PeerNode and open it peerNode = new PeerNode(foundPeerNode); } return null; } } [ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)] internal abstract class PeerChannelListener<TChannel, TChannelAcceptor> : PeerChannelListenerBase, IChannelListener<TChannel> where TChannel : class, IChannel where TChannelAcceptor : ChannelAcceptor<TChannel> { public PeerChannelListener(PeerTransportBindingElement bindingElement, BindingContext context, PeerResolver peerResolver) : base(bindingElement, context, peerResolver) { } protected abstract TChannelAcceptor ChannelAcceptor { get; } internal override ITransportManagerRegistration CreateTransportManagerRegistration(Uri listenUri) { return null; } public TChannel AcceptChannel() { return this.AcceptChannel(this.DefaultReceiveTimeout); } public IAsyncResult BeginAcceptChannel(AsyncCallback callback, object state) { return this.BeginAcceptChannel(this.DefaultReceiveTimeout, callback, state); } public TChannel AcceptChannel(TimeSpan timeout) { base.ThrowIfNotOpened(); return ChannelAcceptor.AcceptChannel(timeout); } public IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state) { base.ThrowIfNotOpened(); return ChannelAcceptor.BeginAcceptChannel(timeout, callback, state); } public TChannel EndAcceptChannel(IAsyncResult result) { return ChannelAcceptor.EndAcceptChannel(result); } void OnCloseCore(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.ChannelAcceptor.Close(timeoutHelper.RemainingTime()); base.OnClose(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) { OnCloseCore(timeout); } protected override void OnAbort() { if (this.ChannelAcceptor != null) this.ChannelAcceptor.Abort(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return new CompletedAsyncResult<TimeoutHelper>(timeoutHelper, callback, state); } protected override void OnEndClose(IAsyncResult result) { TimeoutHelper timeoutHelper = CompletedAsyncResult<TimeoutHelper>.End(result); OnCloseCore(timeoutHelper.RemainingTime()); } void OnOpenCore(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); CreateAcceptor(); ChannelAcceptor.Open(timeoutHelper.RemainingTime()); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); OnOpenCore(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); return new CompletedAsyncResult<TimeoutHelper>(timeoutHelper, callback, state); } protected override void OnEndOpen(IAsyncResult result) { TimeoutHelper timeoutHelper = CompletedAsyncResult<TimeoutHelper>.End(result); OnOpenCore(timeoutHelper.RemainingTime()); } protected override bool OnWaitForChannel(TimeSpan timeout) { return ChannelAcceptor.WaitForChannel(timeout); } protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state) { return ChannelAcceptor.BeginWaitForChannel(timeout, callback, state); } protected override bool OnEndWaitForChannel(IAsyncResult result) { return ChannelAcceptor.EndWaitForChannel(result); } protected abstract void CreateAcceptor(); } }
namespace Azure.Identity { public partial class AuthenticationFailedException : System.Exception { protected AuthenticationFailedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public AuthenticationFailedException(string message) { } public AuthenticationFailedException(string message, System.Exception innerException) { } } public partial class AuthenticationRecord { internal AuthenticationRecord() { } public string Authority { get { throw null; } } public string ClientId { get { throw null; } } public string HomeAccountId { get { throw null; } } public string TenantId { get { throw null; } } public string Username { get { throw null; } } public static Azure.Identity.AuthenticationRecord Deserialize(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> DeserializeAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public void Serialize(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.Tasks.Task SerializeAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AuthenticationRequiredException : Azure.Identity.CredentialUnavailableException { protected AuthenticationRequiredException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(string)) { } public AuthenticationRequiredException(string message, Azure.Core.TokenRequestContext context) : base (default(string)) { } public AuthenticationRequiredException(string message, Azure.Core.TokenRequestContext context, System.Exception innerException) : base (default(string)) { } public Azure.Core.TokenRequestContext TokenRequestContext { get { throw null; } } } public partial class AuthorizationCodeCredential : Azure.Core.TokenCredential { protected AuthorizationCodeCredential() { } public AuthorizationCodeCredential(string tenantId, string clientId, string clientSecret, string authorizationCode) { } public AuthorizationCodeCredential(string tenantId, string clientId, string clientSecret, string authorizationCode, Azure.Identity.AuthorizationCodeCredentialOptions options) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public AuthorizationCodeCredential(string tenantId, string clientId, string clientSecret, string authorizationCode, Azure.Identity.TokenCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AuthorizationCodeCredentialOptions : Azure.Identity.TokenCredentialOptions { public AuthorizationCodeCredentialOptions() { } public System.Uri RedirectUri { get { throw null; } set { } } } public static partial class AzureAuthorityHosts { public static System.Uri AzureChina { get { throw null; } } public static System.Uri AzureGermany { get { throw null; } } public static System.Uri AzureGovernment { get { throw null; } } public static System.Uri AzurePublicCloud { get { throw null; } } } public partial class AzureCliCredential : Azure.Core.TokenCredential { public AzureCliCredential() { } public AzureCliCredential(Azure.Identity.AzureCliCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AzureCliCredentialOptions : Azure.Identity.TokenCredentialOptions { public AzureCliCredentialOptions() { } public string TenantId { get { throw null; } set { } } } public partial class AzurePowerShellCredential : Azure.Core.TokenCredential { public AzurePowerShellCredential() { } public AzurePowerShellCredential(Azure.Identity.AzurePowerShellCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AzurePowerShellCredentialOptions : Azure.Identity.TokenCredentialOptions { public AzurePowerShellCredentialOptions() { } public string TenantId { get { throw null; } set { } } } public partial class ChainedTokenCredential : Azure.Core.TokenCredential { public ChainedTokenCredential(params Azure.Core.TokenCredential[] sources) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ClientAssertionCredential : Azure.Core.TokenCredential { protected ClientAssertionCredential() { } public ClientAssertionCredential(string tenantId, string clientId, System.Func<string> assertionCallback, Azure.Identity.ClientAssertionCredentialOptions options = null) { } public ClientAssertionCredential(string tenantId, string clientId, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<string>> assertionCallback, Azure.Identity.ClientAssertionCredentialOptions options = null) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ClientAssertionCredentialOptions : Azure.Identity.TokenCredentialOptions { public ClientAssertionCredentialOptions() { } } public partial class ClientCertificateCredential : Azure.Core.TokenCredential { protected ClientCertificateCredential() { } public ClientCertificateCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate) { } public ClientCertificateCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate, Azure.Identity.ClientCertificateCredentialOptions options) { } public ClientCertificateCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate, Azure.Identity.TokenCredentialOptions options) { } public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath) { } public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath, Azure.Identity.ClientCertificateCredentialOptions options) { } public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath, Azure.Identity.TokenCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ClientCertificateCredentialOptions : Azure.Identity.TokenCredentialOptions { public ClientCertificateCredentialOptions() { } public bool SendCertificateChain { get { throw null; } set { } } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } public partial class ClientSecretCredential : Azure.Core.TokenCredential { protected ClientSecretCredential() { } public ClientSecretCredential(string tenantId, string clientId, string clientSecret) { } public ClientSecretCredential(string tenantId, string clientId, string clientSecret, Azure.Identity.ClientSecretCredentialOptions options) { } public ClientSecretCredential(string tenantId, string clientId, string clientSecret, Azure.Identity.TokenCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ClientSecretCredentialOptions : Azure.Identity.TokenCredentialOptions { public ClientSecretCredentialOptions() { } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } public partial class CredentialUnavailableException : Azure.Identity.AuthenticationFailedException { protected CredentialUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(string)) { } public CredentialUnavailableException(string message) : base (default(string)) { } public CredentialUnavailableException(string message, System.Exception innerException) : base (default(string)) { } } public partial class DefaultAzureCredential : Azure.Core.TokenCredential { public DefaultAzureCredential(Azure.Identity.DefaultAzureCredentialOptions options) { } public DefaultAzureCredential(bool includeInteractiveCredentials = false) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DefaultAzureCredentialOptions : Azure.Identity.TokenCredentialOptions { public DefaultAzureCredentialOptions() { } public bool ExcludeAzureCliCredential { get { throw null; } set { } } public bool ExcludeAzurePowerShellCredential { get { throw null; } set { } } public bool ExcludeEnvironmentCredential { get { throw null; } set { } } public bool ExcludeInteractiveBrowserCredential { get { throw null; } set { } } public bool ExcludeManagedIdentityCredential { get { throw null; } set { } } public bool ExcludeSharedTokenCacheCredential { get { throw null; } set { } } public bool ExcludeVisualStudioCodeCredential { get { throw null; } set { } } public bool ExcludeVisualStudioCredential { get { throw null; } set { } } public string InteractiveBrowserCredentialClientId { get { throw null; } set { } } public string InteractiveBrowserTenantId { get { throw null; } set { } } public string ManagedIdentityClientId { get { throw null; } set { } } public Azure.Core.ResourceIdentifier ManagedIdentityResourceId { get { throw null; } set { } } public string SharedTokenCacheTenantId { get { throw null; } set { } } public string SharedTokenCacheUsername { get { throw null; } set { } } public string VisualStudioCodeTenantId { get { throw null; } set { } } public string VisualStudioTenantId { get { throw null; } set { } } } public partial class DeviceCodeCredential : Azure.Core.TokenCredential { public DeviceCodeCredential() { } public DeviceCodeCredential(Azure.Identity.DeviceCodeCredentialOptions options) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public DeviceCodeCredential(System.Func<Azure.Identity.DeviceCodeInfo, System.Threading.CancellationToken, System.Threading.Tasks.Task> deviceCodeCallback, string clientId, Azure.Identity.TokenCredentialOptions options = null) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public DeviceCodeCredential(System.Func<Azure.Identity.DeviceCodeInfo, System.Threading.CancellationToken, System.Threading.Tasks.Task> deviceCodeCallback, string tenantId, string clientId, Azure.Identity.TokenCredentialOptions options = null) { } public virtual Azure.Identity.AuthenticationRecord Authenticate(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Identity.AuthenticationRecord Authenticate(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeviceCodeCredentialOptions : Azure.Identity.TokenCredentialOptions { public DeviceCodeCredentialOptions() { } public Azure.Identity.AuthenticationRecord AuthenticationRecord { get { throw null; } set { } } public string ClientId { get { throw null; } set { } } public System.Func<Azure.Identity.DeviceCodeInfo, System.Threading.CancellationToken, System.Threading.Tasks.Task> DeviceCodeCallback { get { throw null; } set { } } public bool DisableAutomaticAuthentication { get { throw null; } set { } } public string TenantId { get { throw null; } set { } } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct DeviceCodeInfo { private object _dummy; private int _dummyPrimitive; public string ClientId { get { throw null; } } public string DeviceCode { get { throw null; } } public System.DateTimeOffset ExpiresOn { get { throw null; } } public string Message { get { throw null; } } public System.Collections.Generic.IReadOnlyCollection<string> Scopes { get { throw null; } } public string UserCode { get { throw null; } } public System.Uri VerificationUri { get { throw null; } } } public partial class EnvironmentCredential : Azure.Core.TokenCredential { public EnvironmentCredential() { } public EnvironmentCredential(Azure.Identity.TokenCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public static partial class IdentityModelFactory { public static Azure.Identity.AuthenticationRecord AuthenticationRecord(string username, string authority, string homeAccountId, string tenantId, string clientId) { throw null; } public static Azure.Identity.DeviceCodeInfo DeviceCodeInfo(string userCode, string deviceCode, System.Uri verificationUri, System.DateTimeOffset expiresOn, string message, string clientId, System.Collections.Generic.IReadOnlyCollection<string> scopes) { throw null; } } public partial class InteractiveBrowserCredential : Azure.Core.TokenCredential { public InteractiveBrowserCredential() { } public InteractiveBrowserCredential(Azure.Identity.InteractiveBrowserCredentialOptions options) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public InteractiveBrowserCredential(string clientId) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public InteractiveBrowserCredential(string tenantId, string clientId, Azure.Identity.TokenCredentialOptions options = null) { } public virtual Azure.Identity.AuthenticationRecord Authenticate(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Identity.AuthenticationRecord Authenticate(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class InteractiveBrowserCredentialOptions : Azure.Identity.TokenCredentialOptions { public InteractiveBrowserCredentialOptions() { } public Azure.Identity.AuthenticationRecord AuthenticationRecord { get { throw null; } set { } } public string ClientId { get { throw null; } set { } } public bool DisableAutomaticAuthentication { get { throw null; } set { } } public string LoginHint { get { throw null; } set { } } public System.Uri RedirectUri { get { throw null; } set { } } public string TenantId { get { throw null; } set { } } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } public partial class ManagedIdentityCredential : Azure.Core.TokenCredential { protected ManagedIdentityCredential() { } public ManagedIdentityCredential(Azure.Core.ResourceIdentifier resourceId, Azure.Identity.TokenCredentialOptions options = null) { } public ManagedIdentityCredential(string clientId = null, Azure.Identity.TokenCredentialOptions options = null) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class OnBehalfOfCredential : Azure.Core.TokenCredential { protected OnBehalfOfCredential() { } public OnBehalfOfCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate, string userAssertion) { } public OnBehalfOfCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate, string userAssertion, Azure.Identity.OnBehalfOfCredentialOptions options) { } public OnBehalfOfCredential(string tenantId, string clientId, string clientSecret, string userAssertion) { } public OnBehalfOfCredential(string tenantId, string clientId, string clientSecret, string userAssertion, Azure.Identity.OnBehalfOfCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class OnBehalfOfCredentialOptions : Azure.Identity.TokenCredentialOptions { public OnBehalfOfCredentialOptions() { } public bool SendCertificateChain { get { throw null; } set { } } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } public partial class SharedTokenCacheCredential : Azure.Core.TokenCredential { public SharedTokenCacheCredential() { } public SharedTokenCacheCredential(Azure.Identity.SharedTokenCacheCredentialOptions options) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public SharedTokenCacheCredential(string username, Azure.Identity.TokenCredentialOptions options = null) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class SharedTokenCacheCredentialOptions : Azure.Identity.TokenCredentialOptions { public SharedTokenCacheCredentialOptions() { } public SharedTokenCacheCredentialOptions(Azure.Identity.TokenCachePersistenceOptions tokenCacheOptions) { } public Azure.Identity.AuthenticationRecord AuthenticationRecord { get { throw null; } set { } } public string ClientId { get { throw null; } set { } } public bool EnableGuestTenantAuthentication { get { throw null; } set { } } public string TenantId { get { throw null; } set { } } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } } public string Username { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct TokenCacheData { private object _dummy; private int _dummyPrimitive; public TokenCacheData(System.ReadOnlyMemory<byte> cacheBytes) { throw null; } public System.ReadOnlyMemory<byte> CacheBytes { get { throw null; } } } public partial class TokenCachePersistenceOptions { public TokenCachePersistenceOptions() { } public string Name { get { throw null; } set { } } public bool UnsafeAllowUnencryptedStorage { get { throw null; } set { } } } public partial class TokenCacheRefreshArgs { internal TokenCacheRefreshArgs() { } public string SuggestedCacheKey { get { throw null; } } } public partial class TokenCacheUpdatedArgs { internal TokenCacheUpdatedArgs() { } public System.ReadOnlyMemory<byte> UnsafeCacheData { get { throw null; } } } public partial class TokenCredentialOptions : Azure.Core.ClientOptions { public TokenCredentialOptions() { } public System.Uri AuthorityHost { get { throw null; } set { } } } public abstract partial class UnsafeTokenCacheOptions : Azure.Identity.TokenCachePersistenceOptions { protected UnsafeTokenCacheOptions() { } protected internal abstract System.Threading.Tasks.Task<System.ReadOnlyMemory<byte>> RefreshCacheAsync(); protected internal virtual System.Threading.Tasks.Task<Azure.Identity.TokenCacheData> RefreshCacheAsync(Azure.Identity.TokenCacheRefreshArgs args, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected internal abstract System.Threading.Tasks.Task TokenCacheUpdatedAsync(Azure.Identity.TokenCacheUpdatedArgs tokenCacheUpdatedArgs); } public partial class UsernamePasswordCredential : Azure.Core.TokenCredential { protected UsernamePasswordCredential() { } public UsernamePasswordCredential(string username, string password, string tenantId, string clientId) { } public UsernamePasswordCredential(string username, string password, string tenantId, string clientId, Azure.Identity.TokenCredentialOptions options) { } public UsernamePasswordCredential(string username, string password, string tenantId, string clientId, Azure.Identity.UsernamePasswordCredentialOptions options) { } public virtual Azure.Identity.AuthenticationRecord Authenticate(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Identity.AuthenticationRecord Authenticate(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Identity.AuthenticationRecord> AuthenticateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class UsernamePasswordCredentialOptions : Azure.Identity.TokenCredentialOptions { public UsernamePasswordCredentialOptions() { } public Azure.Identity.TokenCachePersistenceOptions TokenCachePersistenceOptions { get { throw null; } set { } } } public partial class VisualStudioCodeCredential : Azure.Core.TokenCredential { public VisualStudioCodeCredential() { } public VisualStudioCodeCredential(Azure.Identity.VisualStudioCodeCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class VisualStudioCodeCredentialOptions : Azure.Identity.TokenCredentialOptions { public VisualStudioCodeCredentialOptions() { } public string TenantId { get { throw null; } set { } } } public partial class VisualStudioCredential : Azure.Core.TokenCredential { public VisualStudioCredential() { } public VisualStudioCredential(Azure.Identity.VisualStudioCredentialOptions options) { } public override Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class VisualStudioCredentialOptions : Azure.Identity.TokenCredentialOptions { public VisualStudioCredentialOptions() { } public string TenantId { get { throw null; } set { } } } }
/* The MIT License (MIT) Copyright (c) 2015-2017 Secret Lab Pty. Ltd. and Yarn Spinner contributors. 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. */ // Comment out to not catch exceptions #define CATCH_EXCEPTIONS using System; using System.Collections.Generic; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using System.Text; using System.IO; using System.Linq; using System.Globalization; namespace Yarn { public enum NodeFormat { Unknown, // an unknown type SingleNodeText, // a plain text file containing a single node with no metadata Text, // a text file containing multiple nodes with metadata } internal class Loader { private Dialogue dialogue; public Program program { get; private set; } // Prepares a loader. 'implementation' is used for logging. public Loader(Dialogue dialogue) { if (dialogue == null) throw new ArgumentNullException (nameof(dialogue)); this.dialogue = dialogue; } // the preprocessor that cleans up things to make it easier on ANTLR // replaces \r\n with \n // adds in INDENTS and DEDENTS where necessary // replaces \t with four spaces // takes in a string of yarn and returns a string the compiler can then use private struct EmissionTuple { public int depth; public bool emitted; public EmissionTuple(int depth, bool emitted) { this.depth = depth; this.emitted = emitted; } } private string preprocessor(string nodeText) { string processed = null; using (StringReader reader = new StringReader(nodeText)) { // a list to hold outputLines once they have been cleaned up List<string> outputLines = new List<string>(); // a stack to keep track of how far indented we are // made up of ints and bools // ints track the depth, bool tracks if we emitted an indent token // starts with 0 and false so we can never fall off the end of the stack Stack<EmissionTuple> indents = new Stack<EmissionTuple>(); indents.Push(new EmissionTuple(0, false)); // a bool to determine if we are in a mode where we need to track indents bool shouldTrackNextIndentation = false; char INDENT = '\a'; char DEDENT = '\v'; //string INDENT = "{"; //string DEDENT = "}"; string OPTION = "->"; string line; while ((line = reader.ReadLine()) != null) { // replacing \t with 4 spaces string tweakedLine = line.Replace("\t", " "); // stripping of any trailing newlines, will add them back in later tweakedLine = tweakedLine.TrimEnd('\r', '\n'); // getting the number of indents on this line int lineIndent = tweakedLine.TakeWhile(Char.IsWhiteSpace).Count(); // working out if it is an option (ie does it start with ->) bool isOption = tweakedLine.TrimStart(' ').StartsWith(OPTION, StringComparison.InvariantCulture); // are we in a state where we need to track indents? var previous = indents.Peek(); if (shouldTrackNextIndentation && (lineIndent > previous.depth)) { indents.Push(new EmissionTuple(lineIndent, true)); // adding an indent to the stream // tries to add it to the end of the previous line where possible if (outputLines.Count == 0) { tweakedLine = INDENT + tweakedLine; } else { outputLines[outputLines.Count - 1] = outputLines[outputLines.Count - 1] + INDENT; } shouldTrackNextIndentation = false; } // have we finished with the current block of statements else if (lineIndent < previous.depth) { while (lineIndent < indents.Peek().depth) { var topLevel = indents.Pop(); if (topLevel.emitted) { // adding dedents if (outputLines.Count == 0) { tweakedLine = DEDENT + tweakedLine; } else { outputLines[outputLines.Count - 1] = outputLines[outputLines.Count - 1] + DEDENT; } } } } else { shouldTrackNextIndentation = false; } // do we need to track the indents for the next statement? if (isOption) { shouldTrackNextIndentation = true; if (indents.Peek().depth < lineIndent) { indents.Push(new EmissionTuple(lineIndent, false)); } } outputLines.Add(tweakedLine); } // mash it all back together now StringBuilder builder = new StringBuilder(); foreach (string outLine in outputLines) { builder.Append(outLine); builder.Append("\n"); } processed = builder.ToString(); } return processed; } // Given a bunch of raw text, load all nodes that were inside it. // You can call this multiple times to append to the collection of nodes, // but note that new nodes will replace older ones with the same name. // Returns the number of nodes that were loaded. public Program Load(string text, Library library, string fileName, Program includeProgram, bool showTokens, bool showParseTree, string onlyConsiderNode, NodeFormat format) { if (format == NodeFormat.Unknown) { format = GetFormatFromFileName(fileName); } // currently experimental node can only be used on yarn.txt yarn files and single nodes if (format != NodeFormat.Text && format != NodeFormat.SingleNodeText) { throw new InvalidDataException($"Invalid node format {format}"); } // this isn't the greatest... if (format == NodeFormat.SingleNodeText) { // it is just the body // need to add a dummy header and body delimiters StringBuilder builder = new StringBuilder(); builder.Append("title:Start\n"); builder.Append("---\n"); builder.Append(text); builder.Append("\n===\n"); text = builder.ToString(); } string inputString = preprocessor(text); ICharStream input = CharStreams.fromstring(inputString); YarnSpinnerLexer lexer = new YarnSpinnerLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); YarnSpinnerParser parser = new YarnSpinnerParser(tokens); // turning off the normal error listener and using ours parser.RemoveErrorListeners(); parser.AddErrorListener(ErrorListener.Instance); IParseTree tree = parser.dialogue(); Compiler compiler = new Compiler(library); compiler.Compile(tree); // merging in the other program if requested if (includeProgram != null) { compiler.program.Include(includeProgram); } return compiler.program; } // The raw text of the Yarn node, plus metadata // All properties are serialised except tagsList, which is a derived property public struct NodeInfo { public struct Position { public int x { get; set; } public int y { get; set; } } public string title { get; set; } public string body { get; set; } // The raw "tags" field, containing space-separated tags. This is written // to the file. public string tags { get; set; } public int colorID { get; set; } public Position position { get; set; } // The tags for this node, as a list of individual strings. public List<string> tagsList { get { // If we have no tags list, or it's empty, return the empty list if (tags == null || tags.Length == 0) { return new List<string>(); } return new List<string>(tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); } } } internal static NodeFormat GetFormatFromFileName(string fileName) { NodeFormat format; if (fileName.EndsWith(".yarn.txt", StringComparison.OrdinalIgnoreCase)) { format = NodeFormat.Text; } else if (fileName.EndsWith(".node", StringComparison.OrdinalIgnoreCase)) { format = NodeFormat.SingleNodeText; } else { throw new FormatException(string.Format(CultureInfo.CurrentCulture, "Unknown file format for file '{0}'", fileName)); } return format; } // Given either Twine, JSON or XML input, return an array // containing info about the nodes in that file internal NodeInfo[] GetNodesFromText(string text, NodeFormat format) { // All the nodes we found in this file var nodes = new List<NodeInfo> (); switch (format) { case NodeFormat.SingleNodeText: // If it starts with a comment, treat it as a single-node file var nodeInfo = new NodeInfo(); nodeInfo.title = "Start"; nodeInfo.body = text; nodes.Add(nodeInfo); break; case NodeFormat.Text: // check for the existence of at least one "---"+newline sentinel, which divides // the headers from the body // we use a regex to match either \r\n or \n line endings if (System.Text.RegularExpressions.Regex.IsMatch(text, "---.?\n") == false) { dialogue.LogErrorMessage("Error parsing input: text appears corrupt (no header sentinel)"); break; } var headerRegex = new System.Text.RegularExpressions.Regex("(?<field>.*): *(?<value>.*)"); var nodeProperties = typeof(NodeInfo).GetProperties(); int lineNumber = 0; using (var reader = new System.IO.StringReader(text)) { string line; while ((line = reader.ReadLine()) != null) { // Create a new node NodeInfo node = new NodeInfo(); // Read header lines do { lineNumber++; // skip empty lines if (line.Length == 0) { continue; } // Attempt to parse the header var headerMatches = headerRegex.Match(line); if (headerMatches == null) { dialogue.LogErrorMessage(string.Format(CultureInfo.CurrentCulture, "Line {0}: Can't parse header '{1}'", lineNumber, line)); continue; } var field = headerMatches.Groups["field"].Value; var value = headerMatches.Groups["value"].Value; // Attempt to set the appropriate property using this field foreach (var property in nodeProperties) { if (property.Name != field) { continue; } // skip properties that can't be written to if (property.CanWrite == false) { continue; } try { var propertyType = property.PropertyType; object convertedValue; if (propertyType.IsAssignableFrom(typeof(string))) { convertedValue = value; } else if (propertyType.IsAssignableFrom(typeof(int))) { convertedValue = int.Parse(value, CultureInfo.InvariantCulture); } else if (propertyType.IsAssignableFrom(typeof(NodeInfo.Position))) { var components = value.Split(','); // we expect 2 components: x and y if (components.Length != 2) { throw new FormatException(); } var position = new NodeInfo.Position(); position.x = int.Parse(components[0], CultureInfo.InvariantCulture); position.y = int.Parse(components[1], CultureInfo.InvariantCulture); convertedValue = position; } else { throw new NotSupportedException(); } // we need to box this because structs are value types, // so calling SetValue using 'node' would just modify a copy of 'node' object box = node; property.SetValue(box, convertedValue, null); node = (NodeInfo)box; break; } catch (FormatException) { dialogue.LogErrorMessage(string.Format(CultureInfo.CurrentCulture, "{0}: Error setting '{1}': invalid value '{2}'", lineNumber, field, value)); } catch (NotSupportedException) { dialogue.LogErrorMessage(string.Format(CultureInfo.CurrentCulture, "{0}: Error setting '{1}': This property cannot be set", lineNumber, field)); } } } while ((line = reader.ReadLine()) != "---"); lineNumber++; // We're past the header; read the body var lines = new List<string>(); // Read header lines until we hit the end of node sentinel or the end of the file while ((line = reader.ReadLine()) != "===" && line != null) { lineNumber++; lines.Add(line); } // We're done reading the lines! Zip 'em up into a string and // store it in the body node.body = string.Join("\n", lines.ToArray()); // And add this node to the list nodes.Add(node); // And now we're ready to move on to the next line! } } break; default: throw new InvalidOperationException("Unknown format " + format.ToString()); } // hooray we're done return nodes.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { internal sealed class WebSocketHandle { /// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary> private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private readonly CancellationTokenSource _abortSource = new CancellationTokenSource(); private WebSocketState _state = WebSocketState.Connecting; private WebSocket _webSocket; public static WebSocketHandle Create() => new WebSocketHandle(); public static bool IsValid(WebSocketHandle handle) => handle != null; public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus; public string CloseStatusDescription => _webSocket?.CloseStatusDescription; public WebSocketState State => _webSocket?.State ?? _state; public string SubProtocol => _webSocket?.SubProtocol; public static void CheckPlatformSupport() { /* nop */ } public void Dispose() { _state = WebSocketState.Closed; _webSocket?.Dispose(); } public void Abort() { _abortSource.Cancel(); _webSocket?.Abort(); } public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => _webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public Task SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => _webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) => _webSocket.ReceiveAsync(buffer, cancellationToken); public ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken) => _webSocket.ReceiveAsync(buffer, cancellationToken); public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { HttpResponseMessage response = null; try { // Create the request message, including a uri with ws{s} switched to http{s}. uri = new UriBuilder(uri) { Scheme = (uri.Scheme == UriScheme.Ws) ? UriScheme.Http : UriScheme.Https }.Uri; var request = new HttpRequestMessage(HttpMethod.Get, uri); if (options._requestHeaders?.Count > 0) // use field to avoid lazily initializing the collection { foreach (string key in options.RequestHeaders) { request.Headers.Add(key, options.RequestHeaders[key]); } } // Create the security key and expected response, then build all of the request headers KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept(); AddWebSocketHeaders(request, secKeyAndSecWebSocketAccept.Key, options); // Create the handler for this request and populate it with all of the options. var handler = new SocketsHttpHandler(); handler.Credentials = options.Credentials; handler.Proxy = options.Proxy; handler.CookieContainer = options.Cookies; if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection { handler.SslOptions.ClientCertificates.AddRange(options.ClientCertificates); } // Issue the request. The response must be status code 101. CancellationTokenSource linkedCancellation, externalAndAbortCancellation; if (cancellationToken.CanBeCanceled) // avoid allocating linked source if external token is not cancelable { linkedCancellation = externalAndAbortCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _abortSource.Token); } else { linkedCancellation = null; externalAndAbortCancellation = _abortSource; } using (linkedCancellation) { response = await new HttpMessageInvoker(handler).SendAsync(request, externalAndAbortCancellation.Token).ConfigureAwait(false); externalAndAbortCancellation.Token.ThrowIfCancellationRequested(); // poll in case sends/receives in request/response didn't observe cancellation } if (response.StatusCode != HttpStatusCode.SwitchingProtocols) { throw new WebSocketException(SR.net_webstatus_ConnectFailure); } // The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values. ValidateHeader(response.Headers, HttpKnownHeaderNames.Connection, "Upgrade"); ValidateHeader(response.Headers, HttpKnownHeaderNames.Upgrade, "websocket"); ValidateHeader(response.Headers, HttpKnownHeaderNames.SecWebSocketAccept, secKeyAndSecWebSocketAccept.Value); // The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols, // and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we // already got one in a previous header), fail. Otherwise, track which one we got. string subprotocol = null; IEnumerable<string> subprotocolEnumerableValues; if (response.Headers.TryGetValues(HttpKnownHeaderNames.SecWebSocketProtocol, out subprotocolEnumerableValues)) { Debug.Assert(subprotocolEnumerableValues is string[]); string[] subprotocolArray = (string[])subprotocolEnumerableValues; if (subprotocolArray.Length > 0 && !string.IsNullOrEmpty(subprotocolArray[0])) { subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase)); if (subprotocol == null) { throw new WebSocketException( WebSocketError.UnsupportedProtocol, SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), string.Join(", ", subprotocolArray))); } } } // Get or create the buffer to use const int MinBufferSize = 14; // from ManagedWebSocket.MaxMessageHeaderLength ArraySegment<byte> optionsBuffer = options.Buffer.GetValueOrDefault(); Memory<byte> buffer = optionsBuffer.Count >= MinBufferSize ? optionsBuffer : // use the provided buffer if it's big enough options.ReceiveBufferSize >= MinBufferSize ? new byte[options.ReceiveBufferSize] : // or use the requested size if it's big enough Memory<byte>.Empty; // or let WebSocket.CreateFromStream use its default // Get the response stream and wrap it in a web socket. Stream connectedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); Debug.Assert(connectedStream.CanWrite); Debug.Assert(connectedStream.CanRead); _webSocket = WebSocket.CreateFromStream( connectedStream, isServer: false, subprotocol, options.KeepAliveInterval, buffer); } catch (Exception exc) { if (_state < WebSocketState.Closed) { _state = WebSocketState.Closed; } Abort(); response?.Dispose(); if (exc is WebSocketException) { throw; } throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc); } } /// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param> private static void AddWebSocketHeaders(HttpRequestMessage request, string secKey, ClientWebSocketOptions options) { request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Upgrade, "websocket"); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketVersion, "13"); request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketKey, secKey); if (options._requestedSubProtocols?.Count > 0) { request.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, string.Join(", ", options.RequestedSubProtocols)); } } /// <summary> /// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and /// the associated response we expect to receive as the Sec-WebSocket-Accept header value. /// </summary> /// <returns>A key-value pair of the request header security key and expected response header value.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")] private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept() { string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); using (SHA1 sha = SHA1.Create()) { return new KeyValuePair<string, string>( secKey, Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid)))); } } private static void ValidateHeader(HttpHeaders headers, string name, string expectedValue) { if (!headers.TryGetValues(name, out IEnumerable<string> values)) { ThrowConnectFailure(); } Debug.Assert(values is string[]); string[] array = (string[])values; if (array.Length != 1 || !string.Equals(array[0], expectedValue, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, name, string.Join(", ", array))); } } private static void ThrowConnectFailure() => throw new WebSocketException(SR.net_webstatus_ConnectFailure); } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Web; using Autofac; using Autofac.Builder; using Autofac.Core; using Autofac.Integration.Mvc; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Configuration; using Nop.Core.Data; using Nop.Core.Fakes; using Nop.Core.Infrastructure; using Nop.Core.Infrastructure.DependencyManagement; using Nop.Core.Plugins; using Nop.Data; using Nop.Services.Affiliates; using Nop.Services.Authentication; using Nop.Services.Authentication.External; using Nop.Services.Blogs; using Nop.Services.Catalog; using Nop.Services.Cms; using Nop.Services.Common; using Nop.Services.Configuration; using Nop.Services.Customers; using Nop.Services.Directory; using Nop.Services.Discounts; using Nop.Services.Events; using Nop.Services.ExportImport; using Nop.Services.Forums; using Nop.Services.Helpers; using Nop.Services.Installation; using Nop.Services.Localization; using Nop.Services.Logging; using Nop.Services.Media; using Nop.Services.Messages; using Nop.Services.News; using Nop.Services.Orders; using Nop.Services.Payments; using Nop.Services.Polls; using Nop.Services.Security; using Nop.Services.Seo; using Nop.Services.Shipping; using Nop.Services.Stores; using Nop.Services.Tasks; using Nop.Services.Tax; using Nop.Services.Topics; using Nop.Services.Vendors; using Nop.Web.Framework.Mvc.Routes; using Nop.Web.Framework.Themes; using Nop.Web.Framework.UI; namespace Nop.Web.Framework { public class DependencyRegistrar : IDependencyRegistrar { public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder) { //HTTP context and other related stuff builder.Register(c => //register FakeHttpContext when HttpContext is not available HttpContext.Current != null ? (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) : (new FakeHttpContext("~/") as HttpContextBase)) .As<HttpContextBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Request) .As<HttpRequestBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Response) .As<HttpResponseBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Server) .As<HttpServerUtilityBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Session) .As<HttpSessionStateBase>() .InstancePerLifetimeScope(); //web helper builder.RegisterType<WebHelper>().As<IWebHelper>().InstancePerLifetimeScope(); //user agent helper builder.RegisterType<UserAgentHelper>().As<IUserAgentHelper>().InstancePerLifetimeScope(); //controllers builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); //data layer var dataSettingsManager = new DataSettingsManager(); var dataProviderSettings = dataSettingsManager.LoadSettings(); builder.Register(c => dataSettingsManager.LoadSettings()).As<DataSettings>(); builder.Register(x => new EfDataProviderManager(x.Resolve<DataSettings>())).As<BaseDataProviderManager>().InstancePerDependency(); builder.Register(x => x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IDataProvider>().InstancePerDependency(); if (dataProviderSettings != null && dataProviderSettings.IsValid()) { var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings()); var dataProvider = efDataProviderManager.LoadDataProvider(); dataProvider.InitConnectionFactory(); builder.Register<IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope(); } else { builder.Register<IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope(); } builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope(); //plugins builder.RegisterType<PluginFinder>().As<IPluginFinder>().InstancePerLifetimeScope(); //cache manager builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance(); builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_per_request").InstancePerLifetimeScope(); //work context builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerLifetimeScope(); //store context builder.RegisterType<WebStoreContext>().As<IStoreContext>().InstancePerLifetimeScope(); //services builder.RegisterType<BackInStockSubscriptionService>().As<IBackInStockSubscriptionService>().InstancePerLifetimeScope(); builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerLifetimeScope(); builder.RegisterType<CompareProductsService>().As<ICompareProductsService>().InstancePerLifetimeScope(); builder.RegisterType<RecentlyViewedProductsService>().As<IRecentlyViewedProductsService>().InstancePerLifetimeScope(); builder.RegisterType<ManufacturerService>().As<IManufacturerService>().InstancePerLifetimeScope(); builder.RegisterType<PriceFormatter>().As<IPriceFormatter>().InstancePerLifetimeScope(); builder.RegisterType<ProductAttributeFormatter>().As<IProductAttributeFormatter>().InstancePerLifetimeScope(); builder.RegisterType<ProductAttributeParser>().As<IProductAttributeParser>().InstancePerLifetimeScope(); builder.RegisterType<ProductAttributeService>().As<IProductAttributeService>().InstancePerLifetimeScope(); builder.RegisterType<ProductService>().As<IProductService>().InstancePerLifetimeScope(); builder.RegisterType<CopyProductService>().As<ICopyProductService>().InstancePerLifetimeScope(); builder.RegisterType<SpecificationAttributeService>().As<ISpecificationAttributeService>().InstancePerLifetimeScope(); builder.RegisterType<ProductTemplateService>().As<IProductTemplateService>().InstancePerLifetimeScope(); builder.RegisterType<CategoryTemplateService>().As<ICategoryTemplateService>().InstancePerLifetimeScope(); builder.RegisterType<ManufacturerTemplateService>().As<IManufacturerTemplateService>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<ProductTagService>().As<IProductTagService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterType<AffiliateService>().As<IAffiliateService>().InstancePerLifetimeScope(); builder.RegisterType<VendorService>().As<IVendorService>().InstancePerLifetimeScope(); builder.RegisterType<AddressService>().As<IAddressService>().InstancePerLifetimeScope(); builder.RegisterType<SearchTermService>().As<ISearchTermService>().InstancePerLifetimeScope(); builder.RegisterType<GenericAttributeService>().As<IGenericAttributeService>().InstancePerLifetimeScope(); builder.RegisterType<FulltextService>().As<IFulltextService>().InstancePerLifetimeScope(); builder.RegisterType<MaintenanceService>().As<IMaintenanceService>().InstancePerLifetimeScope(); builder.RegisterType<CustomerAttributeParser>().As<ICustomerAttributeParser>().InstancePerLifetimeScope(); builder.RegisterType<CustomerAttributeService>().As<ICustomerAttributeService>().InstancePerLifetimeScope(); builder.RegisterType<CustomerService>().As<ICustomerService>().InstancePerLifetimeScope(); builder.RegisterType<CustomerRegistrationService>().As<ICustomerRegistrationService>().InstancePerLifetimeScope(); builder.RegisterType<CustomerReportService>().As<ICustomerReportService>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<PermissionService>().As<IPermissionService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<AclService>().As<IAclService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<PriceCalculationService>().As<IPriceCalculationService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterType<GeoLookupService>().As<IGeoLookupService>().InstancePerLifetimeScope(); builder.RegisterType<CountryService>().As<ICountryService>().InstancePerLifetimeScope(); builder.RegisterType<CurrencyService>().As<ICurrencyService>().InstancePerLifetimeScope(); builder.RegisterType<MeasureService>().As<IMeasureService>().InstancePerLifetimeScope(); builder.RegisterType<StateProvinceService>().As<IStateProvinceService>().InstancePerLifetimeScope(); builder.RegisterType<StoreService>().As<IStoreService>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<StoreMappingService>().As<IStoreMappingService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterType<DiscountService>().As<IDiscountService>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<SettingService>().As<ISettingService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterSource(new SettingsSource()); //pass MemoryCacheManager as cacheManager (cache locales between requests) builder.RegisterType<LocalizationService>().As<ILocalizationService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache locales between requests) builder.RegisterType<LocalizedEntityService>().As<ILocalizedEntityService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterType<LanguageService>().As<ILanguageService>().InstancePerLifetimeScope(); builder.RegisterType<DownloadService>().As<IDownloadService>().InstancePerLifetimeScope(); builder.RegisterType<PictureService>().As<IPictureService>().InstancePerLifetimeScope(); builder.RegisterType<MessageTemplateService>().As<IMessageTemplateService>().InstancePerLifetimeScope(); builder.RegisterType<QueuedEmailService>().As<IQueuedEmailService>().InstancePerLifetimeScope(); builder.RegisterType<NewsLetterSubscriptionService>().As<INewsLetterSubscriptionService>().InstancePerLifetimeScope(); builder.RegisterType<CampaignService>().As<ICampaignService>().InstancePerLifetimeScope(); builder.RegisterType<EmailAccountService>().As<IEmailAccountService>().InstancePerLifetimeScope(); builder.RegisterType<WorkflowMessageService>().As<IWorkflowMessageService>().InstancePerLifetimeScope(); builder.RegisterType<MessageTokenProvider>().As<IMessageTokenProvider>().InstancePerLifetimeScope(); builder.RegisterType<Tokenizer>().As<ITokenizer>().InstancePerLifetimeScope(); builder.RegisterType<EmailSender>().As<IEmailSender>().InstancePerLifetimeScope(); builder.RegisterType<CheckoutAttributeFormatter>().As<ICheckoutAttributeFormatter>().InstancePerLifetimeScope(); builder.RegisterType<CheckoutAttributeParser>().As<ICheckoutAttributeParser>().InstancePerLifetimeScope(); builder.RegisterType<CheckoutAttributeService>().As<ICheckoutAttributeService>().InstancePerLifetimeScope(); builder.RegisterType<GiftCardService>().As<IGiftCardService>().InstancePerLifetimeScope(); builder.RegisterType<OrderService>().As<IOrderService>().InstancePerLifetimeScope(); builder.RegisterType<OrderReportService>().As<IOrderReportService>().InstancePerLifetimeScope(); builder.RegisterType<OrderProcessingService>().As<IOrderProcessingService>().InstancePerLifetimeScope(); builder.RegisterType<OrderTotalCalculationService>().As<IOrderTotalCalculationService>().InstancePerLifetimeScope(); builder.RegisterType<ShoppingCartService>().As<IShoppingCartService>().InstancePerLifetimeScope(); builder.RegisterType<PaymentService>().As<IPaymentService>().InstancePerLifetimeScope(); builder.RegisterType<EncryptionService>().As<IEncryptionService>().InstancePerLifetimeScope(); builder.RegisterType<FormsAuthenticationService>().As<IAuthenticationService>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<UrlRecordService>().As<IUrlRecordService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); builder.RegisterType<ShipmentService>().As<IShipmentService>().InstancePerLifetimeScope(); builder.RegisterType<ShippingService>().As<IShippingService>().InstancePerLifetimeScope(); builder.RegisterType<TaxCategoryService>().As<ITaxCategoryService>().InstancePerLifetimeScope(); builder.RegisterType<TaxService>().As<ITaxService>().InstancePerLifetimeScope(); builder.RegisterType<TaxCategoryService>().As<ITaxCategoryService>().InstancePerLifetimeScope(); builder.RegisterType<DefaultLogger>().As<ILogger>().InstancePerLifetimeScope(); //pass MemoryCacheManager as cacheManager (cache settings between requests) builder.RegisterType<CustomerActivityService>().As<ICustomerActivityService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope(); if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["UseFastInstallationService"]) && Convert.ToBoolean(ConfigurationManager.AppSettings["UseFastInstallationService"])) { builder.RegisterType<SqlFileInstallationService>().As<IInstallationService>().InstancePerLifetimeScope(); } else { builder.RegisterType<CodeFirstInstallationService>().As<IInstallationService>().InstancePerLifetimeScope(); } builder.RegisterType<ForumService>().As<IForumService>().InstancePerLifetimeScope(); builder.RegisterType<PollService>().As<IPollService>().InstancePerLifetimeScope(); builder.RegisterType<BlogService>().As<IBlogService>().InstancePerLifetimeScope(); builder.RegisterType<WidgetService>().As<IWidgetService>().InstancePerLifetimeScope(); builder.RegisterType<TopicService>().As<ITopicService>().InstancePerLifetimeScope(); builder.RegisterType<NewsService>().As<INewsService>().InstancePerLifetimeScope(); builder.RegisterType<DateTimeHelper>().As<IDateTimeHelper>().InstancePerLifetimeScope(); builder.RegisterType<SitemapGenerator>().As<ISitemapGenerator>().InstancePerLifetimeScope(); builder.RegisterType<PageHeadBuilder>().As<IPageHeadBuilder>().InstancePerLifetimeScope(); builder.RegisterType<ScheduleTaskService>().As<IScheduleTaskService>().InstancePerLifetimeScope(); builder.RegisterType<ExportManager>().As<IExportManager>().InstancePerLifetimeScope(); builder.RegisterType<ImportManager>().As<IImportManager>().InstancePerLifetimeScope(); builder.RegisterType<PdfService>().As<IPdfService>().InstancePerLifetimeScope(); builder.RegisterType<ThemeProvider>().As<IThemeProvider>().InstancePerLifetimeScope(); builder.RegisterType<ThemeContext>().As<IThemeContext>().InstancePerLifetimeScope(); builder.RegisterType<ExternalAuthorizer>().As<IExternalAuthorizer>().InstancePerLifetimeScope(); builder.RegisterType<OpenAuthenticationService>().As<IOpenAuthenticationService>().InstancePerLifetimeScope(); builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().SingleInstance(); //Register event consumers var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList(); foreach (var consumer in consumers) { builder.RegisterType(consumer) .As(consumer.FindInterfaces((type, criteria) => { var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition()); return isMatch; }, typeof(IConsumer<>))) .InstancePerLifetimeScope(); } builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance(); builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance(); } public int Order { get { return 0; } } } public class SettingsSource : IRegistrationSource { static readonly MethodInfo BuildMethod = typeof(SettingsSource).GetMethod( "BuildRegistration", BindingFlags.Static | BindingFlags.NonPublic); public IEnumerable<IComponentRegistration> RegistrationsFor( Service service, Func<Service, IEnumerable<IComponentRegistration>> registrations) { var ts = service as TypedService; if (ts != null && typeof(ISettings).IsAssignableFrom(ts.ServiceType)) { var buildMethod = BuildMethod.MakeGenericMethod(ts.ServiceType); yield return (IComponentRegistration)buildMethod.Invoke(null, null); } } static IComponentRegistration BuildRegistration<TSettings>() where TSettings : ISettings, new() { return RegistrationBuilder .ForDelegate((c, p) => { var currentStoreId = c.Resolve<IStoreContext>().CurrentStore.Id; //uncomment the code below if you want load settings per store only when you have two stores installed. //var currentStoreId = c.Resolve<IStoreService>().GetAllStores().Count > 1 // c.Resolve<IStoreContext>().CurrentStore.Id : 0; //although it's better to connect to your database and execute the following SQL: //DELETE FROM [Setting] WHERE [StoreId] > 0 return c.Resolve<ISettingService>().LoadSetting<TSettings>(currentStoreId); }) .InstancePerLifetimeScope() .CreateRegistration(); } public bool IsAdapterForIndividualComponents { get { return false; } } } }
using System; using UnityEngine; using UnityEditor; using System.Linq; using System.IO; using System.Collections.Generic; using System.Reflection; using UnityEngine.AssetGraph; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { /// <summary> /// IModifier is an interface which modifies incoming assets. /// Subclass of IModifier must have <c>CustomModifier</c> attribute. /// </summary> public interface IModifier { /// <summary> /// Called when validating this prefabBuilder. /// NodeException should be thrown if this modifier is not ready to be used for building. /// </summary> void OnValidate (); /// <summary> /// Test if incoming assset is different from this IModifier's setting. /// </summary> /// <returns><c>true</c> if this instance is modified the specified assets; otherwise, <c>false</c>.</returns> /// <param name="assets">Assets.</param> bool IsModified (UnityEngine.Object[] assets, List<AssetReference> group); /// <summary> /// Modify incoming assets. /// </summary> /// <param name="assets">Assets.</param> void Modify (UnityEngine.Object[] assets, List<AssetReference> group); /// <summary> /// Draw Inspector GUI for this Modifier. /// </summary> /// <param name="onValueChanged">On value changed.</param> void OnInspectorGUI (Action onValueChanged); } /// <summary> /// CustomModifier attribute is to declare the class is used as a IModifier. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class CustomModifier : Attribute { private string m_name; private Type m_modifyFor; /// <summary> /// Name of Modifier appears on GUI. /// </summary> /// <value>The name.</value> public string Name { get { return m_name; } } /// <summary> /// Type of asset Modifier modifies. /// </summary> /// <value>For.</value> public Type For { get { return m_modifyFor; } } /// <summary> /// CustomModifier declares the class is used as a IModifier. /// </summary> /// <param name="name">Name of Modifier appears on GUI.</param> /// <param name="modifyFor">Type of asset Modifier modifies.</param> public CustomModifier (string name, Type modifyFor) { m_name = name; m_modifyFor = modifyFor; } } public class ModifierUtility { private static Dictionary<Type, Dictionary<string, string>> s_attributeAssemblyQualifiedNameMap; private static Dictionary<Type, Dictionary<string, string>> GetAttributeAssemblyQualifiedNameMap() { if(s_attributeAssemblyQualifiedNameMap == null) { s_attributeAssemblyQualifiedNameMap = new Dictionary<Type, Dictionary<string, string>>(); var allBuilders = new List<Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var builders = assembly.GetTypes() .Where(t => t != typeof(IModifier)) .Where(t => typeof(IModifier).IsAssignableFrom(t)); allBuilders.AddRange (builders); } foreach (var builder in allBuilders) { CustomModifier attr = builder.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if (attr != null) { if (!s_attributeAssemblyQualifiedNameMap.ContainsKey (attr.For)) { s_attributeAssemblyQualifiedNameMap[attr.For] = new Dictionary<string, string>(); } var map = s_attributeAssemblyQualifiedNameMap[attr.For]; if (!map.ContainsKey(attr.Name)) { map[attr.Name] = builder.AssemblyQualifiedName; } else { LogUtility.Logger.LogWarning(LogUtility.kTag, "Multiple CustomModifier class with the same name/type found. Ignoring " + builder.Name); } } } } return s_attributeAssemblyQualifiedNameMap; } public static IEnumerable<Type> GetModifyableTypes () { return GetAttributeAssemblyQualifiedNameMap().Keys.AsEnumerable(); } public static Dictionary<string, string> GetAttributeAssemblyQualifiedNameMap (Type targetType) { UnityEngine.Assertions.Assert.IsNotNull(targetType); return GetAttributeAssemblyQualifiedNameMap()[targetType]; } public static string GetModifierGUIName(IModifier m) { CustomModifier attr = m.GetType().GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; return attr.Name; } public static string GetModifierGUIName(string className) { var type = Type.GetType(className); if(type != null) { CustomModifier attr = type.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return attr.Name; } } return string.Empty; } public static string GUINameToAssemblyQualifiedName(string guiName, Type targetType) { var map = GetAttributeAssemblyQualifiedNameMap(targetType); if(map.ContainsKey(guiName)) { return map[guiName]; } return null; } public static Type GetModifierTargetType(IModifier m) { CustomModifier attr = m.GetType().GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; UnityEngine.Assertions.Assert.IsNotNull(attr); return attr.For; } public static Type GetModifierTargetType(string className) { var type = Type.GetType(className); if(type != null) { CustomModifier attr = type.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return attr.For; } } return null; } public static bool HasValidCustomModifierAttribute(Type t) { CustomModifier attr = t.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return !string.IsNullOrEmpty(attr.Name) && attr.For != null; } return false; } public static IModifier CreateModifier(string guiName, Type targetType) { var assemblyQualifiedName = GUINameToAssemblyQualifiedName(guiName, targetType); if(assemblyQualifiedName != null) { var type = Type.GetType(assemblyQualifiedName); if (type == null) { return null; } return (IModifier) type.Assembly.CreateInstance(type.FullName); } return null; } public static IModifier CreateModifier(string assemblyQualifiedName) { if(assemblyQualifiedName == null) { return null; } Type t = Type.GetType(assemblyQualifiedName); if(t == null) { return null; } if(!HasValidCustomModifierAttribute(t)) { return null; } return (IModifier) t.Assembly.CreateInstance(t.FullName); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/FortDeployPokemonResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/FortDeployPokemonResponse.proto</summary> public static partial class FortDeployPokemonResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/FortDeployPokemonResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FortDeployPokemonResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cj9QT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0ZvcnREZXBsb3lQ", "b2tlbW9uUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5S", "ZXNwb25zZXMaIVBPR09Qcm90b3MvRGF0YS9Qb2tlbW9uRGF0YS5wcm90bxoi", "UE9HT1Byb3Rvcy9EYXRhL0d5bS9HeW1TdGF0ZS5wcm90bxo5UE9HT1Byb3Rv", "cy9OZXR3b3JraW5nL1Jlc3BvbnNlcy9Gb3J0RGV0YWlsc1Jlc3BvbnNlLnBy", "b3RvIsQEChlGb3J0RGVwbG95UG9rZW1vblJlc3BvbnNlElEKBnJlc3VsdBgB", "IAEoDjJBLlBPR09Qcm90b3MuTmV0d29ya2luZy5SZXNwb25zZXMuRm9ydERl", "cGxveVBva2Vtb25SZXNwb25zZS5SZXN1bHQSSgoMZm9ydF9kZXRhaWxzGAIg", "ASgLMjQuUE9HT1Byb3Rvcy5OZXR3b3JraW5nLlJlc3BvbnNlcy5Gb3J0RGV0", "YWlsc1Jlc3BvbnNlEjIKDHBva2Vtb25fZGF0YRgDIAEoCzIcLlBPR09Qcm90", "b3MuRGF0YS5Qb2tlbW9uRGF0YRIwCglneW1fc3RhdGUYBCABKAsyHS5QT0dP", "UHJvdG9zLkRhdGEuR3ltLkd5bVN0YXRlIqECCgZSZXN1bHQSEQoNTk9fUkVT", "VUxUX1NFVBAAEgsKB1NVQ0NFU1MQARIlCiFFUlJPUl9BTFJFQURZX0hBU19Q", "T0tFTU9OX09OX0ZPUlQQAhIhCh1FUlJPUl9PUFBPU0lOR19URUFNX09XTlNf", "Rk9SVBADEhYKEkVSUk9SX0ZPUlRfSVNfRlVMTBAEEhYKEkVSUk9SX05PVF9J", "Tl9SQU5HRRAFEhwKGEVSUk9SX1BMQVlFUl9IQVNfTk9fVEVBTRAGEh0KGUVS", "Uk9SX1BPS0VNT05fTk9UX0ZVTExfSFAQBxIkCiBFUlJPUl9QTEFZRVJfQkVM", "T1dfTUlOSU1VTV9MRVZFTBAIEhoKFkVSUk9SX1BPS0VNT05fSVNfQlVERFkQ", "CWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Data.PokemonDataReflection.Descriptor, global::POGOProtos.Data.Gym.GymStateReflection.Descriptor, global::POGOProtos.Networking.Responses.FortDetailsResponseReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.FortDeployPokemonResponse), global::POGOProtos.Networking.Responses.FortDeployPokemonResponse.Parser, new[]{ "Result", "FortDetails", "PokemonData", "GymState" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.FortDeployPokemonResponse.Types.Result) }, null) })); } #endregion } #region Messages public sealed partial class FortDeployPokemonResponse : pb::IMessage<FortDeployPokemonResponse> { private static readonly pb::MessageParser<FortDeployPokemonResponse> _parser = new pb::MessageParser<FortDeployPokemonResponse>(() => new FortDeployPokemonResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FortDeployPokemonResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.FortDeployPokemonResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonResponse(FortDeployPokemonResponse other) : this() { result_ = other.result_; FortDetails = other.fortDetails_ != null ? other.FortDetails.Clone() : null; PokemonData = other.pokemonData_ != null ? other.PokemonData.Clone() : null; GymState = other.gymState_ != null ? other.GymState.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonResponse Clone() { return new FortDeployPokemonResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::POGOProtos.Networking.Responses.FortDeployPokemonResponse.Types.Result result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.FortDeployPokemonResponse.Types.Result Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "fort_details" field.</summary> public const int FortDetailsFieldNumber = 2; private global::POGOProtos.Networking.Responses.FortDetailsResponse fortDetails_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.FortDetailsResponse FortDetails { get { return fortDetails_; } set { fortDetails_ = value; } } /// <summary>Field number for the "pokemon_data" field.</summary> public const int PokemonDataFieldNumber = 3; private global::POGOProtos.Data.PokemonData pokemonData_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Data.PokemonData PokemonData { get { return pokemonData_; } set { pokemonData_ = value; } } /// <summary>Field number for the "gym_state" field.</summary> public const int GymStateFieldNumber = 4; private global::POGOProtos.Data.Gym.GymState gymState_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Data.Gym.GymState GymState { get { return gymState_; } set { gymState_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FortDeployPokemonResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FortDeployPokemonResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(FortDetails, other.FortDetails)) return false; if (!object.Equals(PokemonData, other.PokemonData)) return false; if (!object.Equals(GymState, other.GymState)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (fortDetails_ != null) hash ^= FortDetails.GetHashCode(); if (pokemonData_ != null) hash ^= PokemonData.GetHashCode(); if (gymState_ != null) hash ^= GymState.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (fortDetails_ != null) { output.WriteRawTag(18); output.WriteMessage(FortDetails); } if (pokemonData_ != null) { output.WriteRawTag(26); output.WriteMessage(PokemonData); } if (gymState_ != null) { output.WriteRawTag(34); output.WriteMessage(GymState); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (fortDetails_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(FortDetails); } if (pokemonData_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PokemonData); } if (gymState_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GymState); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FortDeployPokemonResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.fortDetails_ != null) { if (fortDetails_ == null) { fortDetails_ = new global::POGOProtos.Networking.Responses.FortDetailsResponse(); } FortDetails.MergeFrom(other.FortDetails); } if (other.pokemonData_ != null) { if (pokemonData_ == null) { pokemonData_ = new global::POGOProtos.Data.PokemonData(); } PokemonData.MergeFrom(other.PokemonData); } if (other.gymState_ != null) { if (gymState_ == null) { gymState_ = new global::POGOProtos.Data.Gym.GymState(); } GymState.MergeFrom(other.GymState); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::POGOProtos.Networking.Responses.FortDeployPokemonResponse.Types.Result) input.ReadEnum(); break; } case 18: { if (fortDetails_ == null) { fortDetails_ = new global::POGOProtos.Networking.Responses.FortDetailsResponse(); } input.ReadMessage(fortDetails_); break; } case 26: { if (pokemonData_ == null) { pokemonData_ = new global::POGOProtos.Data.PokemonData(); } input.ReadMessage(pokemonData_); break; } case 34: { if (gymState_ == null) { gymState_ = new global::POGOProtos.Data.Gym.GymState(); } input.ReadMessage(gymState_); break; } } } } #region Nested types /// <summary>Container for nested types declared in the FortDeployPokemonResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Result { [pbr::OriginalName("NO_RESULT_SET")] NoResultSet = 0, [pbr::OriginalName("SUCCESS")] Success = 1, [pbr::OriginalName("ERROR_ALREADY_HAS_POKEMON_ON_FORT")] ErrorAlreadyHasPokemonOnFort = 2, [pbr::OriginalName("ERROR_OPPOSING_TEAM_OWNS_FORT")] ErrorOpposingTeamOwnsFort = 3, [pbr::OriginalName("ERROR_FORT_IS_FULL")] ErrorFortIsFull = 4, [pbr::OriginalName("ERROR_NOT_IN_RANGE")] ErrorNotInRange = 5, [pbr::OriginalName("ERROR_PLAYER_HAS_NO_TEAM")] ErrorPlayerHasNoTeam = 6, [pbr::OriginalName("ERROR_POKEMON_NOT_FULL_HP")] ErrorPokemonNotFullHp = 7, [pbr::OriginalName("ERROR_PLAYER_BELOW_MINIMUM_LEVEL")] ErrorPlayerBelowMinimumLevel = 8, [pbr::OriginalName("ERROR_POKEMON_IS_BUDDY")] ErrorPokemonIsBuddy = 9, } } #endregion } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; using Microsoft.VisualStudio.Services.WebApi; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener { public sealed class AgentL0 { private Mock<IConfigurationManager> _configurationManager; private Mock<IJobNotification> _jobNotification; private Mock<IMessageListener> _messageListener; private Mock<IPromptManager> _promptManager; private Mock<IJobDispatcher> _jobDispatcher; private Mock<IAgentServer> _agentServer; private Mock<ITerminal> _term; private Mock<IConfigurationStore> _configStore; private Mock<IVstsAgentWebProxy> _proxy; private Mock<IAgentCertificateManager> _cert; private Mock<ISelfUpdater> _updater; public AgentL0() { _configurationManager = new Mock<IConfigurationManager>(); _jobNotification = new Mock<IJobNotification>(); _messageListener = new Mock<IMessageListener>(); _promptManager = new Mock<IPromptManager>(); _jobDispatcher = new Mock<IJobDispatcher>(); _agentServer = new Mock<IAgentServer>(); _term = new Mock<ITerminal>(); _configStore = new Mock<IConfigurationStore>(); _proxy = new Mock<IVstsAgentWebProxy>(); _cert = new Mock<IAgentCertificateManager>(); _updater = new Mock<ISelfUpdater>(); } private AgentJobRequestMessage CreateJobRequestMessage(string jobName) { TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = null; JobEnvironment environment = new JobEnvironment(); List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); var jobRequest = new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks); return jobRequest as AgentJobRequestMessage; } private JobCancelMessage CreateJobCancelMessage() { var message = new JobCancelMessage(Guid.NewGuid(), TimeSpan.FromSeconds(0)); return message; } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestRunAsync() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { //Arrange hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242 }; var message = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message); var signalWorkerComplete = new SemaphoreSlim(0, 1); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { signalWorkerComplete.Release(); await Task.Delay(2000, hc.AgentShutdownToken); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run" }); Task agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to run one job if (!await signalWorkerComplete.WaitAsync(2000)) { Assert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked."); } else { //Act hc.ShutdownAgent(ShutdownReason.UserCancelled); //stop Agent //Assert Task[] taskToWait2 = { agentTask, Task.Delay(2000) }; //wait for the Agent to exit await Task.WhenAny(taskToWait2); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.IsCanceled); _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(), $"{nameof(_jobDispatcher.Object.Run)} was not invoked."); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce()); } } } public static TheoryData<string[], bool, Times> RunAsServiceTestData = new TheoryData<string[], bool, Times>() { // staring with run command, configured as run as service, should start the agent { new [] { "run" }, true, Times.Once() }, // starting with no argument, configured not to run as service, should start agent interactively { new [] { "run" }, false, Times.Once() } }; [Theory] [MemberData("RunAsServiceTestData")] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestExecuteCommandForRunAsService(string[] args, bool configureAsService, Times expectedTimes) { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, args); _configurationManager.Setup(x => x.IsConfigured()).Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()).Returns(configureAsService); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), expectedTimes); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestMachineProvisionerCLI() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new[] { "run" }); _configurationManager.Setup(x => x.IsConfigured()). Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestMachineProvisionerCLICompat() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new string[] { }); _configurationManager.Setup(x => x.IsConfigured()). Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestRunOnce() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { //Arrange hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242 }; var message = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { await Task.Delay(2000); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); var runOnceJobCompleted = new TaskCompletionSource<bool>(); _jobDispatcher.Setup(x => x.RunOnceJobCompleted) .Returns(runOnceJobCompleted); _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>())) .Callback(() => { runOnceJobCompleted.TrySetResult(true); }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run", "--once" }); Task<int> agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to run one job and exit await Task.WhenAny(agentTask, Task.Delay(30000)); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.Result == Constants.Agent.ReturnCode.Success); _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(), $"{nameof(_jobDispatcher.Object.Run)} was not invoked."); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestRunOnceOnlyTakeOneJobMessage() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { //Arrange hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242 }; var message1 = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }; var message2 = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4235, MessageType = JobRequestMessageTypes.AgentJobRequest }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message1); messages.Enqueue(message2); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { await Task.Delay(2000); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); var runOnceJobCompleted = new TaskCompletionSource<bool>(); _jobDispatcher.Setup(x => x.RunOnceJobCompleted) .Returns(runOnceJobCompleted); _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>())) .Callback(() => { runOnceJobCompleted.TrySetResult(true); }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run", "--once" }); Task<int> agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to run one job and exit await Task.WhenAny(agentTask, Task.Delay(30000)); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.Result == Constants.Agent.ReturnCode.Success); _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(), $"{nameof(_jobDispatcher.Object.Run)} was not invoked."); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestRunOnceHandleUpdateMessage() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { //Arrange hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); hc.SetSingleton<ISelfUpdater>(_updater.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242, AgentId = 5678 }; var message1 = new TaskAgentMessage() { Body = JsonUtility.ToString(new AgentRefreshMessage(settings.AgentId, "2.123.0")), MessageId = 4234, MessageType = AgentRefreshMessage.MessageType }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message1); _updater.Setup(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), It.IsAny<bool>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(true)); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { await Task.Delay(2000); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run", "--once" }); Task<int> agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to exit with right return code await Task.WhenAny(agentTask, Task.Delay(30000)); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.Result == Constants.Agent.ReturnCode.RunOnceAgentUpdating); _updater.Verify(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), false, It.IsAny<CancellationToken>()), Times.Once); _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Never()); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once()); } } [Theory] [Trait("Level", "L0")] [Trait("Category", "Agent")] [InlineData("--help")] [InlineData("--version")] [InlineData("--commit")] [InlineData("--bad-argument", Constants.Agent.ReturnCode.TerminatedError)] public async void TestInfoArgumentsCLI(string arg, int expected=Constants.Agent.ReturnCode.Success) { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new[] { arg }); _configurationManager.Setup(x => x.IsConfigured()). Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); using (var agent = new Agent.Listener.Agent()) { agent.Initialize(hc); var status = await agent.ExecuteCommand(command); Assert.True(status == expected, $"Expected {arg} to return {expected} exit code. Got: {status}"); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestExitsIfUnconfigured() { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new[] { "run" }); _configurationManager.Setup(x => x.IsConfigured()). Returns(false); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); using (var agent = new Agent.Listener.Agent()) { agent.Initialize(hc); var status = await agent.ExecuteCommand(command); Assert.True(status != Constants.Agent.ReturnCode.Success, $"Expected to return unsuccessful exit code if not configured. Got: {status}"); } } } [Theory] [Trait("Level", "L0")] [Trait("Category", "Agent")] [InlineData("configure", false)] [InlineData("configure", true)] //TODO: this passes. If already configured, probably should error out asked to configure again [InlineData("remove", false)] //TODO: this passes. If already not configured, probably should error out [InlineData("remove", true)] public async void TestConfigureCLI(string arg, bool IsConfigured, int expected=Constants.Agent.ReturnCode.Success) { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new[] { arg }); _configurationManager.Setup(x => x.IsConfigured()). Returns(IsConfigured); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configurationManager.Setup(x => x.ConfigureAsync(It.IsAny<CommandSettings>())) .Returns(Task.CompletedTask); _configurationManager.Setup(x => x.UnconfigureAsync(It.IsAny<CommandSettings>())) .Returns(Task.CompletedTask); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); using (var agent = new Agent.Listener.Agent()) { agent.Initialize(hc); var status = await agent.ExecuteCommand(command); Assert.True(status == expected, $"Expected to return {expected} exit code after {arg}. Got: {status}"); // config/unconfig throw exceptions _configurationManager.Setup(x => x.ConfigureAsync(It.IsAny<CommandSettings>())) .Throws(new Exception("Test Exception During Configure")); _configurationManager.Setup(x => x.UnconfigureAsync(It.IsAny<CommandSettings>())) .Throws(new Exception("Test Exception During Unconfigure")); } using (var agent2 = new Agent.Listener.Agent()) { agent2.Initialize(hc); var status2 = await agent2.ExecuteCommand(command); Assert.True(status2 == Constants.Agent.ReturnCode.TerminatedError, $"Expected to return terminated exit code when handling exception after {arg}. Got: {status2}"); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 1 job message and one metadata message public async void TestMetadataUpdate() { using (var hc = new TestHostContext(this)) using (var agent = new Agent.Listener.Agent()) { //Arrange hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IAgentCertificateManager>(_cert.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242 }; var message = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }; var metadataMessage = new TaskAgentMessage() { Body = JsonUtility.ToString(new JobMetadataMessage() { PostLinesFrequencyMillis = 500 }), MessageId = 4235, MessageType = JobEventTypes.JobMetadataUpdate }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message); messages.Enqueue(metadataMessage); var signalWorkerComplete = new SemaphoreSlim(0, 1); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { signalWorkerComplete.Release(); await Task.Delay(2000, hc.AgentShutdownToken); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run" }); Task agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to run one job if (!await signalWorkerComplete.WaitAsync(2000)) { Assert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked."); } else { //Act hc.ShutdownAgent(ShutdownReason.UserCancelled); //stop Agent //Assert Task[] taskToWait2 = { agentTask, Task.Delay(2000) }; //wait for the Agent to exit await Task.WhenAny(taskToWait2); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.IsCanceled); _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(), $"{nameof(_jobDispatcher.Object.Run)} was not invoked."); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce()); } } } } }
// 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.ComponentModel; using System.Diagnostics; using System.Dynamic; using System.Reflection; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio; namespace TestUtilities { public class WpfProxy : IDisposable { private readonly Thread _thread; private readonly Dispatcher _dispatcher; private bool _isDisposed; public WpfProxy() { using (var ready = new AutoResetEvent(false)) { _thread = new Thread(ControllerThread); _thread.SetApartmentState(ApartmentState.STA); _thread.Name = "Wpf Proxy Thread"; _thread.Start(ready); ready.WaitOne(); } for (int retries = 10; (_dispatcher = Dispatcher.FromThread(_thread)) == null && retries > 0; --retries) { Thread.Sleep(10); Console.WriteLine("Retry {0}", retries); } if (_dispatcher == null) { _thread.Abort(); throw new InvalidOperationException("Unable to get dispatcher"); } // Allow plenty of time for the dispatcher to start responding for (int retries = 50; retries > 0; --retries) { try { _dispatcher.Invoke(() => { }); break; } catch (OperationCanceledException) { Thread.Sleep(100); } } } public static WpfProxy FromObject(object obj) { var proxy = obj as WpfObjectProxy; if (proxy != null) { return proxy._provider; } return null; } private void ControllerThread(object obj) { var dispatcher = Dispatcher.FromThread(Thread.CurrentThread); ((AutoResetEvent)obj).Set(); Dispatcher.Run(); } public dynamic Create<T>(Func<T> creator) where T : DependencyObject { return new WpfObjectProxy<T>(this, InvokeWithRetry(creator)); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_isDisposed) { return; } _isDisposed = true; if (disposing) { GC.SuppressFinalize(this); if (_dispatcher != null) { _dispatcher.BeginInvokeShutdown(DispatcherPriority.Send); } } if (_thread != null && !_thread.Join(1000)) { try { _thread.Abort(); } catch (ThreadStateException) { } } } ~WpfProxy() { Dispose(false); } public bool IsDisposed { get { return _isDisposed; } } public void InvokeWithRetry(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { for (int retries = 100; retries > 0; --retries) { try { _dispatcher.Invoke(action, priority); return; } catch (OperationCanceledException) { Thread.Sleep(10); } } throw new OperationCanceledException(); } public T InvokeWithRetry<T>(Func<T> action, DispatcherPriority priority = DispatcherPriority.Normal) { for (int retries = 100; retries > 0; --retries) { try { return _dispatcher.Invoke(action, priority); } catch (OperationCanceledException) { Thread.Sleep(10); } } throw new OperationCanceledException(); } public void Invoke(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { _dispatcher.Invoke(action, priority); } public void Invoke(Action action, DispatcherPriority priority, TimeSpan timeout) { _dispatcher.Invoke(action, priority, CancellationToken.None, timeout); } public T Invoke<T>(Func<T> action, DispatcherPriority priority = DispatcherPriority.Normal) { return _dispatcher.Invoke(action, priority); } public T Invoke<T>(Func<T> action, DispatcherPriority priority, TimeSpan timeout) { return _dispatcher.Invoke(action, priority, CancellationToken.None, timeout); } public async Task InvokeAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { await _dispatcher.InvokeAsync(action, priority); } public async Task<T> InvokeAsync<T>(Func<T> action, DispatcherPriority priority = DispatcherPriority.Normal) { return await _dispatcher.InvokeAsync(action, priority); } public bool CanExecute(RoutedCommand command, object target, object parameter) { target = WpfObjectProxy.UnwrapIfProxy(target); if (!(target is IInputElement)) { return false; } parameter = WpfObjectProxy.UnwrapIfProxy(parameter); return Invoke( () => command.CanExecute(parameter, (IInputElement)target), DispatcherPriority.SystemIdle ); } public Task Execute(RoutedCommand command, object target, object parameter) { target = WpfObjectProxy.UnwrapIfProxy(target); if (!(target is IInputElement)) { throw new InvalidOperationException("Cannot execute command on " + ToString()); } parameter = WpfObjectProxy.UnwrapIfProxy(parameter); return InvokeAsync(() => command.Execute(parameter, target as IInputElement)); } } public class WpfObjectProxy : DynamicObject { protected internal readonly WpfProxy _provider; protected internal readonly DependencyObject _object; internal static object UnwrapIfProxy(object value) { var proxy = value as WpfObjectProxy; return (proxy != null) ? proxy._object : value; } protected internal WpfObjectProxy(WpfProxy provider, DependencyObject obj) { _provider = provider; _object = obj; } public override string ToString() { return string.Format("{0}<{1}>", GetType().Name, _object.GetType().Name); } public Dispatcher Dispatcher { get { return _object.Dispatcher; } } public U GetValue<U>(DependencyProperty property) { if (Dispatcher.CheckAccess()) { return (U)_object.GetValue(property); } else { return Dispatcher.Invoke( () => (U)_object.GetValue(property), DispatcherPriority.SystemIdle ); } } public void SetValue<U>(DependencyProperty property, U value) { Dispatcher.Invoke(() => _object.SetCurrentValue(property, value)); } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (base.TryInvokeMember(binder, args, out result)) { return true; } var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (binder.IgnoreCase) { flags |= BindingFlags.IgnoreCase; } var method = _object.GetType().GetMethod(binder.Name, flags); if (method != null) { result = method.Invoke(_object, args); return true; } return false; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (base.TryGetMember(binder, out result)) { return true; } var flags = BindingFlags.Static | BindingFlags.Public; if (binder.IgnoreCase) { flags |= BindingFlags.IgnoreCase; } var field = _object.GetType().GetField(binder.Name + "Property", flags); if (field != null) { var dp = field.GetValue(_object) as DependencyProperty; if (dp != null) { result = GetValue<object>(dp); return true; } } flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (binder.IgnoreCase) { flags |= BindingFlags.IgnoreCase; } field = _object.GetType().GetField(binder.Name, flags); if (field != null) { result = field.GetValue(_object); return true; } var prop = _object.GetType().GetProperty(binder.Name, flags); if (prop != null && prop.CanRead) { result = prop.GetValue(_object); return true; } return false; } public override bool TrySetMember(SetMemberBinder binder, object value) { if (base.TrySetMember(binder, value)) { return true; } var flags = BindingFlags.Static | BindingFlags.Public; if (binder.IgnoreCase) { flags |= BindingFlags.IgnoreCase; } var field = _object.GetType().GetField(binder.Name + "Property", flags); if (field != null) { var dp = field.GetValue(_object) as DependencyProperty; if (dp != null) { SetValue(dp, value); return true; } } flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (binder.IgnoreCase) { flags |= BindingFlags.IgnoreCase; } field = _object.GetType().GetField(binder.Name, flags); if (field != null && !field.IsInitOnly) { field.SetValue(_object, value); return true; } var prop = _object.GetType().GetProperty(binder.Name, flags); if (prop != null && prop.CanWrite) { prop.SetValue(_object, value); return true; } return false; } } public class WpfObjectProxy<T> : WpfObjectProxy where T : DependencyObject { private static DependencyObject Unwrap(dynamic obj) { return (T)WpfObjectProxy.UnwrapIfProxy(obj); } public WpfObjectProxy(WpfProxy provider, object obj) : base(provider, Unwrap(obj)) { } public T Object { get { return (T)_object; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Monitoring.Alerts; using Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.Monitoring.Alerts { /// <summary> /// Operations for managing the alert rules. /// </summary> internal partial class RuleOperations : IServiceOperations<AlertsClient>, IRuleOperations { /// <summary> /// Initializes a new instance of the RuleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RuleOperations(AlertsClient client) { this._client = client; } private AlertsClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Monitoring.Alerts.AlertsClient. /// </summary> public AlertsClient Client { get { return this._client; } } /// <param name='parameters'> /// Required. The rule to create or update. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateAsync(RuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/monitoring/alertrules/"; if (parameters.Rule != null && parameters.Rule.Id != null) { url = url + Uri.EscapeDataString(parameters.Rule.Id); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject ruleCreateOrUpdateParametersValue = new JObject(); requestDoc = ruleCreateOrUpdateParametersValue; if (parameters.Rule != null) { if (parameters.Rule.Id != null) { ruleCreateOrUpdateParametersValue["Id"] = parameters.Rule.Id; } if (parameters.Rule.Name != null) { ruleCreateOrUpdateParametersValue["Name"] = parameters.Rule.Name; } if (parameters.Rule.Description != null) { ruleCreateOrUpdateParametersValue["Description"] = parameters.Rule.Description; } ruleCreateOrUpdateParametersValue["IsEnabled"] = parameters.Rule.IsEnabled; if (parameters.Rule.Condition != null) { JObject conditionValue = new JObject(); ruleCreateOrUpdateParametersValue["Condition"] = conditionValue; if (parameters.Rule.Condition is ThresholdRuleCondition) { conditionValue["odata.type"] = parameters.Rule.Condition.GetType().FullName; ThresholdRuleCondition derived = ((ThresholdRuleCondition)parameters.Rule.Condition); if (derived.DataSource != null) { JObject dataSourceValue = new JObject(); conditionValue["DataSource"] = dataSourceValue; if (derived.DataSource is RuleMetricDataSource) { dataSourceValue["odata.type"] = derived.DataSource.GetType().FullName; RuleMetricDataSource derived2 = ((RuleMetricDataSource)derived.DataSource); if (derived2.ResourceId != null) { dataSourceValue["ResourceId"] = derived2.ResourceId; } if (derived2.MetricNamespace != null) { dataSourceValue["MetricNamespace"] = derived2.MetricNamespace; } if (derived2.MetricName != null) { dataSourceValue["MetricName"] = derived2.MetricName; } } } conditionValue["Operator"] = derived.Operator.ToString(); conditionValue["Threshold"] = derived.Threshold; conditionValue["WindowSize"] = XmlConvert.ToString(derived.WindowSize); } } if (parameters.Rule.Actions != null) { if (parameters.Rule.Actions is ILazyCollection == false || ((ILazyCollection)parameters.Rule.Actions).IsInitialized) { JArray actionsArray = new JArray(); foreach (RuleAction actionsItem in parameters.Rule.Actions) { JObject ruleActionValue = new JObject(); actionsArray.Add(ruleActionValue); if (actionsItem is RuleEmailAction) { ruleActionValue["odata.type"] = actionsItem.GetType().FullName; RuleEmailAction derived3 = ((RuleEmailAction)actionsItem); ruleActionValue["SendToServiceOwners"] = derived3.SendToServiceOwners; if (derived3.CustomEmails != null) { if (derived3.CustomEmails is ILazyCollection == false || ((ILazyCollection)derived3.CustomEmails).IsInitialized) { JArray customEmailsArray = new JArray(); foreach (string customEmailsItem in derived3.CustomEmails) { customEmailsArray.Add(customEmailsItem); } ruleActionValue["CustomEmails"] = customEmailsArray; } } } } ruleCreateOrUpdateParametersValue["Actions"] = actionsArray; } } ruleCreateOrUpdateParametersValue["LastUpdatedTime"] = parameters.Rule.LastUpdatedTime; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AzureOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='ruleId'> /// Required. The id of the rule to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string ruleId, CancellationToken cancellationToken) { // Validate if (ruleId == null) { throw new ArgumentNullException("ruleId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ruleId", ruleId); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/monitoring/alertrules/"; url = url + Uri.EscapeDataString(ruleId); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AzureOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='ruleId'> /// Required. The id of the rule to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Rule operation response. /// </returns> public async Task<RuleGetResponse> GetAsync(string ruleId, CancellationToken cancellationToken) { // Validate if (ruleId == null) { throw new ArgumentNullException("ruleId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ruleId", ruleId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/monitoring/alertrules/"; url = url + Uri.EscapeDataString(ruleId); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RuleGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RuleGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Rule ruleInstance = new Rule(); result.Rule = ruleInstance; JToken idValue = responseDoc["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ruleInstance.Id = idInstance; } JToken nameValue = responseDoc["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); ruleInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["Description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); ruleInstance.Description = descriptionInstance; } JToken isEnabledValue = responseDoc["IsEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); ruleInstance.IsEnabled = isEnabledInstance; } JToken conditionValue = responseDoc["Condition"]; if (conditionValue != null && conditionValue.Type != JTokenType.Null) { string typeName = ((string)conditionValue["odata.type"]); if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition") { ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition(); JToken dataSourceValue = conditionValue["DataSource"]; if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null) { string typeName2 = ((string)dataSourceValue["odata.type"]); if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource") { RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource(); JToken resourceIdValue = dataSourceValue["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); ruleMetricDataSourceInstance.ResourceId = resourceIdInstance; } JToken metricNamespaceValue = dataSourceValue["MetricNamespace"]; if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null) { string metricNamespaceInstance = ((string)metricNamespaceValue); ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance; } JToken metricNameValue = dataSourceValue["MetricName"]; if (metricNameValue != null && metricNameValue.Type != JTokenType.Null) { string metricNameInstance = ((string)metricNameValue); ruleMetricDataSourceInstance.MetricName = metricNameInstance; } thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance; } } JToken operatorValue = conditionValue["Operator"]; if (operatorValue != null && operatorValue.Type != JTokenType.Null) { ConditionOperator operatorInstance = ((ConditionOperator)Enum.Parse(typeof(ConditionOperator), ((string)operatorValue), true)); thresholdRuleConditionInstance.Operator = operatorInstance; } JToken thresholdValue = conditionValue["Threshold"]; if (thresholdValue != null && thresholdValue.Type != JTokenType.Null) { double thresholdInstance = ((double)thresholdValue); thresholdRuleConditionInstance.Threshold = thresholdInstance; } JToken windowSizeValue = conditionValue["WindowSize"]; if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null) { TimeSpan windowSizeInstance = XmlConvert.ToTimeSpan(((string)windowSizeValue)); thresholdRuleConditionInstance.WindowSize = windowSizeInstance; } ruleInstance.Condition = thresholdRuleConditionInstance; } } JToken actionsArray = responseDoc["Actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { string typeName3 = ((string)actionsValue["odata.type"]); if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction") { RuleEmailAction ruleEmailActionInstance = new RuleEmailAction(); JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"]; if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null) { bool sendToServiceOwnersInstance = ((bool)sendToServiceOwnersValue); ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance; } JToken customEmailsArray = actionsValue["CustomEmails"]; if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null) { foreach (JToken customEmailsValue in ((JArray)customEmailsArray)) { ruleEmailActionInstance.CustomEmails.Add(((string)customEmailsValue)); } } ruleInstance.Actions.Add(ruleEmailActionInstance); } } } JToken lastUpdatedTimeValue = responseDoc["LastUpdatedTime"]; if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null) { DateTime lastUpdatedTimeInstance = ((DateTime)lastUpdatedTimeValue); ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List the alert rules within a subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Rules operation response. /// </returns> public async Task<RuleListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/monitoring/alertrules"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RuleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RuleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["Value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Rule ruleInstance = new Rule(); result.Value.Add(ruleInstance); JToken idValue = valueValue["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ruleInstance.Id = idInstance; } JToken nameValue = valueValue["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); ruleInstance.Name = nameInstance; } JToken descriptionValue = valueValue["Description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); ruleInstance.Description = descriptionInstance; } JToken isEnabledValue = valueValue["IsEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); ruleInstance.IsEnabled = isEnabledInstance; } JToken conditionValue = valueValue["Condition"]; if (conditionValue != null && conditionValue.Type != JTokenType.Null) { string typeName = ((string)conditionValue["odata.type"]); if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition") { ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition(); JToken dataSourceValue = conditionValue["DataSource"]; if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null) { string typeName2 = ((string)dataSourceValue["odata.type"]); if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource") { RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource(); JToken resourceIdValue = dataSourceValue["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); ruleMetricDataSourceInstance.ResourceId = resourceIdInstance; } JToken metricNamespaceValue = dataSourceValue["MetricNamespace"]; if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null) { string metricNamespaceInstance = ((string)metricNamespaceValue); ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance; } JToken metricNameValue = dataSourceValue["MetricName"]; if (metricNameValue != null && metricNameValue.Type != JTokenType.Null) { string metricNameInstance = ((string)metricNameValue); ruleMetricDataSourceInstance.MetricName = metricNameInstance; } thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance; } } JToken operatorValue = conditionValue["Operator"]; if (operatorValue != null && operatorValue.Type != JTokenType.Null) { ConditionOperator operatorInstance = ((ConditionOperator)Enum.Parse(typeof(ConditionOperator), ((string)operatorValue), true)); thresholdRuleConditionInstance.Operator = operatorInstance; } JToken thresholdValue = conditionValue["Threshold"]; if (thresholdValue != null && thresholdValue.Type != JTokenType.Null) { double thresholdInstance = ((double)thresholdValue); thresholdRuleConditionInstance.Threshold = thresholdInstance; } JToken windowSizeValue = conditionValue["WindowSize"]; if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null) { TimeSpan windowSizeInstance = XmlConvert.ToTimeSpan(((string)windowSizeValue)); thresholdRuleConditionInstance.WindowSize = windowSizeInstance; } ruleInstance.Condition = thresholdRuleConditionInstance; } } JToken actionsArray = valueValue["Actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { string typeName3 = ((string)actionsValue["odata.type"]); if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction") { RuleEmailAction ruleEmailActionInstance = new RuleEmailAction(); JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"]; if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null) { bool sendToServiceOwnersInstance = ((bool)sendToServiceOwnersValue); ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance; } JToken customEmailsArray = actionsValue["CustomEmails"]; if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null) { foreach (JToken customEmailsValue in ((JArray)customEmailsArray)) { ruleEmailActionInstance.CustomEmails.Add(((string)customEmailsValue)); } } ruleInstance.Actions.Add(ruleEmailActionInstance); } } } JToken lastUpdatedTimeValue = valueValue["LastUpdatedTime"]; if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null) { DateTime lastUpdatedTimeInstance = ((DateTime)lastUpdatedTimeValue); ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Security; using System.Collections.Generic; using System.Runtime.InteropServices; namespace System.Net.Sockets { internal sealed class DynamicWinsockMethods { // In practice there will never be more than four of these, so its not worth a complicated // hash table structure. Store them in a list and search through it. private static List<DynamicWinsockMethods> s_methodTable = new List<DynamicWinsockMethods>(); public static DynamicWinsockMethods GetMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { lock (s_methodTable) { DynamicWinsockMethods methods; for (int i = 0; i < s_methodTable.Count; i++) { methods = s_methodTable[i]; if (methods._addressFamily == addressFamily && methods._socketType == socketType && methods._protocolType == protocolType) { return methods; } } methods = new DynamicWinsockMethods(addressFamily, socketType, protocolType); s_methodTable.Add(methods); return methods; } } private AddressFamily _addressFamily; private SocketType _socketType; private ProtocolType _protocolType; private object _lockObject; private AcceptExDelegate _acceptEx; private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs; private ConnectExDelegate _connectEx; private TransmitPacketsDelegate _transmitPackets; private DisconnectExDelegate _disconnectEx; private DisconnectExDelegateBlocking _disconnectExBlocking; private WSARecvMsgDelegate _recvMsg; private WSARecvMsgDelegateBlocking _recvMsgBlocking; private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { _addressFamily = addressFamily; _socketType = socketType; _protocolType = protocolType; _lockObject = new object(); } public T GetDelegate<T>(SafeCloseSocket socketHandle) where T : class { if (typeof(T) == typeof(AcceptExDelegate)) { EnsureAcceptEx(socketHandle); return (T)(object)_acceptEx; } else if (typeof(T) == typeof(GetAcceptExSockaddrsDelegate)) { EnsureGetAcceptExSockaddrs(socketHandle); return (T)(object)_getAcceptExSockaddrs; } else if (typeof(T) == typeof(ConnectExDelegate)) { EnsureConnectEx(socketHandle); return (T)(object)_connectEx; } else if (typeof(T) == typeof(DisconnectExDelegate)) { EnsureDisconnectEx(socketHandle); return (T)(object)_disconnectEx; } else if (typeof(T) == typeof(DisconnectExDelegateBlocking)) { EnsureDisconnectEx(socketHandle); return (T)(object)_disconnectExBlocking; } else if (typeof(T) == typeof(WSARecvMsgDelegate)) { EnsureWSARecvMsg(socketHandle); return (T)(object)_recvMsg; } else if (typeof(T) == typeof(WSARecvMsgDelegateBlocking)) { EnsureWSARecvMsg(socketHandle); return (T)(object)_recvMsgBlocking; } else if (typeof(T) == typeof(TransmitPacketsDelegate)) { EnsureTransmitPackets(socketHandle); return (T)(object)_transmitPackets; } System.Diagnostics.Debug.Assert(false, "Invalid type passed to DynamicWinsockMethods.GetDelegate"); return null; } // Private methods that actually load the function pointers. private IntPtr LoadDynamicFunctionPointer(SafeCloseSocket socketHandle, ref Guid guid) { IntPtr ptr = IntPtr.Zero; int length; SocketError errorCode; unsafe { errorCode = Interop.Winsock.WSAIoctl( socketHandle, Interop.Winsock.IoctlSocketConstants.SIOGETEXTENSIONFUNCTIONPOINTER, ref guid, sizeof(Guid), out ptr, sizeof(IntPtr), out length, IntPtr.Zero, IntPtr.Zero); } if (errorCode != SocketError.Success) { throw new SocketException(); } return ptr; } private void EnsureAcceptEx(SafeCloseSocket socketHandle) { if (_acceptEx == null) { lock (_lockObject) { if (_acceptEx == null) { Guid guid = new Guid("{0xb5367df1,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrAcceptEx = LoadDynamicFunctionPointer(socketHandle, ref guid); _acceptEx = Marshal.GetDelegateForFunctionPointer<AcceptExDelegate>(ptrAcceptEx); } } } } private void EnsureGetAcceptExSockaddrs(SafeCloseSocket socketHandle) { if (_getAcceptExSockaddrs == null) { lock (_lockObject) { if (_getAcceptExSockaddrs == null) { Guid guid = new Guid("{0xb5367df2,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}"); IntPtr ptrGetAcceptExSockaddrs = LoadDynamicFunctionPointer(socketHandle, ref guid); _getAcceptExSockaddrs = Marshal.GetDelegateForFunctionPointer<GetAcceptExSockaddrsDelegate>(ptrGetAcceptExSockaddrs); } } } } private void EnsureConnectEx(SafeCloseSocket socketHandle) { if (_connectEx == null) { lock (_lockObject) { if (_connectEx == null) { Guid guid = new Guid("{0x25a207b9,0x0ddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}"); IntPtr ptrConnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid); _connectEx = Marshal.GetDelegateForFunctionPointer<ConnectExDelegate>(ptrConnectEx); } } } } private void EnsureDisconnectEx(SafeCloseSocket socketHandle) { if (_disconnectEx == null) { lock (_lockObject) { if (_disconnectEx == null) { Guid guid = new Guid("{0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}"); IntPtr ptrDisconnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid); _disconnectEx = Marshal.GetDelegateForFunctionPointer<DisconnectExDelegate>(ptrDisconnectEx); _disconnectExBlocking = Marshal.GetDelegateForFunctionPointer<DisconnectExDelegateBlocking>(ptrDisconnectEx); } } } } private void EnsureWSARecvMsg(SafeCloseSocket socketHandle) { if (_recvMsg == null) { lock (_lockObject) { if (_recvMsg == null) { Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}"); IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid); _recvMsg = Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegate>(ptrWSARecvMsg); _recvMsgBlocking = Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg); } } } } private void EnsureTransmitPackets(SafeCloseSocket socketHandle) { if (_transmitPackets == null) { lock (_lockObject) { if (_transmitPackets == null) { Guid guid = new Guid("{0xd9689da0,0x1f90,0x11d3,{0x99,0x71,0x00,0xc0,0x4f,0x68,0xc8,0x76}}"); IntPtr ptrTransmitPackets = LoadDynamicFunctionPointer(socketHandle, ref guid); _transmitPackets = Marshal.GetDelegateForFunctionPointer<TransmitPacketsDelegate>(ptrTransmitPackets); } } } } } internal delegate bool AcceptExDelegate( SafeCloseSocket listenSocketHandle, SafeCloseSocket acceptSocketHandle, IntPtr buffer, int len, int localAddressLength, int remoteAddressLength, out int bytesReceived, SafeHandle overlapped); internal delegate void GetAcceptExSockaddrsDelegate( IntPtr buffer, int receiveDataLength, int localAddressLength, int remoteAddressLength, out IntPtr localSocketAddress, out int localSocketAddressLength, out IntPtr remoteSocketAddress, out int remoteSocketAddressLength); internal delegate bool ConnectExDelegate( SafeCloseSocket socketHandle, IntPtr socketAddress, int socketAddressSize, IntPtr buffer, int dataLength, out int bytesSent, SafeHandle overlapped); internal delegate bool DisconnectExDelegate(SafeCloseSocket socketHandle, SafeHandle overlapped, int flags, int reserved); internal delegate bool DisconnectExDelegateBlocking(IntPtr socketHandle, IntPtr overlapped, int flags, int reserved); internal delegate SocketError WSARecvMsgDelegate( SafeCloseSocket socketHandle, IntPtr msg, out int bytesTransferred, SafeHandle overlapped, IntPtr completionRoutine); internal delegate SocketError WSARecvMsgDelegateBlocking( IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine); internal delegate bool TransmitPacketsDelegate( SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped, TransmitFileOptions flags); }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used when rendering a Customer field. /// </summary> public class CustomerControlTemplate : CellTemplate, ICustomFieldControlTemplate { /// <summary> /// CustomerControlTemplate class initialization. /// </summary> /// <param name="field"></param> /// <param name="metadata"></param> /// <param name="validationGroup"></param> /// <param name="bindings"></param> public CustomerControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings) : base(metadata, validationGroup, bindings) { Field = field; } public override string CssClass { get { return "lookup form-control"; } } /// <summary> /// Form field. /// </summary> public CrmEntityFormViewField Field { get; private set; } private string ValidationText { get { return Metadata.ValidationText; } } private ValidatorDisplay ValidatorDisplay { get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; } } protected override void InstantiateControlIn(Control container) { var dropDown = new DropDownList { ID = ControlID, CssClass = string.Join(" ", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip }; dropDown.Attributes.Add("onchange", "setIsDirty(this.id);"); container.Controls.Add(dropDown); if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { dropDown.Attributes.Add("required", string.Empty); } var context = CrmConfigurationManager.CreateContext(); if (Metadata.ReadOnly || ((WebControls.CrmEntityFormView)container.BindingContainer).Mode == FormViewMode.ReadOnly) { AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, context, dropDown); } else { PopulateDropDownIfFirstLoad(context, dropDown); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; if (Guid.TryParse(dropDown.SelectedValue, out id)) { foreach (var lookupTarget in Metadata.LookupTargets) { var lookupTargetId = GetEntityMetadata(context, lookupTarget).PrimaryIdAttribute; var foundEntity = context.CreateQuery(lookupTarget).FirstOrDefault(e => e.GetAttributeValue<Guid?>(lookupTargetId) == id); if (foundEntity != null) { return new EntityReference(lookupTarget, id); } } } return null; }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.SelectedValue = entityReference.Id.ToString(); } }; } } protected override void InstantiateValidatorsIn(Control container) { if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { container.Controls.Add(new RequiredFieldValidator { ID = string.Format("RequiredFieldValidator{0}", ControlID), ControlToValidate = ControlID, ValidationGroup = ValidationGroup, Display = ValidatorDisplay, ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)), Text = Metadata.ValidationText, }); } this.InstantiateCustomValidatorsIn(container); } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(Control container, OrganizationServiceContext context, DropDownList dropDown) { dropDown.CssClass = "{0} readonly".FormatWith(CssClass); dropDown.Attributes["disabled"] = "disabled"; dropDown.Attributes["aria-disabled"] = "true"; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID) }; container.Controls.Add(hiddenValue); var hiddenSelectedIndex = new HiddenField { ID = "{0}_SelectedIndex".FormatWith(ControlID) }; container.Controls.Add(hiddenSelectedIndex); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; if (Guid.TryParse(hiddenValue.Value, out id)) { foreach (var lookupTarget in Metadata.LookupTargets) { var lookupTargetId = GetEntityMetadata(context, lookupTarget).PrimaryIdAttribute; var foundEntity = context.CreateQuery(lookupTarget).FirstOrDefault(e => e.GetAttributeValue<Guid?>(lookupTargetId) == id); if (foundEntity != null) { return new EntityReference(lookupTarget, id); } } } return null; }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.Items.Add(new ListItem { Value = entityReference.Id.ToString(), Text = entityReference.Name ?? string.Empty }); dropDown.SelectedValue = "{0}".FormatWith(entityReference.Id); hiddenValue.Value = dropDown.SelectedValue; hiddenSelectedIndex.Value = dropDown.SelectedIndex.ToString(CultureInfo.InvariantCulture); } }; } private static string GetEntityPrimaryNameAttribute(OrganizationServiceContext context, Entity entity) { var entityMetadata = GetEntityMetadata(context, entity.LogicalName); var primaryAttributeName = entityMetadata.PrimaryNameAttribute; return entity.GetAttributeValue<string>(primaryAttributeName); } private static EntityMetadata GetEntityMetadata(OrganizationServiceContext context, string logicalName) { if (context == null) { throw new ArgumentNullException("context"); } if (string.IsNullOrEmpty(logicalName)) { throw new ArgumentNullException("logicalName"); } var metadataReponse = context.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Entity }) as RetrieveEntityResponse; if (metadataReponse != null && metadataReponse.EntityMetadata != null) { return metadataReponse.EntityMetadata; } throw new InvalidOperationException("Unable to retrieve the metadata for entity name {0}.".FormatWith(logicalName)); } private void PopulateDropDownIfFirstLoad(OrganizationServiceContext context, ListControl dropDown) { if (dropDown.Items.Count > 0) { return; } var empty = new ListItem(string.Empty, string.Empty); empty.Attributes["label"] = " "; dropDown.Items.Add(empty); var lookupEntities = new List<Entity>(); foreach (var entities in Metadata.LookupTargets.Select(context.CreateQuery)) { lookupEntities.AddRange(entities); } foreach (var entity in lookupEntities) { var listitem = new ListItem { Value = entity.Id.ToString(), Text = GetEntityPrimaryNameAttribute(context, entity) }; // We may have to check if the entity is the same as the CrmEntityFormView // Adding a lookup back to oneself may cause an error. dropDown.Items.Add(listitem); } } } }
using System; using System.Configuration; using System.Drawing; 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 System.IO; using umbraco.DataLayer; using umbraco.BusinessLogic; using umbraco.editorControls; using Umbraco.Core.IO; using System.Collections.Generic; using umbraco.cms.businesslogic.datatype; namespace umbraco.editorControls.userControlGrapper { public class usercontrolPrevalueEditor : System.Web.UI.WebControls.PlaceHolder, umbraco.interfaces.IDataPrevalue { public ISqlHelper SqlHelper { get { return Application.SqlHelper; } } #region IDataPrevalue Members // referenced datatype private umbraco.cms.businesslogic.datatype.BaseDataType _datatype; private DropDownList _dropdownlist; private DropDownList _dropdownlistUserControl; private PlaceHolder _phSettings; private Dictionary<string, DataEditorSettingType> dtSettings = new Dictionary<string, DataEditorSettingType>(); public usercontrolPrevalueEditor(umbraco.cms.businesslogic.datatype.BaseDataType DataType) { // state it knows its datatypedefinitionid _datatype = DataType; setupChildControls(); } private void setupChildControls() { _dropdownlist = new DropDownList(); _dropdownlist.ID = "dbtype"; _dropdownlist.Items.Add(DBTypes.Date.ToString()); _dropdownlist.Items.Add(DBTypes.Integer.ToString()); _dropdownlist.Items.Add(DBTypes.Ntext.ToString()); _dropdownlist.Items.Add(DBTypes.Nvarchar.ToString()); _dropdownlistUserControl = new DropDownList(); _dropdownlistUserControl.ID = "usercontrol"; _phSettings = new PlaceHolder(); _phSettings.ID = "settings"; // put the childcontrols in context - ensuring that // the viewstate is persisted etc. Controls.Add(_dropdownlist); Controls.Add(_dropdownlistUserControl); Controls.Add(_phSettings); // populate the usercontrol dropdown _dropdownlistUserControl.Items.Add(new ListItem(ui.Text("choose"), "")); populateUserControls( IOHelper.MapPath( SystemDirectories.UserControls) ); } private void populateUserControls(string path) { DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo uc in di.GetFiles("*.ascx")) { string ucRoot = IOHelper.MapPath(SystemDirectories.UserControls); _dropdownlistUserControl.Items.Add( new ListItem(SystemDirectories.UserControls + uc.FullName.Substring(ucRoot.Length).Replace(IOHelper.DirSepChar, '/')) /* new ListItem( uc.FullName.Substring( uc.FullName.IndexOf(root), uc.FullName.Length - uc.FullName.IndexOf(root)).Replace(IOHelper.DirSepChar, '/')) */ ); } foreach (DirectoryInfo dir in di.GetDirectories()) populateUserControls(dir.FullName); } public Control Editor { get { return this; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { string config = Configuration; if (config != "") { _dropdownlistUserControl.SelectedValue = config; } _dropdownlist.SelectedValue = _datatype.DBType.ToString(); } //check for settings if (!string.IsNullOrEmpty(Configuration)) LoadSetttings(Configuration); } private Dictionary<string, DataEditorSetting> GetSettings(Type t) { Dictionary<string, DataEditorSetting> settings = new Dictionary<string, DataEditorSetting>(); foreach (System.Reflection.PropertyInfo p in t.GetProperties()) { object[] o = p.GetCustomAttributes(typeof(DataEditorSetting), true); if (o.Length > 0) settings.Add(p.Name, (DataEditorSetting)o[0]); } return settings; } private bool HasSettings(Type t) { bool hasSettings = false; foreach (System.Reflection.PropertyInfo p in t.GetProperties()) { object[] o = p.GetCustomAttributes(typeof(DataEditorSetting), true); if (o.Length > 0) { hasSettings = true; break; } } return hasSettings; } private void LoadSetttings(string fileName) { // due to legacy, some user controls may not have the tilde start if (fileName.StartsWith("~/")) fileName = fileName.Substring(2); if (System.IO.File.Exists(IOHelper.MapPath("~/" + fileName))) { UserControl oControl = (UserControl)this.Page.LoadControl(@"~/" + fileName); Type type = oControl.GetType(); Dictionary<string, DataEditorSetting> settings = GetSettings(type); foreach (KeyValuePair<string, DataEditorSetting> kv in settings) { DataEditorSettingType dst = kv.Value.GetDataEditorSettingType(); dtSettings.Add(kv.Key, dst); DataEditorPropertyPanel panel = new DataEditorPropertyPanel(); panel.Text = kv.Value.GetName(); panel.Text += "<br/><small>" + kv.Value.description + "</small>"; if (HasSettings(type)) { DataEditorSettingsStorage ss = new DataEditorSettingsStorage(); List<Setting<string, string>> s = ss.GetSettings(_datatype.DataTypeDefinitionId); ss.Dispose(); if (s.Find(set => set.Key == kv.Key).Value != null) dst.Value = s.Find(set => set.Key == kv.Key).Value; } panel.Controls.Add(dst.RenderControl(kv.Value)); Label invalid = new Label(); invalid.Attributes.Add("style", "color:#8A1F11"); invalid.ID = "lbl" + kv.Key; panel.Controls.Add(invalid); _phSettings.Controls.Add(panel); } } } public void Save() { bool hasErrors = false; foreach (KeyValuePair<string, DataEditorSettingType> k in dtSettings) { var result = k.Value.Validate(); Label lbl = FindControlRecursive<Label>(_phSettings, "lbl" + k.Key); if(result == null && lbl != null) { if(lbl != null) lbl.Text = string.Empty; } else { if(hasErrors == false) hasErrors = true; if (lbl != null) lbl.Text = " " + result.ErrorMessage; } } if (!hasErrors) { _datatype.DBType = (umbraco.cms.businesslogic.datatype.DBTypes) Enum.Parse(typeof (umbraco.cms.businesslogic.datatype.DBTypes), _dropdownlist.SelectedValue, true); // Generate data-string string data = _dropdownlistUserControl.SelectedValue; // If the add new prevalue textbox is filled out - add the value to the collection. IParameter[] SqlParams = new IParameter[] { SqlHelper.CreateParameter("@value", data), SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId) }; SqlHelper.ExecuteNonQuery("delete from cmsDataTypePreValues where datatypenodeid = @dtdefid", SqlParams); // we need to populate the parameters again due to an issue with SQL CE SqlParams = new IParameter[] { SqlHelper.CreateParameter("@value", data), SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId) }; SqlHelper.ExecuteNonQuery( "insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'')", SqlParams); //settings DataEditorSettingsStorage ss = new DataEditorSettingsStorage(); //ss.ClearSettings(_datatype.DataTypeDefinitionId); int i = 0; foreach (KeyValuePair<string, DataEditorSettingType> k in dtSettings) { ss.InsertSetting(_datatype.DataTypeDefinitionId, k.Key, k.Value.Value, i); i++; } ss.Dispose(); if (dtSettings.Count == 0) { if (!string.IsNullOrEmpty(Configuration)) LoadSetttings(Configuration); } } } protected override void Render(HtmlTextWriter writer) { writer.WriteLine("<div class=\"propertyItem\">"); writer.WriteLine("<div class=\"propertyItemheader\">Database datatype</div>"); writer.WriteLine("<div class=\"propertyItemContent\">"); _dropdownlist.RenderControl(writer); writer.Write("</div></div>"); writer.WriteLine("<div class=\"propertyItem\">"); writer.WriteLine("<div class=\"propertyItemheader\">Usercontrol:</div>"); writer.WriteLine("<div class=\"propertyItemContent\">"); _dropdownlistUserControl.RenderControl(writer); writer.Write("</div></div>"); _phSettings.RenderControl(writer); } public string Configuration { get { object conf = SqlHelper.ExecuteScalar<object>("select value from cmsDataTypePreValues where datatypenodeid = @datatypenodeid", SqlHelper.CreateParameter("@datatypenodeid", _datatype.DataTypeDefinitionId)); if (conf != null) return conf.ToString(); else return ""; } } private static T FindControlRecursive<T>(Control parent, string id) where T : Control { if ((parent is T) && (parent.ID == id)) { return (T)parent; } foreach (Control control in parent.Controls) { T foundControl = FindControlRecursive<T>(control, id); if (foundControl != null) { return foundControl; } } return default(T); } #endregion } }
namespace Ioke.Lang.Parser { using Ioke.Lang; using Ioke.Lang.Util; using System.Collections; using System.Collections.Generic; public class LevelsCreator : IOperatorShufflerFactory { public IOperatorShuffler Create(IokeObject msg, IokeObject context, IokeObject message) { return new Levels(msg, context, message); } } public class Levels : IOperatorShuffler { public const int OP_LEVEL_MAX = 32; private class Level { public IokeObject message; public enum Type {Attach, Arg, New, Unused}; public Type type; public int precedence; public Level(Type type) { this.type = type; } public void Attach(IokeObject msg) { switch(type) { case Type.Attach: Message.SetNext(message, msg); break; case Type.Arg: Message.AddArg(message, msg); break; case Type.New: message = msg; break; case Type.Unused: break; } } public void SetAwaitingFirstArg(IokeObject msg, int precedence) { this.type = Type.Arg; this.message = msg; this.precedence = precedence; } public void SetAlreadyHasArgs(IokeObject msg) { this.type = Type.Attach; this.message = msg; } public void Finish(IList<IokeObject> expressions) { if(message != null) { Message.SetNext(message, null); if(message.Arguments.Count == 1) { object arg1 = message.Arguments[0]; if(arg1 is IokeObject) { IokeObject arg = IokeObject.As(arg1, null); if(arg.Name.Length == 0 && arg.Arguments.Count == 1 && Message.GetNext(arg) == null) { int index = expressions.IndexOf(arg); if(index != -1) { expressions[index] = message; } message.Arguments.Clear(); foreach(object o in arg.Arguments) message.Arguments.Add(o); arg.Arguments.Clear(); } else if(!"'".Equals(message.Name) && arg.Name.Equals(".") && Message.GetNext(arg) == null) { message.Arguments.Clear(); } } } } type = Type.Unused; } } Runtime runtime; IDictionary operatorTable; IDictionary trinaryOperatorTable; IDictionary invertedOperatorTable; IList<Level> stack; IokeObject _message; IokeObject _context; int currentLevel; Level[] pool = new Level[OP_LEVEL_MAX]; public class OpTable { public readonly string name; public readonly int precedence; public OpTable(string name, int precedence) { this.name = name; this.precedence = precedence; } } public readonly static ICollection<string> DONT_SEPARATE_ARGUMENTS = new SaneHashSet<string>() {"and", "nand", "or", "xor", "nor"}; public static OpTable[] defaultOperators = new OpTable[]{ new OpTable("!", 0), new OpTable("?", 0), new OpTable("$", 0), new OpTable("~", 0), new OpTable("#", 0), new OpTable("**", 1), new OpTable("*", 2), new OpTable("/", 2), new OpTable("%", 2), new OpTable("+", 3), new OpTable("-", 3), new OpTable("<<", 4), new OpTable(">>", 4), new OpTable("<=>", 5), new OpTable(">", 5), new OpTable("<", 5), new OpTable("<=", 5), new OpTable(">=", 5), new OpTable("<>", 5), new OpTable("<>>", 5), new OpTable("==", 6), new OpTable("!=", 6), new OpTable("===", 6), new OpTable("=~", 6), new OpTable("!~", 6), new OpTable("&", 7), new OpTable("^", 8), new OpTable("|", 9), new OpTable("&&", 10), new OpTable("?&", 10), new OpTable("||", 11), new OpTable("?|", 11), new OpTable("..", 12), new OpTable("...", 12), new OpTable("=>", 12), new OpTable("<->", 12), new OpTable("->", 12), new OpTable("+>", 12), new OpTable("!>", 12), new OpTable("&>", 12), new OpTable("%>", 12), new OpTable("#>", 12), new OpTable("@>", 12), new OpTable("/>", 12), new OpTable("*>", 12), new OpTable("?>", 12), new OpTable("|>", 12), new OpTable("^>", 12), new OpTable("~>", 12), new OpTable("->>", 12), new OpTable("+>>", 12), new OpTable("!>>", 12), new OpTable("&>>", 12), new OpTable("%>>", 12), new OpTable("#>>", 12), new OpTable("@>>", 12), new OpTable("/>>", 12), new OpTable("*>>", 12), new OpTable("?>>", 12), new OpTable("|>>", 12), new OpTable("^>>", 12), new OpTable("~>>", 12), new OpTable("=>>", 12), new OpTable("**>", 12), new OpTable("**>>", 12), new OpTable("&&>", 12), new OpTable("&&>>", 12), new OpTable("||>", 12), new OpTable("||>>", 12), new OpTable("$>", 12), new OpTable("$>>", 12), new OpTable("+=", 13), new OpTable("-=", 13), new OpTable("**=", 13), new OpTable("*=", 13), new OpTable("/=", 13), new OpTable("%=", 13), new OpTable("and", 13), new OpTable("nand", 13), new OpTable("&=", 13), new OpTable("&&=", 13), new OpTable("^=", 13), new OpTable("or", 13), new OpTable("xor", 13), new OpTable("nor", 13), new OpTable("|=", 13), new OpTable("||=", 13), new OpTable("<<=", 13), new OpTable(">>=", 13), new OpTable("<-", 14), new OpTable("return", 14), new OpTable("import", 14) }; public static OpTable[] defaultTrinaryOperators = new OpTable[]{ new OpTable("=", 2), new OpTable("+=", 2), new OpTable("-=", 2), new OpTable("/=", 2), new OpTable("*=", 2), new OpTable("**=", 2), new OpTable("%=", 2), new OpTable("&=", 2), new OpTable("&&=", 2), new OpTable("|=", 2), new OpTable("||=", 2), new OpTable("^=", 2), new OpTable("<<=", 2), new OpTable(">>=", 2), new OpTable("++", 1), new OpTable("--", 1) }; public static OpTable[] defaultInvertedOperators = new OpTable[]{ new OpTable("::", 12), new OpTable(":::", 12) }; public interface OpTableCreator { IDictionary Create(Runtime runtime); } private class BinaryOpTableCreator : OpTableCreator { public IDictionary Create(Runtime runtime) { IDictionary table = new SaneHashtable(); foreach(OpTable ot in defaultOperators) { table[runtime.GetSymbol(ot.name)] = runtime.NewNumber(ot.precedence); } return table; } } private class TrinaryOpTableCreator : OpTableCreator { public IDictionary Create(Runtime runtime) { IDictionary table = new SaneHashtable(); foreach(OpTable ot in defaultTrinaryOperators) { table[runtime.GetSymbol(ot.name)] = runtime.NewNumber(ot.precedence); } return table; } } private class InvertedOpTableCreator : OpTableCreator { public IDictionary Create(Runtime runtime) { IDictionary table = new SaneHashtable(); foreach(OpTable ot in defaultInvertedOperators) { table[runtime.GetSymbol(ot.name)] = runtime.NewNumber(ot.precedence); } return table; } } public Levels(IokeObject msg, IokeObject context, IokeObject message) { this.runtime = context.runtime; this._context = context; this._message = message; IokeObject opTable = IokeObject.As(msg.FindCell(_message, _context, "OperatorTable"), null); if(opTable == runtime.nul) { opTable = runtime.NewFromOrigin(); opTable.Kind = "Message OperatorTable"; runtime.Message.SetCell("OperatorTable", opTable); opTable.SetCell("precedenceLevelCount", runtime.NewNumber(OP_LEVEL_MAX)); } this.operatorTable = GetOpTable(opTable, "operators", new BinaryOpTableCreator()); this.trinaryOperatorTable = GetOpTable(opTable, "trinaryOperators", new TrinaryOpTableCreator()); this.invertedOperatorTable = GetOpTable(opTable, "invertedOperators", new InvertedOpTableCreator()); this.stack = new SaneList<Level>(); this.Reset(); } public IDictionary GetOpTable(IokeObject opTable, string name, OpTableCreator creator) { IokeObject operators = IokeObject.As(opTable.FindCell(_message, _context, name), null); if(operators != runtime.nul && (IokeObject.dataOf(operators) is Dict)) { return Dict.GetMap(operators); } else { var result = creator.Create(runtime); opTable.SetCell(name, runtime.NewDict(result)); return result; } } public bool IsInverted(IokeObject messageSymbol) { return invertedOperatorTable.Contains(messageSymbol); } public int LevelForOp(string messageName, IokeObject messageSymbol, IokeObject msg) { object value = operatorTable[messageSymbol]; if(value == null) { value = invertedOperatorTable[messageSymbol]; } if(value == null) { if(messageName.Length > 0) { char first = messageName[0]; switch(first) { case '|': return 9; case '^': return 8; case '&': return 7; case '<': case '>': return 5; case '=': case '!': case '?': case '~': case '$': return 6; case '+': case '-': return 3; case '*': case '/': case '%': return 2; default: return -1; } } return -1; } return Number.GetValue(value).intValue(); } public int ArgCountForOp(string messageName, IokeObject messageSymbol, IokeObject msg) { object value = trinaryOperatorTable[messageSymbol]; if(value == null) { return -1; } return Number.GetValue(value).intValue(); } public void PopDownTo(int targetLevel, IList<IokeObject> expressions) { Level level = null; while((level = stack[0]) != null && level.precedence <= targetLevel && level.type != Level.Type.Arg) { var obj = stack[0]; stack.RemoveAt(0); obj.Finish(expressions); currentLevel--; } } private Level CurrentLevel() { return stack[0]; } private void AttachAndReplace(Level self, IokeObject msg) { self.Attach(msg); self.type = Level.Type.Attach; self.message = msg; } public void AttachToTopAndPush(IokeObject msg, int precedence) { Level top = stack[0]; AttachAndReplace(top, msg); Level level = pool[currentLevel++]; level.SetAwaitingFirstArg(msg, precedence); stack.Insert(0, level); } public void Attach(IokeObject msg, IList<IokeObject> expressions) { string messageName = Message.GetName(msg); IokeObject messageSymbol = runtime.GetSymbol(messageName); int precedence = LevelForOp(messageName, messageSymbol, msg); int argCountForOp = ArgCountForOp(messageName, messageSymbol, msg); int msgArgCount = msg.Arguments.Count; bool inverted = IsInverted(messageSymbol); /* // : "str" bar becomes :("str") bar // -foo bar becomes -(foo) bar */ if(msgArgCount == 0 && Message.GetNext(msg) != null && ((messageName.Equals(":") || messageName.Equals("`") || messageName.Equals("'")) || (messageName.Equals("-") && Message.GetPrev(msg) == null))) { precedence = -1; object arg = Message.GetNext(msg); Message.SetNext(msg, Message.GetNext(arg)); Message.SetNext(IokeObject.As(arg, null), null); msg.Arguments.Add(arg); msgArgCount++; } if(inverted && (msgArgCount == 0)) { IokeObject head = msg; while(Message.GetPrev(head) != null && !Message.IsTerminator(Message.GetPrev(head))) { head = Message.GetPrev(head); } if(head != msg) { IokeObject argPart = Message.DeepCopy(head); if(Message.GetPrev(msg) != null) { Message.SetNext(Message.GetPrev(msg), null); } Message.SetPrev(msg, null); // IokeObject beforeHead = Message.GetPrev(head); msg.Arguments.Add(argPart); IokeObject next = Message.GetNext(msg); IokeObject last = next; while(Message.GetNext(last) != null && !Message.IsTerminator(Message.GetNext(last))) { last = Message.GetNext(last); } IokeObject cont = Message.GetNext(last); Message.SetNext(msg, cont); if(cont != null) { Message.SetPrev(cont, msg); } Message.SetNext(last, msg); Message.SetPrev(msg, last); head.Become(next, null, null); } } /* // o a = b c . d becomes o =(a, b c) . d // // a attaching // = msg // b c Message.next(msg) */ if(argCountForOp != -1 && (msgArgCount == 0) && !((Message.GetNext(msg) != null) && Message.GetName(Message.GetNext(msg)).Equals("="))) { Level currentLevel = CurrentLevel(); IokeObject attaching = currentLevel.message; string setCellName; if(attaching == null) { // = b . IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, _message, _context, "Error", "Parser", "OpShuffle"), _context).Mimic(_message, _context); condition.SetCell("message", _message); condition.SetCell("context", _context); condition.SetCell("receiver", _context); condition.SetCell("text", runtime.NewText("Can't create trinary expression without lvalue")); runtime.ErrorCondition(condition); } // a = b . // string cellName = attaching.Name; IokeObject copyOfMessage = Message.Copy(attaching); Message.SetPrev(copyOfMessage, null); Message.SetNext(copyOfMessage, null); attaching.Arguments.Clear(); // a = b . -> a(a) = b . Message.AddArg(attaching, copyOfMessage); setCellName = messageName; int expectedArgs = argCountForOp; // a(a) = b . -> =(a) = b . Message.SetName(attaching, setCellName); currentLevel.type = Level.Type.Attach; // =(a) = b . // =(a) = or =("a") = . IokeObject mn = Message.GetNext(msg); if(expectedArgs > 1 && (mn == null || Message.IsTerminator(mn))) { // TODO: error, "compile error: %s must be followed by a value.", messageName } if(expectedArgs > 1) { // =(a) = b c . -> =(a, b c .) = b c . Message.AddArg(attaching, mn); // process the value (b c d) later (=(a, b c d) = b c d .) if(Message.GetNext(msg) != null && !Message.IsTerminator(Message.GetNext(msg))) { expressions.Insert(0, Message.GetNext(msg)); } IokeObject last = msg; while(Message.GetNext(last) != null && !Message.IsTerminator(Message.GetNext(last))) { last = Message.GetNext(last); } Message.SetNext(attaching, Message.GetNext(last)); Message.SetNext(msg, Message.GetNext(last)); if(last != msg) { Message.SetNext(last, null); } } else { Message.SetNext(attaching, Message.GetNext(msg)); } } else if(Message.IsTerminator(msg)) { PopDownTo(OP_LEVEL_MAX-1, expressions); AttachAndReplace(CurrentLevel(), msg); } else if(precedence != -1) { // An operator if(msgArgCount == 0) { PopDownTo(precedence, expressions); AttachToTopAndPush(msg, precedence); } else { AttachAndReplace(CurrentLevel(), msg); } } else { AttachAndReplace(CurrentLevel(), msg); } } public void NextMessage(IList<IokeObject> expressions) { while(stack.Count > 0) { var o = stack[0]; stack.RemoveAt(0); o.Finish(expressions); } Reset(); } public void Reset() { currentLevel = 1; for(int i=0;i<OP_LEVEL_MAX;i++) { pool[i] = new Level(Level.Type.Unused); } Level level = pool[0]; level.message = null; level.type = Level.Type.New; level.precedence = OP_LEVEL_MAX; stack.Clear(); stack.Add(pool[0]); } } }
// 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. #if FEATURE_CODEPAGES_FILE namespace System.Text { using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; // Our input file data structures look like: // // Header Structure Looks Like: // struct NLSPlusHeader // { // WORD[16] filename; // 32 bytes // WORD[4] version; // 8 bytes = 40 // I.e: 3, 2, 0, 0 // WORD count; // 2 bytes = 42 // Number of code page index's that'll follow // } // // Each code page section looks like: // struct NLSCodePageIndex // { // WORD[16] codePageName; // 32 bytes // WORD codePage; // +2 bytes = 34 // WORD byteCount; // +2 bytes = 36 // DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE. // } // // Each code page then has its own header // struct NLSCodePage // { // WORD[16] codePageName; // 32 bytes // WORD[4] version; // 8 bytes = 40 // I.e: 3.2.0.0 // WORD codePage; // 2 bytes = 42 // WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS) // WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character // WORD byteReplace; // 2 bytes = 48 // default replacement byte(s) // BYTE[] data; // data section // } [Serializable] internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable { // Static & Const stuff internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; [NonSerialized] protected int dataTableCodePage; // Variables to help us allocate/mark our memory section correctly [NonSerialized] protected bool bFlagDataTable = true; [NonSerialized] protected int iExtraBytes = 0; // Our private unicode to bytes best fit array and visa versa. [NonSerialized] protected char[] arrayUnicodeBestFit = null; [NonSerialized] protected char[] arrayBytesBestFit = null; // This is used to help ISCII, EUCJP and ISO2022 figure out they're MlangEncodings [NonSerialized] protected bool m_bUseMlangTypeForSerialization = false; [System.Security.SecuritySafeCritical] // static constructors should be safe to call static BaseCodePageEncoding() { } // // This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME. // // Explicit layout is used here since a syntax like char[16] can not be used in sequential layout. [StructLayout(LayoutKind.Explicit)] internal unsafe struct CodePageDataFileHeader { [FieldOffset(0)] internal char TableName; // WORD[16] [FieldOffset(0x20)] internal ushort Version; // WORD[4] [FieldOffset(0x28)] internal short CodePageCount; // WORD [FieldOffset(0x2A)] internal short unused1; // Add a unused WORD so that CodePages is aligned with DWORD boundary. // Otherwise, 64-bit version will fail. [FieldOffset(0x2C)] internal CodePageIndex CodePages; // Start of code page index } [StructLayout(LayoutKind.Explicit, Pack=2)] internal unsafe struct CodePageIndex { [FieldOffset(0)] internal char CodePageName; // WORD[16] [FieldOffset(0x20)] internal short CodePage; // WORD [FieldOffset(0x22)] internal short ByteCount; // WORD [FieldOffset(0x24)] internal int Offset; // DWORD } [StructLayout(LayoutKind.Explicit)] internal unsafe struct CodePageHeader { [FieldOffset(0)] internal char CodePageName; // WORD[16] [FieldOffset(0x20)] internal ushort VersionMajor; // WORD [FieldOffset(0x22)] internal ushort VersionMinor; // WORD [FieldOffset(0x24)] internal ushort VersionRevision;// WORD [FieldOffset(0x26)] internal ushort VersionBuild; // WORD [FieldOffset(0x28)] internal short CodePage; // WORD [FieldOffset(0x2a)] internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS) [FieldOffset(0x2c)] internal char UnicodeReplace; // WORD // default replacement unicode character [FieldOffset(0x2e)] internal ushort ByteReplace; // WORD // default replacement bytes [FieldOffset(0x30)] internal short FirstDataWord; // WORD[] } // Initialize our global stuff [SecurityCritical] unsafe static CodePageDataFileHeader* m_pCodePageFileHeader = (CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME); // Real variables [NonSerialized] [SecurityCritical] unsafe protected CodePageHeader* pCodePage = null; // Safe handle wrapper around section map view [System.Security.SecurityCritical] // auto-generated [NonSerialized] protected SafeViewOfFileHandle safeMemorySectionHandle = null; // Safe handle wrapper around mapped file handle [System.Security.SecurityCritical] // auto-generated [NonSerialized] protected SafeFileMappingHandle safeFileMappingHandle = null; [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage) { // Remember number of code page that we'll be using the table for. dataTableCodePage = dataCodePage; LoadCodePageTables(); } // Constructor called by serialization. [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // We cannot ever call this, we've proxied ourselved to CodePageEncoding throw new ArgumentNullException("this"); } // ISerializable implementation [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw"); // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding) info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize", this.IsSingleByte ? 1 : 2); // Use this class or MLangBaseCodePageEncoding as our deserializer. info.SetType(m_bUseMlangTypeForSerialization ? typeof(MLangCodePageEncoding) : typeof(CodePageEncoding)); } // We need to load tables for our code page [System.Security.SecurityCritical] // auto-generated private unsafe void LoadCodePageTables() { CodePageHeader* pCodePage = FindCodePage(dataTableCodePage); // Make sure we have one if (pCodePage == null) { // Didn't have one throw new NotSupportedException( Environment.GetResourceString("NotSupported_NoCodepageData", CodePage)); } // Remember our code page this.pCodePage = pCodePage; // We had it, so load it LoadManagedCodePage(); } // Look up the code page pointer [System.Security.SecurityCritical] // auto-generated private static unsafe CodePageHeader* FindCodePage(int codePage) { // We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't // binary or anything so its not monsterously fast. for (int i = 0; i < m_pCodePageFileHeader->CodePageCount; i++) { CodePageIndex* pCodePageIndex = (&(m_pCodePageFileHeader->CodePages)) + i; if (pCodePageIndex->CodePage == codePage) { // Found it! CodePageHeader* pCodePage = (CodePageHeader*)((byte*)m_pCodePageFileHeader + pCodePageIndex->Offset); return pCodePage; } } // Couldn't find it return null; } // Get our code page byte count [System.Security.SecurityCritical] // auto-generated internal static unsafe int GetCodePageByteSize(int codePage) { // Get our code page info CodePageHeader* pCodePage = FindCodePage(codePage); // If null return 0 if (pCodePage == null) return 0; Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2, "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table"); // Return what it says for byte count return pCodePage->ByteCount; } // We have a managed code page entry, so load our tables [System.Security.SecurityCritical] protected abstract unsafe void LoadManagedCodePage(); // Allocate memory to load our code page [System.Security.SecurityCritical] // auto-generated protected unsafe byte* GetSharedMemory(int iSize) { // Build our name String strName = GetMemorySectionName(); IntPtr mappedFileHandle; // This gets shared memory for our map. If its can't, it gives us clean memory. Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle); Contract.Assert(pMemorySection != null, "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened"); // If that failed, we have to die. if (pMemorySection == null) throw new OutOfMemoryException( Environment.GetResourceString("Arg_OutOfMemoryException")); // if we have null file handle. this means memory was allocated after // failing to open the mapped file. if (mappedFileHandle != IntPtr.Zero) { safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr) pMemorySection, true); safeFileMappingHandle = new SafeFileMappingHandle(mappedFileHandle, true); } return pMemorySection; } [System.Security.SecurityCritical] // auto-generated protected unsafe virtual String GetMemorySectionName() { int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage; String strName = String.Format(CultureInfo.InvariantCulture, "NLS_CodePage_{0}_{1}_{2}_{3}_{4}", iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor, this.pCodePage->VersionRevision, this.pCodePage->VersionBuild); return strName; } [System.Security.SecurityCritical] protected abstract unsafe void ReadBestFitTable(); [System.Security.SecuritySafeCritical] internal override char[] GetBestFitUnicodeToBytesData() { // Read in our best fit table if necessary if (arrayUnicodeBestFit == null) ReadBestFitTable(); Contract.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); // Normally we don't have any best fit data. return arrayUnicodeBestFit; } [System.Security.SecuritySafeCritical] internal override char[] GetBestFitBytesToUnicodeData() { // Read in our best fit table if necessary if (arrayBytesBestFit == null) ReadBestFitTable(); Contract.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); // Normally we don't have any best fit data. return arrayBytesBestFit; } // During the AppDomain shutdown the Encoding class may already finalized and the memory section // is invalid. so we detect that by validating the memory section handle then re-initialize the memory // section by calling LoadManagedCodePage() method and eventually the mapped file handle and // the memory section pointer will get finalized one more time. [System.Security.SecurityCritical] // auto-generated internal unsafe void CheckMemorySection() { if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } } } } #endif // FEATURE_CODEPAGES_FILE
using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.PostProcessing { public sealed class CurveEditor { #region Enums enum EditMode { None, Moving, TangentEdit } enum Tangent { In, Out } #endregion #region Structs public struct Settings { public Rect bounds; public RectOffset padding; public Color selectionColor; public float curvePickingDistance; public float keyTimeClampingDistance; public static Settings defaultSettings { get { return new Settings { bounds = new Rect(0f, 0f, 1f, 1f), padding = new RectOffset(10, 10, 10, 10), selectionColor = Color.yellow, curvePickingDistance = 6f, keyTimeClampingDistance = 1e-4f }; } } } public struct CurveState { public bool visible; public bool editable; public uint minPointCount; public float zeroKeyConstantValue; public Color color; public float width; public float handleWidth; public bool showNonEditableHandles; public bool onlyShowHandlesOnSelection; public bool loopInBounds; public static CurveState defaultState { get { return new CurveState { visible = true, editable = true, minPointCount = 2, zeroKeyConstantValue = 0f, color = Color.white, width = 2f, handleWidth = 2f, showNonEditableHandles = true, onlyShowHandlesOnSelection = false, loopInBounds = false }; } } } public struct Selection { public SerializedProperty curve; public int keyframeIndex; public Keyframe? keyframe; public Selection(SerializedProperty curve, int keyframeIndex, Keyframe? keyframe) { this.curve = curve; this.keyframeIndex = keyframeIndex; this.keyframe = keyframe; } } internal struct MenuAction { internal SerializedProperty curve; internal int index; internal Vector3 position; internal MenuAction(SerializedProperty curve) { this.curve = curve; this.index = -1; this.position = Vector3.zero; } internal MenuAction(SerializedProperty curve, int index) { this.curve = curve; this.index = index; this.position = Vector3.zero; } internal MenuAction(SerializedProperty curve, Vector3 position) { this.curve = curve; this.index = -1; this.position = position; } } #endregion #region Fields & properties public Settings settings { get; private set; } Dictionary<SerializedProperty, CurveState> m_Curves; Rect m_CurveArea; SerializedProperty m_SelectedCurve; int m_SelectedKeyframeIndex = -1; EditMode m_EditMode = EditMode.None; Tangent m_TangentEditMode; bool m_Dirty; #endregion #region Constructors & destructors public CurveEditor() : this(Settings.defaultSettings) {} public CurveEditor(Settings settings) { this.settings = settings; m_Curves = new Dictionary<SerializedProperty, CurveState>(); } #endregion #region Public API public void Add(params SerializedProperty[] curves) { foreach (var curve in curves) Add(curve, CurveState.defaultState); } public void Add(SerializedProperty curve) { Add(curve, CurveState.defaultState); } public void Add(SerializedProperty curve, CurveState state) { // Make sure the property is in fact an AnimationCurve var animCurve = curve.animationCurveValue; if (animCurve == null) throw new ArgumentException("curve"); if (m_Curves.ContainsKey(curve)) Debug.LogWarning("Curve has already been added to the editor"); m_Curves.Add(curve, state); } public void Remove(SerializedProperty curve) { m_Curves.Remove(curve); } public void RemoveAll() { m_Curves.Clear(); } public CurveState GetCurveState(SerializedProperty curve) { CurveState state; if (!m_Curves.TryGetValue(curve, out state)) throw new KeyNotFoundException("curve"); return state; } public void SetCurveState(SerializedProperty curve, CurveState state) { if (!m_Curves.ContainsKey(curve)) throw new KeyNotFoundException("curve"); m_Curves[curve] = state; } public Selection GetSelection() { Keyframe? key = null; if (m_SelectedKeyframeIndex > -1) { var curve = m_SelectedCurve.animationCurveValue; if (m_SelectedKeyframeIndex >= curve.length) m_SelectedKeyframeIndex = -1; else key = curve[m_SelectedKeyframeIndex]; } return new Selection(m_SelectedCurve, m_SelectedKeyframeIndex, key); } public void SetKeyframe(SerializedProperty curve, int keyframeIndex, Keyframe keyframe) { var animCurve = curve.animationCurveValue; SetKeyframe(animCurve, keyframeIndex, keyframe); SaveCurve(curve, animCurve); } public bool OnGUI(Rect rect) { if (Event.current.type == EventType.Repaint) m_Dirty = false; GUI.BeginClip(rect); { var area = new Rect(Vector2.zero, rect.size); m_CurveArea = settings.padding.Remove(area); foreach (var curve in m_Curves) OnCurveGUI(area, curve.Key, curve.Value); OnGeneralUI(area); } GUI.EndClip(); return m_Dirty; } #endregion #region UI & events void OnCurveGUI(Rect rect, SerializedProperty curve, CurveState state) { // Discard invisible curves if (!state.visible) return; var animCurve = curve.animationCurveValue; var keys = animCurve.keys; var length = keys.Length; // Curve drawing // Slightly dim non-editable curves var color = state.color; if (!state.editable) color.a *= 0.5f; Handles.color = color; var bounds = settings.bounds; if (length == 0) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, state.zeroKeyConstantValue)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, state.zeroKeyConstantValue)); Handles.DrawAAPolyLine(state.width, p1, p2); } else if (length == 1) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[0].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } else { var prevKey = keys[0]; for (int k = 1; k < length; k++) { var key = keys[k]; var pts = BezierSegment(prevKey, key); if (float.IsInfinity(prevKey.outTangent) || float.IsInfinity(key.inTangent)) { var s = HardSegment(prevKey, key); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); prevKey = key; } // Curve extents & loops if (keys[0].time > bounds.xMin) { if (state.loopInBounds) { var p1 = keys[length - 1]; p1.time -= settings.bounds.width; var p2 = keys[0]; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } else { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(keys[0]); Handles.DrawAAPolyLine(state.width, p1, p2); } } if (keys[length - 1].time < bounds.xMax) { if (state.loopInBounds) { var p1 = keys[length - 1]; var p2 = keys[0]; p2.time += settings.bounds.width; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } else { var p1 = CurveToCanvas(keys[length - 1]); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[length - 1].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } } } // Make sure selection is correct (undo can break it) bool isCurrentlySelectedCurve = curve == m_SelectedCurve; if (isCurrentlySelectedCurve && m_SelectedKeyframeIndex >= length) m_SelectedKeyframeIndex = -1; // Handles & keys for (int k = 0; k < length; k++) { bool isCurrentlySelectedKeyframe = k == m_SelectedKeyframeIndex; var e = Event.current; var pos = CurveToCanvas(keys[k]); var hitRect = new Rect(pos.x - 8f, pos.y - 8f, 16f, 16f); var offset = isCurrentlySelectedCurve ? new RectOffset(5, 5, 5, 5) : new RectOffset(6, 6, 6, 6); var outTangent = pos + CurveTangentToCanvas(keys[k].outTangent).normalized * 40f; var inTangent = pos - CurveTangentToCanvas(keys[k].inTangent).normalized * 40f; var inTangentHitRect = new Rect(inTangent.x - 7f, inTangent.y - 7f, 14f, 14f); var outTangentHitrect = new Rect(outTangent.x - 7f, outTangent.y - 7f, 14f, 14f); // Draw if (state.showNonEditableHandles) { if (e.type == EventType.repaint) { var selectedColor = (isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) ? settings.selectionColor : state.color; // Keyframe EditorGUI.DrawRect(offset.Remove(hitRect), selectedColor); // Tangents if (isCurrentlySelectedCurve && (!state.onlyShowHandlesOnSelection || (state.onlyShowHandlesOnSelection && isCurrentlySelectedKeyframe))) { Handles.color = selectedColor; if (k > 0 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, inTangent); EditorGUI.DrawRect(offset.Remove(inTangentHitRect), selectedColor); } if (k < length - 1 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, outTangent); EditorGUI.DrawRect(offset.Remove(outTangentHitrect), selectedColor); } } } } // Events if (state.editable) { // Keyframe move if (m_EditMode == EditMode.Moving && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { EditMoveKeyframe(animCurve, keys, k); } // Tangent editing if (m_EditMode == EditMode.TangentEdit && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { bool alreadyBroken = !(Mathf.Approximately(keys[k].inTangent, keys[k].outTangent) || (float.IsInfinity(keys[k].inTangent) && float.IsInfinity(keys[k].outTangent))); EditMoveTangent(animCurve, keys, k, m_TangentEditMode, e.shift || !(alreadyBroken || e.control)); } // Keyframe selection & context menu if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition)) { if (hitRect.Contains(e.mousePosition)) { if (e.button == 0) { SelectKeyframe(curve, k); m_EditMode = EditMode.Moving; e.Use(); } else if (e.button == 1) { // Keyframe context menu var menu = new GenericMenu(); menu.AddItem(new GUIContent("Delete Key"), false, (x) => { var action = (MenuAction)x; var curveValue = action.curve.animationCurveValue; action.curve.serializedObject.Update(); RemoveKeyframe(curveValue, action.index); m_SelectedKeyframeIndex = -1; SaveCurve(action.curve, curveValue); action.curve.serializedObject.ApplyModifiedProperties(); }, new MenuAction(curve, k)); menu.ShowAsContext(); e.Use(); } } } // Tangent selection & edit mode if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition)) { if (inTangentHitRect.Contains(e.mousePosition) && (k > 0 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.In; e.Use(); } else if (outTangentHitrect.Contains(e.mousePosition) && (k < length - 1 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.Out; e.Use(); } } // Mouse up - clean up states if (e.rawType == EventType.MouseUp && m_EditMode != EditMode.None) { m_EditMode = EditMode.None; } // Set cursors { EditorGUIUtility.AddCursorRect(hitRect, MouseCursor.MoveArrow); if (k > 0 || state.loopInBounds) EditorGUIUtility.AddCursorRect(inTangentHitRect, MouseCursor.RotateArrow); if (k < length - 1 || state.loopInBounds) EditorGUIUtility.AddCursorRect(outTangentHitrect, MouseCursor.RotateArrow); } } } Handles.color = Color.white; SaveCurve(curve, animCurve); } void OnGeneralUI(Rect rect) { var e = Event.current; // Selection if (e.type == EventType.mouseDown) { GUI.FocusControl(null); m_SelectedCurve = null; m_SelectedKeyframeIndex = -1; bool used = false; var hit = CanvasToCurve(e.mousePosition); float curvePickValue = CurveToCanvas(hit).y; // Try and select a curve foreach (var curve in m_Curves) { if (!curve.Value.editable || !curve.Value.visible) continue; var prop = curve.Key; var state = curve.Value; var animCurve = prop.animationCurveValue; float hitY = animCurve.length == 0 ? state.zeroKeyConstantValue : animCurve.Evaluate(hit.x); var curvePos = CurveToCanvas(new Vector3(hit.x, hitY)); if (Mathf.Abs(curvePos.y - curvePickValue) < settings.curvePickingDistance) { m_SelectedCurve = prop; if (e.clickCount == 2 && e.button == 0) { // Create a keyframe on double-click on this curve EditCreateKeyframe(animCurve, hit, true, state.zeroKeyConstantValue); SaveCurve(prop, animCurve); } else if (e.button == 1) { // Curve context menu var menu = new GenericMenu(); menu.AddItem(new GUIContent("Add Key"), false, (x) => { var action = (MenuAction)x; var curveValue = action.curve.animationCurveValue; action.curve.serializedObject.Update(); EditCreateKeyframe(curveValue, hit, true, 0f); SaveCurve(action.curve, curveValue); action.curve.serializedObject.ApplyModifiedProperties(); }, new MenuAction(prop, hit)); menu.ShowAsContext(); e.Use(); used = true; } } } if (e.clickCount == 2 && e.button == 0 && m_SelectedCurve == null) { // Create a keyframe on every curve on double-click foreach (var curve in m_Curves) { if (!curve.Value.editable || !curve.Value.visible) continue; var prop = curve.Key; var state = curve.Value; var animCurve = prop.animationCurveValue; EditCreateKeyframe(animCurve, hit, e.alt, state.zeroKeyConstantValue); SaveCurve(prop, animCurve); } } else if (!used && e.button == 1) { // Global context menu var menu = new GenericMenu(); menu.AddItem(new GUIContent("Add Key At Position"), false, () => ContextMenuAddKey(hit, false)); menu.AddItem(new GUIContent("Add Key On Curves"), false, () => ContextMenuAddKey(hit, true)); menu.ShowAsContext(); } e.Use(); } // Delete selected key(s) if (e.type == EventType.keyDown && (e.keyCode == KeyCode.Delete || e.keyCode == KeyCode.Backspace)) { if (m_SelectedKeyframeIndex != -1 && m_SelectedCurve != null) { var animCurve = m_SelectedCurve.animationCurveValue; var length = animCurve.length; if (m_Curves[m_SelectedCurve].minPointCount < length && length >= 0) { EditDeleteKeyframe(animCurve, m_SelectedKeyframeIndex); m_SelectedKeyframeIndex = -1; SaveCurve(m_SelectedCurve, animCurve); } e.Use(); } } } void SaveCurve(SerializedProperty prop, AnimationCurve curve) { prop.animationCurveValue = curve; } void Invalidate() { m_Dirty = true; } #endregion #region Keyframe manipulations void SelectKeyframe(SerializedProperty curve, int keyframeIndex) { m_SelectedKeyframeIndex = keyframeIndex; m_SelectedCurve = curve; Invalidate(); } void ContextMenuAddKey(Vector3 hit, bool createOnCurve) { SerializedObject serializedObject = null; foreach (var curve in m_Curves) { if (!curve.Value.editable || !curve.Value.visible) continue; var prop = curve.Key; var state = curve.Value; if (serializedObject == null) { serializedObject = prop.serializedObject; serializedObject.Update(); } var animCurve = prop.animationCurveValue; EditCreateKeyframe(animCurve, hit, createOnCurve, state.zeroKeyConstantValue); SaveCurve(prop, animCurve); } if (serializedObject != null) serializedObject.ApplyModifiedProperties(); Invalidate(); } void EditCreateKeyframe(AnimationCurve curve, Vector3 position, bool createOnCurve, float zeroKeyConstantValue) { float tangent = EvaluateTangent(curve, position.x); if (createOnCurve) { position.y = curve.length == 0 ? zeroKeyConstantValue : curve.Evaluate(position.x); } AddKeyframe(curve, new Keyframe(position.x, position.y, tangent, tangent)); } void EditDeleteKeyframe(AnimationCurve curve, int keyframeIndex) { RemoveKeyframe(curve, keyframeIndex); } void AddKeyframe(AnimationCurve curve, Keyframe newValue) { curve.AddKey(newValue); Invalidate(); } void RemoveKeyframe(AnimationCurve curve, int keyframeIndex) { curve.RemoveKey(keyframeIndex); Invalidate(); } void SetKeyframe(AnimationCurve curve, int keyframeIndex, Keyframe newValue) { var keys = curve.keys; if (keyframeIndex > 0) newValue.time = Mathf.Max(keys[keyframeIndex - 1].time + settings.keyTimeClampingDistance, newValue.time); if (keyframeIndex < keys.Length - 1) newValue.time = Mathf.Min(keys[keyframeIndex + 1].time - settings.keyTimeClampingDistance, newValue.time); curve.MoveKey(keyframeIndex, newValue); Invalidate(); } void EditMoveKeyframe(AnimationCurve curve, Keyframe[] keys, int keyframeIndex) { var key = CanvasToCurve(Event.current.mousePosition); float inTgt = keys[keyframeIndex].inTangent; float outTgt = keys[keyframeIndex].outTangent; SetKeyframe(curve, keyframeIndex, new Keyframe(key.x, key.y, inTgt, outTgt)); } void EditMoveTangent(AnimationCurve curve, Keyframe[] keys, int keyframeIndex, Tangent targetTangent, bool linkTangents) { var pos = CanvasToCurve(Event.current.mousePosition); float time = keys[keyframeIndex].time; float value = keys[keyframeIndex].value; pos -= new Vector3(time, value); if (targetTangent == Tangent.In && pos.x > 0f) pos.x = 0f; if (targetTangent == Tangent.Out && pos.x < 0f) pos.x = 0f; float tangent; if (Mathf.Approximately(pos.x, 0f)) tangent = pos.y < 0f ? float.PositiveInfinity : float.NegativeInfinity; else tangent = pos.y / pos.x; float inTangent = keys[keyframeIndex].inTangent; float outTangent = keys[keyframeIndex].outTangent; if (targetTangent == Tangent.In || linkTangents) inTangent = tangent; if (targetTangent == Tangent.Out || linkTangents) outTangent = tangent; SetKeyframe(curve, keyframeIndex, new Keyframe(time, value, inTangent, outTangent)); } #endregion #region Maths utilities Vector3 CurveToCanvas(Keyframe keyframe) { return CurveToCanvas(new Vector3(keyframe.time, keyframe.value)); } Vector3 CurveToCanvas(Vector3 position) { var bounds = settings.bounds; var output = new Vector3((position.x - bounds.x) / (bounds.xMax - bounds.x), (position.y - bounds.y) / (bounds.yMax - bounds.y)); output.x = output.x * (m_CurveArea.xMax - m_CurveArea.xMin) + m_CurveArea.xMin; output.y = (1f - output.y) * (m_CurveArea.yMax - m_CurveArea.yMin) + m_CurveArea.yMin; return output; } Vector3 CanvasToCurve(Vector3 position) { var bounds = settings.bounds; var output = position; output.x = (output.x - m_CurveArea.xMin) / (m_CurveArea.xMax - m_CurveArea.xMin); output.y = (output.y - m_CurveArea.yMin) / (m_CurveArea.yMax - m_CurveArea.yMin); output.x = Mathf.Lerp(bounds.x, bounds.xMax, output.x); output.y = Mathf.Lerp(bounds.yMax, bounds.y, output.y); return output; } Vector3 CurveTangentToCanvas(float tangent) { if (!float.IsInfinity(tangent)) { var bounds = settings.bounds; float ratio = (m_CurveArea.width / m_CurveArea.height) / ((bounds.xMax - bounds.x) / (bounds.yMax - bounds.y)); return new Vector3(1f, -tangent / ratio).normalized; } return float.IsPositiveInfinity(tangent) ? Vector3.up : Vector3.down; } Vector3[] BezierSegment(Keyframe start, Keyframe end) { var segment = new Vector3[4]; segment[0] = CurveToCanvas(new Vector3(start.time, start.value)); segment[3] = CurveToCanvas(new Vector3(end.time, end.value)); float middle = start.time + ((end.time - start.time) * 0.333333f); float middle2 = start.time + ((end.time - start.time) * 0.666666f); segment[1] = CurveToCanvas(new Vector3(middle, ProjectTangent(start.time, start.value, start.outTangent, middle))); segment[2] = CurveToCanvas(new Vector3(middle2, ProjectTangent(end.time, end.value, end.inTangent, middle2))); return segment; } Vector3[] HardSegment(Keyframe start, Keyframe end) { var segment = new Vector3[3]; segment[0] = CurveToCanvas(start); segment[1] = CurveToCanvas(new Vector3(end.time, start.value)); segment[2] = CurveToCanvas(end); return segment; } float ProjectTangent(float inPosition, float inValue, float inTangent, float projPosition) { return inValue + ((projPosition - inPosition) * inTangent); } float EvaluateTangent(AnimationCurve curve, float time) { int prev = -1, next = 0; for (int i = 0; i < curve.keys.Length; i++) { if (time > curve.keys[i].time) { prev = i; next = i + 1; } else break; } if (next == 0) return 0f; if (prev == curve.keys.Length - 1) return 0f; const float kD = 1e-3f; float tp = Mathf.Max(time - kD, curve.keys[prev].time); float tn = Mathf.Min(time + kD, curve.keys[next].time); float vp = curve.Evaluate(tp); float vn = curve.Evaluate(tn); if (Mathf.Approximately(tn, tp)) return (vn - vp > 0f) ? float.PositiveInfinity : float.NegativeInfinity; return (vn - vp) / (tn - tp); } #endregion } }
// Copyright Bastian Eicher // Licensed under the MIT License using System.Runtime.Versioning; using System.Security; using Microsoft.Win32; namespace NanoByte.Common.Native; /// <summary> /// Provides utility and extension methods for <see cref="Registry"/> access. /// </summary> [SupportedOSPlatform("windows")] public static class RegistryUtils { #region DWORD /// <summary> /// Reads a DWORD value from the registry. /// </summary> /// <param name="keyName">The full path of the key to read from.</param> /// <param name="valueName">The name of the value to read.</param> /// <param name="defaultValue">The default value to return if the key or value does not exist.</param> /// <exception cref="IOException">Registry access failed.</exception> [Pure] public static int GetDword([Localizable(false)] string keyName, [Localizable(false)] string? valueName, int defaultValue = 0) { #region Sanity checks if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException(nameof(keyName)); #endregion try { return Registry.GetValue(keyName, valueName, defaultValue) as int? ?? defaultValue; } #region Error handling catch (SecurityException ex) { Log.Warn(ex); return defaultValue; } #endregion } /// <summary> /// Sets a DWORD value in the registry. /// </summary> /// <param name="keyName">The full path of the key to write to.</param> /// <param name="valueName">The name of the value to write.</param> /// <param name="value">The value to write.</param> /// <exception cref="IOException">Registry access failed.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the key is not permitted.</exception> public static void SetDword([Localizable(false)] string keyName, [Localizable(false)] string? valueName, int value) { #region Sanity checks if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException(nameof(keyName)); #endregion try { Registry.SetValue(keyName, valueName, value, RegistryValueKind.DWord); } #region Error handling catch (SecurityException ex) { // Wrap exception since only certain exception types are allowed throw new UnauthorizedAccessException(ex.Message, ex); } #endregion } #endregion #region String /// <summary> /// Reads a string value from the registry. /// </summary> /// <param name="keyName">The full path of the key to read from.</param> /// <param name="valueName">The name of the value to read.</param> /// <param name="defaultValue">The default value to return if the key or value does not exist.</param> /// <exception cref="IOException">Registry access failed.</exception> [Pure] [return: NotNullIfNotNull("defaultValue")] public static string? GetString([Localizable(false)] string keyName, [Localizable(false)] string? valueName, [Localizable(false)] string? defaultValue = null) { #region Sanity checks if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException(nameof(keyName)); #endregion try { return Registry.GetValue(keyName, valueName, defaultValue) as string ?? defaultValue; } #region Error handling catch (SecurityException ex) { Log.Warn(ex); return defaultValue; } #endregion } /// <summary> /// Sets a string value in the registry. /// </summary> /// <param name="keyName">The full path of the key to write to.</param> /// <param name="valueName">The name of the value to write.</param> /// <param name="value">The value to write.</param> /// <exception cref="IOException">Registry access failed.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the key is not permitted.</exception> public static void SetString([Localizable(false)] string keyName, [Localizable(false)] string? valueName, [Localizable(false)] string value) { #region Sanity checks if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException(nameof(keyName)); #endregion try { Registry.SetValue(keyName, valueName, value, RegistryValueKind.String); } #region Error handling catch (SecurityException ex) { // Wrap exception since only certain exception types are allowed throw new UnauthorizedAccessException(ex.Message, ex); } #endregion } #endregion #region Software private const string HklmSoftwareKey = @"HKEY_LOCAL_MACHINE\SOFTWARE\"; private const string HklmWowSoftwareKey = @"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\"; private const string HkcuSoftwareKey = @"HKEY_CURRENT_USER\SOFTWARE\"; /// <summary> /// Reads a string value from one of the SOFTWARE keys in the registry. /// </summary> /// <remarks>Checks HKLM/SOFTWARE, HKLM/SOFTWARE/Wow6432Node and HKCU/SOFTWARE in that order.</remarks> /// <param name="subkeyName">The path of the key relative to the SOFTWARE key.</param> /// <param name="valueName">The name of the value to read.</param> /// <param name="defaultValue">The default value to return if the key or value does not exist.</param> /// <exception cref="IOException">Registry access failed.</exception> [Pure] [return: NotNullIfNotNull("defaultValue")] public static string? GetSoftwareString([Localizable(false)] string subkeyName, [Localizable(false)] string? valueName, [Localizable(false)] string? defaultValue = null) { #region Sanity checks if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion return GetString(HklmSoftwareKey + subkeyName, valueName, GetString(HklmWowSoftwareKey + subkeyName, valueName, GetString(HkcuSoftwareKey + subkeyName, valueName, defaultValue))); } /// <summary> /// Reads a string value from one of the SOFTWARE keys in the registry. /// </summary> /// <param name="subkeyName">The path of the key relative to the SOFTWARE key.</param> /// <param name="valueName">The name of the value to read.</param> /// <param name="machineWide"><c>true</c> to read from HKLM/SOFTWARE (and HKLM/SOFTWARE/Wow6432Node if on 64-bit Windows); <c>false</c> to read from HCKU/SOFTWARE.</param> /// <exception cref="IOException">Registry access failed.</exception> [Pure] public static string? GetSoftwareString([Localizable(false)] string subkeyName, [Localizable(false)] string? valueName, bool machineWide) { #region Sanity checks if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion return machineWide ? GetString(HklmSoftwareKey + subkeyName, valueName, GetString(HklmWowSoftwareKey + subkeyName, valueName)) : GetString(HkcuSoftwareKey + subkeyName, valueName); } /// <summary> /// Sets a string value in one or more of the SOFTWARE keys in the registry. /// </summary> /// <param name="subkeyName">The path of the key relative to the SOFTWARE key.</param> /// <param name="valueName">The name of the value to write.</param> /// <param name="value">The value to write.</param> /// <param name="machineWide"><c>true</c> to write to HKLM/SOFTWARE (and HKLM/SOFTWARE/Wow6432Node if on 64-bit Windows); <c>false</c> to write to HCKU/SOFTWARE.</param> /// <exception cref="IOException">Registry access failed.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the key is not permitted.</exception> public static void SetSoftwareString([Localizable(false)] string subkeyName, [Localizable(false)] string? valueName, [Localizable(false)] string value, bool machineWide = false) { #region Sanity checks if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion if (machineWide) { SetString(HklmSoftwareKey + subkeyName, valueName, value); #if !NET20 && !NET40 if (Environment.Is64BitProcess) SetString(HklmWowSoftwareKey + subkeyName, valueName, value); #endif } else SetString(HkcuSoftwareKey + subkeyName, valueName, value); } /// <summary> /// Deletes a value from one of the SOFTWARE keys in the registry. /// </summary> /// <remarks>Does not throw an exception for missing keys or values.</remarks> /// <param name="subkeyName">The path of the key relative to the SOFTWARE key.</param> /// <param name="valueName">The name of the value to delete.</param> /// <param name="machineWide"><c>true</c> to delete from HKLM/SOFTWARE (and HKLM/SOFTWARE/Wow6432Node if on 64-bit Windows); <c>false</c> to delete from HCKU/SOFTWARE.</param> /// <exception cref="IOException">Registry access failed.</exception> public static void DeleteSoftwareValue([Localizable(false)] string subkeyName, [Localizable(false)] string valueName, bool machineWide) { #region Sanity checks if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); if (string.IsNullOrEmpty(valueName)) throw new ArgumentNullException(nameof(valueName)); #endregion if (machineWide) { DeleteValue(Registry.LocalMachine, @"SOFTWARE\" + subkeyName, valueName); #if !NET20 && !NET40 if (Environment.Is64BitProcess) DeleteValue(Registry.LocalMachine, @"SOFTWARE\Wow6432Node\" + subkeyName, valueName); #endif } else DeleteValue(Registry.CurrentUser, @"SOFTWARE\" + subkeyName, valueName); } private static void DeleteValue(RegistryKey root, string subkeyName, string valueName) { var key = root.OpenSubKey(subkeyName, writable: true); key?.DeleteValue(valueName, throwOnMissingValue: false); } #endregion #region Enumeration /// <summary> /// Retrieves the names of all values within a specific subkey of a registry root. /// </summary> /// <param name="key">The root key to look within.</param> /// <param name="subkeyName">The path of the subkey below <paramref name="key"/>.</param> /// <returns>A list of value names; an empty array if the key does not exist.</returns> /// <exception cref="IOException">Registry access failed.</exception> [Pure] public static string[] GetValueNames([Localizable(false)] this RegistryKey key, [Localizable(false)] string subkeyName) { #region Sanity checks if (key == null) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion try { using var subkey = key.OpenSubKey(subkeyName); return subkey?.GetValueNames() ?? new string[0]; } #region Error handling catch (SecurityException ex) { Log.Warn(ex); return new string[0]; } #endregion } /// <summary> /// Retrieves the names of all subkeys within a specific subkey of a registry root. /// </summary> /// <param name="key">The root key to look within.</param> /// <param name="subkeyName">The path of the subkey below <paramref name="key"/>.</param> /// <returns>A list of key names; an empty array if the key does not exist.</returns> /// <exception cref="IOException">Registry access failed.</exception> [Pure] public static string[] GetSubKeyNames([Localizable(false)] RegistryKey key, [Localizable(false)] string subkeyName) { #region Sanity checks if (key == null) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion try { using var subkey = key.OpenSubKey(subkeyName); return subkey?.GetSubKeyNames() ?? new string[0]; } #region Error handling catch (SecurityException ex) { Log.Warn(ex); return new string[0]; } #endregion } #endregion #region Keys /// <summary> /// Like <see cref="RegistryKey.OpenSubKey(string,bool)"/> but with no <c>null</c> return values. /// </summary> /// <param name="key">The key to open a subkey in.</param> /// <param name="subkeyName">The name of the subkey to open.</param> /// <param name="writable"><c>true</c> for write-access to the key.</param> /// <returns>The newly created subkey.</returns> /// <exception cref="IOException">Failed to open the key.</exception> /// <exception cref="UnauthorizedAccessException">Access to the key is not permitted.</exception> public static RegistryKey OpenSubKeyChecked([Localizable(false)] this RegistryKey key, [Localizable(false)] string subkeyName, bool writable = false) { #region Sanity checks if (key == null) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion try { var result = key.OpenSubKey(subkeyName, writable); if (result == null) throw new IOException(string.Format(Resources.FailedToOpenRegistrySubkey, subkeyName, key)); return result; } #region Error handling catch (SecurityException ex) { // Wrap exception since only certain exception types are allowed throw new UnauthorizedAccessException(ex.Message, ex); } #endregion } /// <summary> /// Like <see cref="RegistryKey.CreateSubKey(string)"/> but with no <c>null</c> return values. /// </summary> /// <param name="key">The key to create a subkey in.</param> /// <param name="subkeyName">The name of the subkey to create.</param> /// <returns>The newly created subkey.</returns> /// <exception cref="IOException">Failed to create the key.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the key is not permitted.</exception> public static RegistryKey CreateSubKeyChecked([Localizable(false)] this RegistryKey key, [Localizable(false)] string subkeyName) { #region Sanity checks if (key == null) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion try { var result = key.CreateSubKey(subkeyName); if (result == null) throw new IOException(string.Format(Resources.FailedToOpenRegistrySubkey, subkeyName, key)); return result; } #region Error handling catch (SecurityException ex) { // Wrap exception since only certain exception types are allowed throw new UnauthorizedAccessException(ex.Message, ex); } #endregion } /// <summary> /// Opens a HKEY_LOCAL_MACHINE key in the registry for reading, first trying to find the 64-bit version of it, then falling back to the 32-bit version. /// </summary> /// <param name="subkeyName">The path to the key below HKEY_LOCAL_MACHINE.</param> /// <param name="x64">Indicates whether a 64-bit key was opened.</param> /// <returns>The opened registry key or <c>null</c> if it could not found.</returns> /// <exception cref="IOException">Failed to open the key.</exception> /// <exception cref="UnauthorizedAccessException">Access to the key is not permitted.</exception> public static RegistryKey OpenHklmKey([Localizable(false)] string subkeyName, out bool x64) { #region Sanity checks if (string.IsNullOrEmpty(subkeyName)) throw new ArgumentNullException(nameof(subkeyName)); #endregion #if !NET20 && !NET40 if (Environment.Is64BitProcess) { var result = Registry.LocalMachine.OpenSubKey(subkeyName); if (result != null) { x64 = true; return result; } else { x64 = false; return OpenSubKeyChecked(Registry.LocalMachine, @"WOW6432Node\" + subkeyName); } } else #endif { x64 = false; return OpenSubKeyChecked(Registry.LocalMachine, subkeyName); } } #endregion }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing.Design; using System.Windows.Forms; namespace GodLesZ.Library.Controls { /// <summary> /// A DataListView is a ListView that can be bound to a datasource (which would normally be a DataTable or DataView). /// </summary> /// <remarks> /// <para>This listview keeps itself in sync with its source datatable by listening for change events.</para> /// <para>If the listview has no columns when given a data source, it will automatically create columns to show all of the datatables columns. /// This will be only the simplest view of the world, and would look more interesting with a few delegates installed.</para> /// <para>This listview will also automatically generate missing aspect getters to fetch the values from the data view.</para> /// <para>Changing data sources is possible, but error prone. Before changing data sources, the programmer is responsible for modifying/resetting /// the column collection to be valid for the new data source.</para> /// <para>Internally, a CurrencyManager controls keeping the data source in-sync with other users of the data source (as per normal .NET /// behavior). This means that the model objects in the DataListView are DataRowView objects. If you write your own AspectGetters/Setters, /// they will be given DataRowView objects.</para> /// </remarks> public class DataListView : ObjectListView { /// <summary> /// Make a DataListView /// </summary> public DataListView() : base() { } #region Public Properties /// <summary> /// Get or set the DataSource that will be displayed in this list view. /// </summary> /// <remarks>The DataSource should implement either <see cref="IList"/>, <see cref="IBindingList"/>, /// or <see cref="IListSource"/>. Some common examples are the following types of objects: /// <list type="unordered"> /// <item><description><see cref="DataView"/></description></item> /// <item><description><see cref="DataTable"/></description></item> /// <item><description><see cref="DataSet"/></description></item> /// <item><description><see cref="DataViewManager"/></description></item> /// <item><description><see cref="BindingSource"/></description></item> /// </list> /// <para>When binding to a list container (i.e. one that implements the /// <see cref="IListSource"/> interface, such as <see cref="DataSet"/>) /// you must also set the <see cref="DataMember"/> property in order /// to identify which particular list you would like to display. You /// may also set the <see cref="DataMember"/> property even when /// DataSource refers to a list, since <see cref="DataMember"/> can /// also be used to navigate relations between lists.</para> /// </remarks> [Category("Data"), TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")] public virtual Object DataSource { get { return dataSource; } set { //THINK: Should we only assign it if it is changed? //if (dataSource != value) { dataSource = value; this.RebindDataSource(true); //} } } private Object dataSource; /// <summary> /// Gets or sets the name of the list or table in the data source for which the DataListView is displaying data. /// </summary> /// <remarks>If the data source is not a DataSet or DataViewManager, this property has no effect</remarks> [Category("Data"), Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", typeof(UITypeEditor)), DefaultValue("")] public virtual string DataMember { get { return dataMember; } set { if (dataMember != value) { dataMember = value; RebindDataSource(); } } } private string dataMember = ""; #endregion #region Initialization private CurrencyManager currencyManager = null; /// <summary> /// Our data source has changed. Figure out how to handle the new source /// </summary> protected virtual void RebindDataSource() { RebindDataSource(false); } /// <summary> /// Our data source has changed. Figure out how to handle the new source /// </summary> protected virtual void RebindDataSource(bool forceDataInitialization) { if (this.BindingContext == null) return; // Obtain the CurrencyManager for the current data source. CurrencyManager tempCurrencyManager = null; if (this.DataSource != null) { tempCurrencyManager = (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember]; } // Has our currency manager changed? if (this.currencyManager != tempCurrencyManager) { // Stop listening for events on our old currency manager if (this.currencyManager != null) { this.currencyManager.MetaDataChanged -= new EventHandler(currencyManager_MetaDataChanged); this.currencyManager.PositionChanged -= new EventHandler(currencyManager_PositionChanged); this.currencyManager.ListChanged -= new ListChangedEventHandler(currencyManager_ListChanged); } this.currencyManager = tempCurrencyManager; // Start listening for events on our new currency manager if (this.currencyManager != null) { this.currencyManager.MetaDataChanged += new EventHandler(currencyManager_MetaDataChanged); this.currencyManager.PositionChanged += new EventHandler(currencyManager_PositionChanged); this.currencyManager.ListChanged += new ListChangedEventHandler(currencyManager_ListChanged); } // Our currency manager has changed so we have to initialize a new data source forceDataInitialization = true; } if (forceDataInitialization) InitializeDataSource(); } /// <summary> /// The data source for this control has changed. Reconfigure the control for the new source /// </summary> protected virtual void InitializeDataSource() { if (this.Frozen || this.currencyManager == null) return; this.CreateColumnsFromSource(); this.CreateMissingAspectGettersAndPutters(); this.SetObjects(this.currencyManager.List); // If we have some data, resize the new columns based on the data available. if (this.Items.Count > 0) { foreach (ColumnHeader column in this.Columns) { if (column.Width == 0) this.AutoResizeColumn(column.Index, ColumnHeaderAutoResizeStyle.ColumnContent); } } } /// <summary> /// Create columns for the listview based on what properties are available in the data source /// </summary> /// <remarks> /// <para>This method will not replace existing columns.</para> /// </remarks> protected virtual void CreateColumnsFromSource() { if (this.currencyManager == null || this.Columns.Count != 0) return; PropertyDescriptorCollection properties = this.currencyManager.GetItemProperties(); if (properties.Count == 0) return; bool hasBooleanColumns = false; for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; // Relationships to other tables turn up as IBindibleLists. Don't make columns to show them. // CHECK: Is this always true? What other things could be here? Constraints? Triggers? if (property.PropertyType == typeof(IBindingList)) continue; // Create a column OLVColumn column = new OLVColumn(property.DisplayName, property.Name); if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(CheckState)) { hasBooleanColumns = true; column.TextAlign = HorizontalAlignment.Center; column.Width = 32; column.AspectName = property.Name; column.CheckBoxes = true; if (property.PropertyType == typeof(CheckState)) column.TriStateCheckBoxes = true; } else { column.Width = 0; // zero-width since we will resize it once we have some data // If our column is a BLOB, it could be an image, so assign a renderer to draw it. // CONSIDER: Is this a common enough case to warrant this code? if (property.PropertyType == typeof(System.Byte[])) column.Renderer = new ImageRenderer(); } column.IsEditable = !property.IsReadOnly; // Add it to our list this.Columns.Add(column); } if (hasBooleanColumns) this.SetupSubItemCheckBoxes(); } /// <summary> /// Generate aspect getters and putters for any columns that are missing them (and for which we have /// enough information to actually generate a getter) /// </summary> protected virtual void CreateMissingAspectGettersAndPutters() { for (int i = 0; i < this.Columns.Count; i++) { OLVColumn column = this.GetColumn(i); if (column.AspectGetter == null && !String.IsNullOrEmpty(column.AspectName)) { column.AspectGetter = delegate(object row) { // In most cases, rows will be DataRowView objects DataRowView drv = row as DataRowView; if (drv != null) return drv[column.AspectName]; else return column.GetAspectByName(row); }; } if (column.IsEditable && column.AspectPutter == null && !String.IsNullOrEmpty(column.AspectName)) { column.AspectPutter = delegate(object row, object newValue) { // In most cases, rows will be DataRowView objects DataRowView drv = row as DataRowView; if (drv != null) drv[column.AspectName] = newValue; else column.PutAspectByName(row, newValue); }; } } } #endregion #region Object manipulations /// <summary> /// Add the given collection of model objects to this control. /// </summary> /// <param name="modelObjects">A collection of model objects</param> /// <remarks>This is a no-op for data lists, since the data /// is controlled by the DataSource. Manipulate the data source /// rather than this view of the data source.</remarks> public override void AddObjects(ICollection modelObjects) { } /// <summary> /// Remove the given collection of model objects from this control. /// </summary> /// <remarks>This is a no-op for data lists, since the data /// is controlled by the DataSource. Manipulate the data source /// rather than this view of the data source.</remarks> public override void RemoveObjects(ICollection modelObjects) { } #endregion #region Event Handlers /// <summary> /// What should we do when the list is unfrozen /// </summary> protected override void DoUnfreeze() { this.RebindDataSource(true); } /// <summary> /// Handles binding context changes /// </summary> /// <param name="e">The EventArgs that will be passed to any handlers /// of the BindingContextChanged event.</param> protected override void OnBindingContextChanged(EventArgs e) { base.OnBindingContextChanged(e); // If our binding context changes, we must rebind, since we will // have a new currency managers, even if we are still bound to the // same data source. this.RebindDataSource(false); } /// <summary> /// Handles parent binding context changes /// </summary> /// <param name="e">Unused EventArgs.</param> protected override void OnParentBindingContextChanged(EventArgs e) { base.OnParentBindingContextChanged(e); // BindingContext is an ambient property - by default it simply picks // up the parent control's context (unless something has explicitly // given us our own). So we must respond to changes in our parent's // binding context in the same way we would changes to our own // binding context. this.RebindDataSource(false); } /// <summary> /// CurrencyManager ListChanged event handler. /// Deals with fine-grained changes to list items. /// </summary> /// <remarks> /// It's actually difficult to deal with these changes in a fine-grained manner. /// If our listview is grouped, then any change may make a new group appear or /// an old group disappear. It is rarely enough to simply update the affected row. /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void currencyManager_ListChanged(object sender, ListChangedEventArgs e) { switch (e.ListChangedType) { // Well, usually fine-grained... The whole list has changed utterly, so reload it. case ListChangedType.Reset: this.InitializeDataSource(); break; // A single item has changed, so just refresh that. // TODO: Even in this simple case, we should probably rebuild the list. case ListChangedType.ItemChanged: Object changedRow = this.currencyManager.List[e.NewIndex]; this.RefreshObject(changedRow); break; // A new item has appeared, so add that. // We get this event twice if certain grid controls are used to add a new row to a // datatable: once when the editing of a new row begins, and once again when that // editing commits. (If the user cancels the creation of the new row, we never see // the second creation.) We detect this by seeing if this is a view on a row in a // DataTable, and if it is, testing to see if it's a new row under creation. case ListChangedType.ItemAdded: Object newRow = this.currencyManager.List[e.NewIndex]; DataRowView drv = newRow as DataRowView; if (drv == null || !drv.IsNew) { // Either we're not dealing with a view on a data table, or this is the commit // notification. Either way, this is the final notification, so we want to // handle the new row now! this.InitializeDataSource(); } break; // An item has gone away. case ListChangedType.ItemDeleted: this.InitializeDataSource(); break; // An item has changed its index. case ListChangedType.ItemMoved: this.InitializeDataSource(); break; // Something has changed in the metadata. // CHECK: When are these events actually fired? case ListChangedType.PropertyDescriptorAdded: case ListChangedType.PropertyDescriptorChanged: case ListChangedType.PropertyDescriptorDeleted: this.InitializeDataSource(); break; } } /// <summary> /// The CurrencyManager calls this if the data source looks /// different. We just reload everything. /// CHECK: Do we need this if we are handle ListChanged metadata events? /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void currencyManager_MetaDataChanged(object sender, EventArgs e) { this.InitializeDataSource(); } /// <summary> /// Called by the CurrencyManager when the currently selected item /// changes. We update the ListView selection so that we stay in sync /// with any other controls bound to the same source. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void currencyManager_PositionChanged(object sender, EventArgs e) { int index = this.currencyManager.Position; // Make sure the index is sane (-1 pops up from time to time) if (index < 0 || index >= this.Items.Count) return; // Avoid recursion. If we are currently changing the index, don't // start the process again. if (this.isChangingIndex) return; try { this.isChangingIndex = true; // We can't use the index directly, since our listview may be sorted this.SelectedObject = this.currencyManager.List[index]; // THINK: Do we always want to bring it into view? if (this.SelectedItems.Count > 0) this.SelectedItems[0].EnsureVisible(); } finally { this.isChangingIndex = false; } } private bool isChangingIndex = false; /// <summary> /// Handle a SelectedIndexChanged event /// </summary> /// <param name="e">The event</param> /// <remarks> /// Called by Windows Forms when the currently selected index of the /// control changes. This usually happens because the user clicked on /// the control. In this case we want to notify the CurrencyManager so /// that any other bound controls will remain in sync. This method will /// also be called when we changed our index as a result of a /// notification that originated from the CurrencyManager, and in that /// case we avoid notifying the CurrencyManager back! /// </remarks> protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged(e); // Prevent recursion if (this.isChangingIndex) return; // If we are bound to a datasource, and only one item is selected, // tell the currency manager which item is selected. if (this.SelectedIndices.Count == 1 && this.currencyManager != null) { try { this.isChangingIndex = true; // We can't use the selectedIndex directly, since our listview may be sorted. // So we have to find the index of the selected object within the original list. this.currencyManager.Position = this.currencyManager.List.IndexOf(this.SelectedObject); } finally { this.isChangingIndex = false; } } } #endregion } }
// // Application.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.Threading.Tasks; using System.Threading; namespace Xwt { public static class Application { static Toolkit toolkit; static ToolkitEngineBackend engine; static UILoop mainLoop; /// <summary> /// Gets the task scheduler of the current engine. /// </summary> /// <value>The toolkit specific task scheduler.</value> /// <remarks> /// The Xwt task scheduler marshals every Task to the Xwt GUI thread without concurrency. /// </remarks> public static TaskScheduler UITaskScheduler { get { return Toolkit.CurrentEngine.Scheduler; } } /// <summary> /// The main GUI loop. /// </summary> /// <value>The main loop.</value> public static UILoop MainLoop { get { return mainLoop; } } internal static System.Threading.Thread UIThread { get; private set; } /// <summary> /// Initialize Xwt with the best matching toolkit for the current platform. /// </summary> public static void Initialize () { if (engine != null) return; Initialize (null); } /// <summary> /// Initialize Xwt with the specified type. /// </summary> /// <param name="type">The toolkit type.</param> public static void Initialize (ToolkitType type) { Initialize (Toolkit.GetBackendType (type)); toolkit.Type = type; } /// <summary> /// Initialize Xwt with the specified backend type. /// </summary> /// <param name="backendType">The <see cref="Type.FullName"/> of the backend type.</param> public static void Initialize (string backendType) { if (engine != null) return; toolkit = Toolkit.Load (backendType, false); toolkit.SetActive (); engine = toolkit.Backend; mainLoop = new UILoop (toolkit); UIThread = System.Threading.Thread.CurrentThread; toolkit.EnterUserCode (); } /// <summary> /// Initializes Xwt as guest, embedded into an other existing toolkit. /// </summary> /// <param name="type">The toolkit type.</param> public static void InitializeAsGuest (ToolkitType type) { Initialize (type); toolkit.ExitUserCode (null); } /// <summary> /// Initializes Xwt as guest, embedded into an other existing toolkit. /// </summary> /// <param name="backendType">The <see cref="Type.FullName"/> of the backend type.</param> public static void InitializeAsGuest (string backendType) { if (backendType == null) throw new ArgumentNullException ("backendType"); Initialize (backendType); toolkit.ExitUserCode (null); } /// <summary> /// Runs the main Xwt GUI thread. /// </summary> /// <remarks> /// Blocks until the main GUI loop exits. Use <see cref="Application.Exit"/> /// to stop the Xwt application. /// </remarks> public static void Run () { if (XwtSynchronizationContext.AutoInstall) if (SynchronizationContext.Current == null || (!((engine.IsGuest) || (SynchronizationContext.Current is XwtSynchronizationContext)))) SynchronizationContext.SetSynchronizationContext (new XwtSynchronizationContext ()); toolkit.InvokePlatformCode (delegate { engine.RunApplication (); }); } /// <summary> /// Exits the Xwt application. /// </summary> public static void Exit () { toolkit.InvokePlatformCode (delegate { engine.ExitApplication (); }); if (SynchronizationContext.Current is XwtSynchronizationContext) XwtSynchronizationContext.Uninstall (); } /// <summary> /// Releases all resources used by the application /// </summary> /// <remarks>This method must be called before the application process ends</remarks> public static void Dispose () { ResourceManager.Dispose (); Toolkit.DisposeAll (); } /// <summary> /// Invokes an action in the GUI thread /// </summary> /// <param name='action'> /// The action to execute. /// </param> public static void Invoke (Action action) { if (action == null) throw new ArgumentNullException ("action"); engine.InvokeAsync (delegate { try { toolkit.EnterUserCode (); action (); toolkit.ExitUserCode (null); } catch (Exception ex) { toolkit.ExitUserCode (ex); } }); } /// <summary> /// Invokes an action in the GUI thread after the provided time span /// </summary> /// <returns> /// A timer object /// </returns> /// <param name='action'> /// The action to execute. /// </param> /// <remarks> /// This method schedules the execution of the provided function. The function /// must return 'true' if it has to be executed again after the time span, or 'false' /// if the timer can be discarded. /// The execution of the funciton can be canceled by disposing the returned object. /// </remarks> public static IDisposable TimeoutInvoke (int ms, Func<bool> action) { if (action == null) throw new ArgumentNullException ("action"); if (ms < 0) throw new ArgumentException ("ms can't be negative"); return TimeoutInvoke (TimeSpan.FromMilliseconds (ms), action); } /// <summary> /// Invokes an action in the GUI thread after the provided time span /// </summary> /// <returns> /// A timer object /// </returns> /// <param name='action'> /// The action to execute. /// </param> /// <remarks> /// This method schedules the execution of the provided function. The function /// must return 'true' if it has to be executed again after the time span, or 'false' /// if the timer can be discarded. /// The execution of the funciton can be canceled by disposing the returned object. /// </remarks> public static IDisposable TimeoutInvoke (TimeSpan timeSpan, Func<bool> action) { if (action == null) throw new ArgumentNullException ("action"); if (timeSpan.Ticks < 0) throw new ArgumentException ("timeSpan can't be negative"); Timer t = new Timer (); t.Id = engine.TimerInvoke (delegate { bool res = false; try { toolkit.EnterUserCode (); res = action (); toolkit.ExitUserCode (null); } catch (Exception ex) { toolkit.ExitUserCode (ex); } return res; }, timeSpan); return t; } /// <summary> /// Create a toolkit specific status icon. /// </summary> /// <returns>The status icon.</returns> public static StatusIcon CreateStatusIcon () { return new StatusIcon (); } /// <summary> /// Occurs when an exception is not caught. /// </summary> /// <remarks>Subscribe to handle uncaught exceptions, which could /// otherwise block or stop the application.</remarks> public static event EventHandler<ExceptionEventArgs> UnhandledException; class Timer: IDisposable { public object Id; public void Dispose () { Application.engine.CancelTimerInvoke (Id); } } /// <summary> /// Notifies about unhandled exceptions using the UnhandledException event. /// </summary> /// <param name="ex">The unhandled Exception.</param> internal static void NotifyException (Exception ex) { var unhandledException = UnhandledException; if (unhandledException != null) { unhandledException (null, new ExceptionEventArgs (ex)); } else { Console.WriteLine (ex); } } } /// <summary> /// The UILoop class provides access to the main GUI loop. /// </summary> public class UILoop { Toolkit toolkit; internal UILoop (Toolkit toolkit) { this.toolkit = toolkit; } /// <summary> /// Dispatches pending events in the GUI event queue /// </summary> public void DispatchPendingEvents () { try { toolkit.ExitUserCode (null); toolkit.Backend.DispatchPendingEvents (); } finally { toolkit.EnterUserCode (); } } /// <summary> /// Runs an Action after all user handlers have been processed and /// the main GUI loop is about to proceed with its next iteration. /// </summary> /// <param name="action">Action to execute.</param> public void QueueExitAction (Action action) { if (action == null) throw new ArgumentNullException ("action"); toolkit.QueueExitAction (action); } } public enum ToolkitType { Gtk = 1, Cocoa = 2, Wpf = 3, XamMac = 4, Gtk3 = 5, } }
// 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.IO; using System.IO.Packaging; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Globalization; namespace System.IO.Packaging { /// <summary> /// The package properties are a subset of the standard OLE property sets /// SummaryInformation and DocumentSummaryInformation, and include such properties /// as Title and Subject. /// </summary> /// <remarks> /// <para>Setting a property to null deletes this property. 'null' is never strictly speaking /// a property value, but an absence indicator.</para> /// </remarks> internal class PartBasedPackageProperties : PackageProperties { #region Constructors internal PartBasedPackageProperties(Package package) { _package = package; // Initialize literals as Xml Atomic strings. _nameTable = PackageXmlStringTable.NameTable; ReadPropertyValuesFromPackage(); // No matter what happens during initialization, the dirty flag should not be set. _dirty = false; } #endregion Constructors #region Public Properties /// <value> /// The primary creator. The identification is environment-specific and /// can consist of a name, email address, employee ID, etc. It is /// recommended that this value be only as verbose as necessary to /// identify the individual. /// </value> public override string Creator { get { return (string)GetPropertyValue(PackageXmlEnum.Creator); } set { RecordNewBinding(PackageXmlEnum.Creator, value); } } /// <value> /// The title. /// </value> public override string Title { get { return (string)GetPropertyValue(PackageXmlEnum.Title); } set { RecordNewBinding(PackageXmlEnum.Title, value); } } /// <value> /// The topic of the contents. /// </value> public override string Subject { get { return (string)GetPropertyValue(PackageXmlEnum.Subject); } set { RecordNewBinding(PackageXmlEnum.Subject, value); } } /// <value> /// The category. This value is typically used by UI applications to create navigation /// controls. /// </value> public override string Category { get { return (string)GetPropertyValue(PackageXmlEnum.Category); } set { RecordNewBinding(PackageXmlEnum.Category, value); } } /// <value> /// A delimited set of keywords to support searching and indexing. This /// is typically a list of terms that are not available elsewhere in the /// properties. /// </value> public override string Keywords { get { return (string)GetPropertyValue(PackageXmlEnum.Keywords); } set { RecordNewBinding(PackageXmlEnum.Keywords, value); } } /// <value> /// The description or abstract of the contents. /// </value> public override string Description { get { return (string)GetPropertyValue(PackageXmlEnum.Description); } set { RecordNewBinding(PackageXmlEnum.Description, value); } } /// <value> /// The type of content represented, generally defined by a specific /// use and intended audience. Example values include "Whitepaper", /// "Security Bulletin", and "Exam". (This property is distinct from /// MIME content types as defined in RFC 2616.) /// </value> public override string ContentType { get { string contentType = GetPropertyValue(PackageXmlEnum.ContentType) as string; return contentType; } set { RecordNewBinding(PackageXmlEnum.ContentType, value); } } /// <value> /// The status of the content. Example values include "Draft", /// "Reviewed", and "Final". /// </value> public override string ContentStatus { get { return (string)GetPropertyValue(PackageXmlEnum.ContentStatus); } set { RecordNewBinding(PackageXmlEnum.ContentStatus, value); } } /// <value> /// The version number. This value is set by the user or by the application. /// </value> public override string Version { get { return (string)GetPropertyValue(PackageXmlEnum.Version); } set { RecordNewBinding(PackageXmlEnum.Version, value); } } /// <value> /// The revision number. This value indicates the number of saves or /// revisions. The application is responsible for updating this value /// after each revision. /// </value> public override string Revision { get { return (string)GetPropertyValue(PackageXmlEnum.Revision); } set { RecordNewBinding(PackageXmlEnum.Revision, value); } } /// <value> /// The creation date and time. /// </value> public override Nullable<DateTime> Created { get { return GetDateTimePropertyValue(PackageXmlEnum.Created); } set { RecordNewBinding(PackageXmlEnum.Created, value); } } /// <value> /// The date and time of the last modification. /// </value> public override Nullable<DateTime> Modified { get { return GetDateTimePropertyValue(PackageXmlEnum.Modified); } set { RecordNewBinding(PackageXmlEnum.Modified, value); } } /// <value> /// The user who performed the last modification. The identification is /// environment-specific and can consist of a name, email address, /// employee ID, etc. It is recommended that this value be only as /// verbose as necessary to identify the individual. /// </value> public override string LastModifiedBy { get { return (string)GetPropertyValue(PackageXmlEnum.LastModifiedBy); } set { RecordNewBinding(PackageXmlEnum.LastModifiedBy, value); } } /// <value> /// The date and time of the last printing. /// </value> public override Nullable<DateTime> LastPrinted { get { return GetDateTimePropertyValue(PackageXmlEnum.LastPrinted); } set { RecordNewBinding(PackageXmlEnum.LastPrinted, value); } } /// <value> /// A language of the intellectual content of the resource /// </value> public override string Language { get { return (string)GetPropertyValue(PackageXmlEnum.Language); } set { RecordNewBinding(PackageXmlEnum.Language, value); } } /// <value> /// A unique identifier. /// </value> public override string Identifier { get { return (string)GetPropertyValue(PackageXmlEnum.Identifier); } set { RecordNewBinding(PackageXmlEnum.Identifier, value); } } #endregion Public Properties #region Internal Methods // Invoked from Package.Flush. // The expectation is that whatever is currently dirty will get flushed. internal void Flush() { if (!_dirty) return; // Make sure there is a part to write to and that it contains // the expected start markup. Stream zipStream = null; EnsureXmlWriter(ref zipStream); // Write the property elements and clear _dirty. SerializeDirtyProperties(); // add closing markup and close the writer. CloseXmlWriter(); Debug.Assert(_xmlWriter == null); zipStream?.Dispose(); } // Invoked from Package.Close. internal void Close() { Flush(); } #endregion Internal Methods #region Private Methods // The property store is implemented as a hash table of objects. // Keys are taken from the set of string constants defined in this // class and compared by their references rather than their values. private object GetPropertyValue(PackageXmlEnum propertyName) { _package.ThrowIfWriteOnly(); if (!_propertyDictionary.ContainsKey(propertyName)) return null; return _propertyDictionary[propertyName]; } // Shim function to adequately cast the result of GetPropertyValue. private Nullable<DateTime> GetDateTimePropertyValue(PackageXmlEnum propertyName) { object valueObject = GetPropertyValue(propertyName); if (valueObject == null) return null; // If an object is there, it will be a DateTime (not a Nullable<DateTime>). return (Nullable<DateTime>)valueObject; } // Set new property value. // Override that sets the initializing flag to false to reflect the default // situation: recording a binding to implement a value assignment. private void RecordNewBinding(PackageXmlEnum propertyenum, object value) { RecordNewBinding(propertyenum, value, false /* not invoked at construction */, null); } // Set new property value. // Null value is passed for deleting a property. // While initializing, we are not assigning new values, and so the dirty flag should // stay untouched. private void RecordNewBinding(PackageXmlEnum propertyenum, object value, bool initializing, XmlReader reader) { // If we are reading values from the package, reader cannot be null Debug.Assert(!initializing || reader != null); if (!initializing) _package.ThrowIfReadOnly(); // Case of an existing property. if (_propertyDictionary.ContainsKey(propertyenum)) { // Parsing should detect redundant entries. if (initializing) { throw new XmlException(SR.Format(SR.DuplicateCorePropertyName, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Nullable<DateTime> values can be checked against null if (value == null) // a deletion { _propertyDictionary.Remove(propertyenum); } else // an update { _propertyDictionary[propertyenum] = value; } // If the binding is an assignment rather than an initialization, set the dirty flag. _dirty = !initializing; } // Case of an initial value being set for a property. If value is null, no need to do anything else if (value != null) { _propertyDictionary.Add(propertyenum, value); // If the binding is an assignment rather than an initialization, set the dirty flag. _dirty = !initializing; } } // Initialize object from property values found in package. // All values will remain null if the package is not enabled for reading. private void ReadPropertyValuesFromPackage() { Debug.Assert(_propertyPart == null); // This gets called exclusively from constructor. // Don't try to read properties from the package it does not have read access if (_package.FileOpenAccess == FileAccess.Write) return; _propertyPart = GetPropertyPart(); if (_propertyPart == null) return; ParseCorePropertyPart(_propertyPart); } // Locate core properties part using the package relationship that points to it. private PackagePart GetPropertyPart() { // Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType. PackageRelationship corePropertiesRelationship = GetCorePropertiesRelationship(); if (corePropertiesRelationship == null) return null; // Retrieve the part referenced by its target URI. if (corePropertiesRelationship.TargetMode != TargetMode.Internal) throw new FileFormatException(SR.NoExternalTargetForMetadataRelationship); PackagePart propertiesPart = null; Uri propertiesPartUri = PackUriHelper.ResolvePartUri( PackUriHelper.PackageRootUri, corePropertiesRelationship.TargetUri); if (!_package.PartExists(propertiesPartUri)) throw new FileFormatException(SR.DanglingMetadataRelationship); propertiesPart = _package.GetPart(propertiesPartUri); if (!propertiesPart.ValidatedContentType.AreTypeAndSubTypeEqual(s_coreDocumentPropertiesContentType)) { throw new FileFormatException(SR.WrongContentTypeForPropertyPart); } return propertiesPart; } // Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType. private PackageRelationship GetCorePropertiesRelationship() { PackageRelationship propertiesPartRelationship = null; foreach (PackageRelationship rel in _package.GetRelationshipsByType(CoreDocumentPropertiesRelationshipType)) { if (propertiesPartRelationship != null) { throw new FileFormatException(SR.MoreThanOneMetadataRelationships); } propertiesPartRelationship = rel; } return propertiesPartRelationship; } // Deserialize properties part. private void ParseCorePropertyPart(PackagePart part) { XmlReaderSettings xrs = new XmlReaderSettings(); xrs.NameTable = _nameTable; using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read)) // Create a reader that uses _nameTable so as to use the set of tag literals // in effect as a set of atomic identifiers. using (XmlReader reader = XmlReader.Create(stream, xrs)) { //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op if (reader.MoveToContent() != XmlNodeType.Element || (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace) || (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties)) { throw new XmlException(SR.CorePropertiesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // The schema is closed and defines no attributes on the root element. if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Iterate through property elements until EOF. Note the proper closing of all // open tags is checked by the reader itself. // This loop deals only with depth-1 start tags. Handling of element content // is delegated to dedicated functions. int attributesCount; while (reader.Read() && reader.MoveToContent() != XmlNodeType.None) { // Ignore end-tags. We check element errors on opening tags. if (reader.NodeType == XmlNodeType.EndElement) continue; // Any content markup that is not an element here is unexpected. if (reader.NodeType != XmlNodeType.Element) { throw new XmlException(SR.PropertyStartTagExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Any element below the root should open at level 1 exclusively. if (reader.Depth != 1) { throw new XmlException(SR.NoStructuredContentInsideProperties, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader); // Property elements can occur in any order (xsd:all). object localName = reader.LocalName; PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName); string valueType = PackageXmlStringTable.GetValueType(xmlStringIndex); if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error. { throw new XmlException( SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Any element not in the valid core properties namespace is unexpected. // The following is an object comparison, not a string comparison. if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex))) { throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } if (string.CompareOrdinal(valueType, "String") == 0) { // The schema is closed and defines no attributes on this type of element. if (attributesCount != 0) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader); } else if (string.CompareOrdinal(valueType, "DateTime") == 0) { int allowedAttributeCount = (object)reader.NamespaceURI == PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace) ? 1 : 0; // The schema is closed and defines no attributes on this type of element. if (attributesCount != allowedAttributeCount) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } if (allowedAttributeCount != 0) { ValidateXsiType(reader, PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace), W3cdtf); } RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader); } else // An unexpected element is an error. { Debug.Assert(false, "Unknown value type for properties"); } } } } // This method validates xsi:type="dcterms:W3CDTF" // The value of xsi:type is a qualified name. It should have a prefix that matches // the xml namespace (ns) within the scope and the name that matches name // The comparisons should be case-sensitive comparisons internal static void ValidateXsiType(XmlReader reader, object ns, string name) { // Get the value of xsi;type string typeValue = reader.GetAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type), PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace)); // Missing xsi:type if (typeValue == null) { throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } int index = typeValue.IndexOf(':'); // The value of xsi:type is not a qualified name if (index == -1) { throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Check the following conditions // The namespace of the prefix (string before ":") matches "ns" // The name (string after ":") matches "name" if (!object.ReferenceEquals(ns, reader.LookupNamespace(typeValue.Substring(0, index))) || string.CompareOrdinal(name, typeValue.Substring(index + 1, typeValue.Length - index - 1)) != 0) { throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } } // Expect to find text data and return its value. private string GetStringData(XmlReader reader) { if (reader.IsEmptyElement) return string.Empty; reader.Read(); if (reader.MoveToContent() == XmlNodeType.EndElement) return string.Empty; // If there is any content in the element, it should be text content and nothing else. if (reader.NodeType != XmlNodeType.Text) { throw new XmlException(SR.NoStructuredContentInsideProperties, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } return reader.Value; } // Expect to find text data and return its value as DateTime. private Nullable<DateTime> GetDateData(XmlReader reader) { string data = GetStringData(reader); DateTime dateTime; try { // Note: No more than 7 second decimals are accepted by the // list of formats given. There currently is no method that // would perform XSD-compliant parsing. dateTime = DateTime.ParseExact(data, s_dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None); } catch (FormatException exc) { throw new XmlException(SR.XsdDateTimeExpected, exc, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } return dateTime; } // Make sure there is a part to write to and that it contains // the expected start markup. private void EnsureXmlWriter(ref Stream zipStream) { if (_xmlWriter != null) return; EnsurePropertyPart(); // Should succeed or throw an exception. zipStream = _propertyPart.GetStream(FileMode.Create, FileAccess.Write); Stream writerStream = new IgnoreFlushAndCloseStream(zipStream); _xmlWriter = XmlWriter.Create(writerStream, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }); WriteXmlStartTagsForPackageProperties(); } // Create a property part if none exists yet. private void EnsurePropertyPart() { if (_propertyPart != null) return; // If _propertyPart is null, no property part existed when this object was created, // and this function is being called for the first time. // However, when read access is available, we can afford the luxury of checking whether // a property part and its referring relationship got correctly created in the meantime // outside of this class. // In write-only mode, it is impossible to perform this check, and the external creation // scenario will result in an exception being thrown. if (_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite) { _propertyPart = GetPropertyPart(); if (_propertyPart != null) return; } CreatePropertyPart(); } // Create a new property relationship pointing to a new property part. // If only this class is used for manipulating property relationships, there cannot be a // pre-existing dangling property relationship. // No check is performed here for other classes getting misused insofar as this function // has to work in write-only mode. private void CreatePropertyPart() { _propertyPart = _package.CreatePart(GeneratePropertyPartUri(), s_coreDocumentPropertiesContentType.ToString()); _package.CreateRelationship(_propertyPart.Uri, TargetMode.Internal, CoreDocumentPropertiesRelationshipType); } private Uri GeneratePropertyPartUri() { string propertyPartName = DefaultPropertyPartNamePrefix + Guid.NewGuid().ToString(GuidStorageFormatString) + DefaultPropertyPartNameExtension; return PackUriHelper.CreatePartUri(new Uri(propertyPartName, UriKind.Relative)); } private void WriteXmlStartTagsForPackageProperties() { _xmlWriter.WriteStartDocument(); // <coreProperties _xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(PackageXmlEnum.CoreProperties), // local name PackageXmlStringTable.GetXmlString(PackageXmlEnum.PackageCorePropertiesNamespace)); // namespace // xmlns:dc _xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix), PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespacePrefix), null, PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespace)); // xmlns:dcterms _xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix), PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublincCoreTermsNamespacePrefix), null, PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace)); // xmlns:xsi _xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix), PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespacePrefix), null, PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace)); } // Write the property elements and clear _dirty. private void SerializeDirtyProperties() { // Create a property element for each non-null entry. foreach (KeyValuePair<PackageXmlEnum, object> entry in _propertyDictionary) { Debug.Assert(entry.Value != null); PackageXmlEnum propertyNamespace = PackageXmlStringTable.GetXmlNamespace(entry.Key); _xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(entry.Key), PackageXmlStringTable.GetXmlString(propertyNamespace)); if (entry.Value is Nullable<DateTime>) { if (propertyNamespace == PackageXmlEnum.DublinCoreTermsNamespace) { // xsi:type= _xmlWriter.WriteStartAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type), PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace)); // "dcterms:W3CDTF" _xmlWriter.WriteQualifiedName(W3cdtf, PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace)); _xmlWriter.WriteEndAttribute(); } // Use sortable ISO 8601 date/time pattern. Include second fractions down to the 100-nanosecond interval, // which is the definition of a "tick" for the DateTime type. _xmlWriter.WriteString(XmlConvert.ToString(((Nullable<DateTime>)entry.Value).Value.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffffffZ")); } else { // The following uses the fact that ToString is virtual. _xmlWriter.WriteString(entry.Value.ToString()); } _xmlWriter.WriteEndElement(); } // Mark properties as saved. _dirty = false; } // Add end markup and close the writer. private void CloseXmlWriter() { // Close the root element. _xmlWriter.WriteEndElement(); // Close the writer itself. _xmlWriter.Dispose(); // Make sure we know it's closed. _xmlWriter = null; } #endregion Private Methods #region Private Fields private Package _package; private PackagePart _propertyPart; private XmlWriter _xmlWriter; // Table of objects from the closed set of literals defined below. // (Uses object comparison rather than string comparison.) private const int NumCoreProperties = 16; private Dictionary<PackageXmlEnum, object> _propertyDictionary = new Dictionary<PackageXmlEnum, object>(NumCoreProperties); private bool _dirty = false; // This System.Xml.NameTable makes sure that we use the same references to strings // throughout (including when parsing Xml) and so can perform reference comparisons // rather than value comparisons. private NameTable _nameTable; // Literals. private static readonly ContentType s_coreDocumentPropertiesContentType = new ContentType("application/vnd.openxmlformats-package.core-properties+xml"); private const string CoreDocumentPropertiesRelationshipType = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; private const string DefaultPropertyPartNamePrefix = "/package/services/metadata/core-properties/"; private const string W3cdtf = "W3CDTF"; private const string DefaultPropertyPartNameExtension = ".psmdcp"; private const string GuidStorageFormatString = @"N"; // N - simple format without adornments private static PackageXmlEnum[] s_validProperties = new PackageXmlEnum[] { PackageXmlEnum.Creator, PackageXmlEnum.Identifier, PackageXmlEnum.Title, PackageXmlEnum.Subject, PackageXmlEnum.Description, PackageXmlEnum.Language, PackageXmlEnum.Created, PackageXmlEnum.Modified, PackageXmlEnum.ContentType, PackageXmlEnum.Keywords, PackageXmlEnum.Category, PackageXmlEnum.Version, PackageXmlEnum.LastModifiedBy, PackageXmlEnum.ContentStatus, PackageXmlEnum.Revision, PackageXmlEnum.LastPrinted }; // Array of formats to supply to XmlConvert.ToDateTime or DateTime.ParseExact. // xsd:DateTime requires full date time in sortable (ISO 8601) format. // It can be expressed in local time, universal time (Z), or relative to universal time (zzz). // Negative years are accepted. // IMPORTANT: Second fractions are recognized only down to 1 tenth of a microsecond because this is the resolution // of the DateTime type. The Xml standard, however, allows any number of decimals; but XmlConvert only offers // this very awkward API with an explicit pattern enumeration. private static readonly string[] s_dateTimeFormats = new string[] { "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:sszzz", @"\-yyyy-MM-ddTHH:mm:ss", @"\-yyyy-MM-ddTHH:mm:ssZ", @"\-yyyy-MM-ddTHH:mm:sszzz", "yyyy-MM-ddTHH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss.fZ", "yyyy-MM-ddTHH:mm:ss.fzzz", @"\-yyyy-MM-ddTHH:mm:ss.f", @"\-yyyy-MM-ddTHH:mm:ss.fZ", @"\-yyyy-MM-ddTHH:mm:ss.fzzz", "yyyy-MM-ddTHH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss.ffZ", "yyyy-MM-ddTHH:mm:ss.ffzzz", @"\-yyyy-MM-ddTHH:mm:ss.ff", @"\-yyyy-MM-ddTHH:mm:ss.ffZ", @"\-yyyy-MM-ddTHH:mm:ss.ffzzz", "yyyy-MM-ddTHH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ss.fffZ", "yyyy-MM-ddTHH:mm:ss.fffzzz", @"\-yyyy-MM-ddTHH:mm:ss.fff", @"\-yyyy-MM-ddTHH:mm:ss.fffZ", @"\-yyyy-MM-ddTHH:mm:ss.fffzzz", "yyyy-MM-ddTHH:mm:ss.ffff", "yyyy-MM-ddTHH:mm:ss.ffffZ", "yyyy-MM-ddTHH:mm:ss.ffffzzz", @"\-yyyy-MM-ddTHH:mm:ss.ffff", @"\-yyyy-MM-ddTHH:mm:ss.ffffZ", @"\-yyyy-MM-ddTHH:mm:ss.ffffzzz", "yyyy-MM-ddTHH:mm:ss.fffff", "yyyy-MM-ddTHH:mm:ss.fffffZ", "yyyy-MM-ddTHH:mm:ss.fffffzzz", @"\-yyyy-MM-ddTHH:mm:ss.fffff", @"\-yyyy-MM-ddTHH:mm:ss.fffffZ", @"\-yyyy-MM-ddTHH:mm:ss.fffffzzz", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-ddTHH:mm:ss.ffffffZ", "yyyy-MM-ddTHH:mm:ss.ffffffzzz", @"\-yyyy-MM-ddTHH:mm:ss.ffffff", @"\-yyyy-MM-ddTHH:mm:ss.ffffffZ", @"\-yyyy-MM-ddTHH:mm:ss.ffffffzzz", "yyyy-MM-ddTHH:mm:ss.fffffff", "yyyy-MM-ddTHH:mm:ss.fffffffZ", "yyyy-MM-ddTHH:mm:ss.fffffffzzz", @"\-yyyy-MM-ddTHH:mm:ss.fffffff", @"\-yyyy-MM-ddTHH:mm:ss.fffffffZ", @"\-yyyy-MM-ddTHH:mm:ss.fffffffzzz", }; #endregion Private Fields } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace VSSolutionBuilder { /// <summary> /// Class representing a .vcxproj on disk. /// </summary> sealed class VSProject : HasGuid { private VSSolution Solution { get; set; } /// <summary> /// Get the project filepath /// </summary> public string ProjectPath { get; private set; } /// <summary> /// Get the dictionary of EConfiguration to VSProjectConfiguration /// </summary> public System.Collections.Generic.Dictionary<Bam.Core.EConfiguration, VSProjectConfiguration> Configurations { get; private set; } = new System.Collections.Generic.Dictionary<Bam.Core.EConfiguration, VSProjectConfiguration>(); private Bam.Core.Array<VSSettingsGroup> ProjectSettings { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); private Bam.Core.Array<VSSettingsGroup> Headers { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); private Bam.Core.Array<VSSettingsGroup> Sources { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); private Bam.Core.Array<VSSettingsGroup> Others { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); private Bam.Core.Array<VSSettingsGroup> Resources { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); private Bam.Core.Array<VSSettingsGroup> AssemblyFiles { get; set; } = new Bam.Core.Array<VSSettingsGroup>(); /// <summary> /// Get the filter applied to this project /// </summary> public VSProjectFilter Filter { get; private set; } private Bam.Core.Array<VSProject> OrderOnlyDependentProjects { get; set; } = new Bam.Core.Array<VSProject>(); private Bam.Core.Array<VSProject> LinkDependentProjects { get; set; } = new Bam.Core.Array<VSProject>(); /// <summary> /// Construct an instance, at the given path, and added to the given solution. /// The module association is at the solution level (by type), and in child configurations /// which have a 1-1 Module relationship. /// </summary> /// <param name="solution">VSSolution to add the project to</param> /// <param name="projectPath">Path at which the project resides.</param> public VSProject( VSSolution solution, Bam.Core.TokenizedString projectPath) : base(projectPath.ToString()) { this.Solution = solution; this.ProjectPath = projectPath.ToString(); this.Filter = new VSProjectFilter(this); } private static C.EBit GetModuleBitDepth( Bam.Core.Module module) { if (module is C.CModule) { return (module as C.CModule).BitDepth; } else { // best guess return (C.EBit)Bam.Core.CommandLineProcessor.Evaluate(new C.Options.DefaultBitDepth()); } } /// <summary> /// Get the VSProjectConfiguration within this project corresponding to this Module /// </summary> /// <param name="module">Module to get configuration for</param> /// <returns>The VSProjectConfiguration</returns> public VSProjectConfiguration GetConfiguration( Bam.Core.Module module) { lock (this) // this is quite a heavyweight lock { if (null == module.MetaData) { module.MetaData = this; } } lock (this.Configurations) { var moduleConfig = module.BuildEnvironment.Configuration; if (this.Configurations.ContainsKey(moduleConfig)) { return this.Configurations[moduleConfig]; } var platform = Bam.Core.EPlatform.Invalid; var bitDepth = GetModuleBitDepth(module); switch (bitDepth) { case C.EBit.ThirtyTwo: platform = Bam.Core.EPlatform.Win32; break; case C.EBit.SixtyFour: platform = Bam.Core.EPlatform.Win64; break; } if (Bam.Core.EPlatform.Invalid == platform) { throw new Bam.Core.Exception($"Platform cannot be extracted from the tool {module.Tool.ToString()} for project {this.ProjectPath}"); } var configuration = new VSProjectConfiguration(this, module, platform); this.Configurations.Add(moduleConfig, configuration); return configuration; } } /// <summary> /// Get the unique Settings group for the Module /// </summary> /// <param name="module">Module to get the group for</param> /// <param name="group">The type of the group queried</param> /// <param name="path">The path this settings group corresponds to. Default to null.</param> /// <returns></returns> public VSSettingsGroup GetUniqueSettingsGroup( Bam.Core.Module module, VSSettingsGroup.ESettingsGroup group, Bam.Core.TokenizedString path) { lock (this.ProjectSettings) { foreach (var settings in this.ProjectSettings) { if (null == path) { if ((null == settings.Path) && (settings.Group == group)) { return settings; } } else { // ignore checking the group, as files can mutate between them during the buildprocess // (e.g. headers into custom builds) // TODO: can this be a TokenizedString hash compare? if (settings.Path.ToString().Equals(path.ToString(), System.StringComparison.Ordinal)) { return settings; } } } var newGroup = new VSSettingsGroup(this, module, group, path); this.ProjectSettings.Add(newGroup); return newGroup; } } private void AddToFilter( VSSettingsGroup group) { lock (this.Filter) { this.Filter.AddFile(group); } } /// <summary> /// Add a header file to the project /// </summary> /// <param name="header">Settings group corresponding to the header</param> public void AddHeader( VSSettingsGroup header) { lock (this.Headers) { this.Headers.AddUnique(header); } AddToFilter(header); } /// <summary> /// Add a source file to the project /// </summary> /// <param name="source">Settings group correspnding to the source file</param> public void AddSource( VSSettingsGroup source) { lock (this.Sources) { this.Sources.AddUnique(source); } AddToFilter(source); } /// <summary> /// Add an arbitrary file to the project /// </summary> /// <param name="other">Settings group corresponding to the file</param> public void AddOtherFile( VSSettingsGroup other) { lock (this.Others) { this.Others.AddUnique(other); } AddToFilter(other); } /// <summary> /// Add a resource file to the project /// </summary> /// <param name="other">Settings group corresponding to the resource file</param> public void AddResourceFile( VSSettingsGroup other) { lock (this.Resources) { this.Resources.AddUnique(other); } AddToFilter(other); } /// <summary> /// Add an assembly file to the project /// </summary> /// <param name="other">Settings group corresponding to the assembly file</param> public void AddAssemblyFile( VSSettingsGroup other) { lock (this.AssemblyFiles) { this.AssemblyFiles.AddUnique(other); } AddToFilter(other); } /// <summary> /// Add an order only dependency on another project /// </summary> /// <param name="dependentProject">Project that is an order only dependency</param> public void AddOrderOnlyDependency( VSProject dependentProject) { if (this.LinkDependentProjects.Contains(dependentProject)) { Bam.Core.Log.DebugMessage($"Project {this.ProjectPath} already contains a link dependency on {dependentProject.ProjectPath}. There is no need to add it as an order-only dependency."); return; } lock (this.OrderOnlyDependentProjects) { this.OrderOnlyDependentProjects.AddUnique(dependentProject); } } /// <summary> /// Add a link-time dependency on another project /// </summary> /// <param name="dependentProject">Project that is a link time dependency</param> public void AddLinkDependency( VSProject dependentProject) { if (this.OrderOnlyDependentProjects.Contains(dependentProject)) { Bam.Core.Log.DebugMessage($"Project {this.ProjectPath} already contains an order-only dependency on {dependentProject.ProjectPath}. Removing the order-only dependency, and upgrading to a link dependency."); this.OrderOnlyDependentProjects.Remove(dependentProject); } lock (this.LinkDependentProjects) { this.LinkDependentProjects.AddUnique(dependentProject); } } private void SerializeDependentProjects( System.Xml.XmlDocument document, System.Xml.XmlElement parentEl) { if (this.OrderOnlyDependentProjects.Count > 0) { var itemGroupEl = document.CreateVSItemGroup(parentEl: parentEl); foreach (var project in this.OrderOnlyDependentProjects) { foreach (var config in this.Configurations) { if (!config.Value.ContainsOrderOnlyDependency(project)) { continue; } var projectRefEl = document.CreateVSElement("ProjectReference", parentEl: itemGroupEl); projectRefEl.SetAttribute( "Include", Bam.Core.RelativePathUtilities.GetRelativePathFromRoot( System.IO.Path.GetDirectoryName(this.ProjectPath), project.ProjectPath ) ); projectRefEl.SetAttribute("Condition", config.Value.ConditionText); document.CreateVSElement("Project", value: project.Guid.ToString("B"), parentEl: projectRefEl); document.CreateVSElement("LinkLibraryDependencies", value: "false", parentEl: projectRefEl); } } } if (this.LinkDependentProjects.Count > 0) { var itemGroupEl = document.CreateVSItemGroup(parentEl: parentEl); foreach (var project in this.LinkDependentProjects) { foreach (var config in this.Configurations) { if (!config.Value.ContainsLinkDependency(project)) { continue; } var projectRefEl = document.CreateVSElement("ProjectReference", parentEl: itemGroupEl); projectRefEl.SetAttribute( "Include", Bam.Core.RelativePathUtilities.GetRelativePathFromRoot( System.IO.Path.GetDirectoryName(this.ProjectPath), project.ProjectPath ) ); projectRefEl.SetAttribute("Condition", config.Value.ConditionText); document.CreateVSElement("Project", value: project.Guid.ToString("B"), parentEl: projectRefEl); document.CreateVSElement("LinkLibraryDependencies", value: "true", parentEl: projectRefEl); } } } } /// <summary> /// Serialize user settings for the project to XML. /// This includes working directories for the debugger, which are per configuration. /// </summary> /// <returns>The XML document containing the user settings.</returns> public System.Xml.XmlDocument SerializeUserSettings() { var document = new System.Xml.XmlDocument(); var projectEl = this.CreateRootProject(document); var visualCMeta = Bam.Core.Graph.Instance.PackageMetaData<VisualC.MetaData>("VisualC"); projectEl.SetAttribute("ToolsVersion", visualCMeta.VCXProjToolsVersion); foreach (var configuration in this.Configurations.Select(item => item.Value)) { var el = document.CreateVSPropertyGroup(parentEl: projectEl, condition: configuration.ConditionText); var debuggerFlavour = document.CreateVSElement("DebuggerFlavor"); debuggerFlavour.InnerText = "WindowsLocalDebugger"; if (configuration.Module is C.ConsoleApplication module && module.WorkingDirectory != null) { if (!module.WorkingDirectory.IsParsed) { module.WorkingDirectory.Parse(); } var workingDir = document.CreateVSElement("LocalDebuggerWorkingDirectory"); workingDir.InnerText = module.WorkingDirectory.ToString(); el.AppendChild(workingDir); } el.AppendChild(debuggerFlavour); } return document; } private void AddWindowsSDKVersion( System.Xml.XmlDocument document, System.Xml.XmlElement globalPropertyGroup, VisualC.MetaData visualCMeta) { string windowsSDKVersion = null; foreach (var config in this.Configurations) { var vcEnv = visualCMeta.Environment(GetModuleBitDepth(config.Value.Module)); if (!vcEnv.ContainsKey("WindowsSDKVersion")) { continue; } var config_windowssdk_version = vcEnv["WindowsSDKVersion"].First().ToString().TrimEnd(System.IO.Path.DirectorySeparatorChar); if (null == windowsSDKVersion) { windowsSDKVersion = config_windowssdk_version; } else if (!config_windowssdk_version.Equals(windowsSDKVersion, System.StringComparison.Ordinal)) { throw new Bam.Core.Exception("Inconsistent WindowsSDK versions between project configurations"); } } if (null != windowsSDKVersion) { document.CreateVSElement("WindowsTargetPlatformVersion", value: windowsSDKVersion, parentEl: globalPropertyGroup); } } /// <summary> /// Serialize the project to XML /// </summary> /// <returns>XML document containing the project.</returns> public System.Xml.XmlDocument Serialize() { var document = new System.Xml.XmlDocument(); var projectEl = this.CreateRootProject(document); projectEl.SetAttribute("DefaultTargets", "Build"); var visualCMeta = Bam.Core.Graph.Instance.PackageMetaData<VisualC.MetaData>("VisualC"); projectEl.SetAttribute("ToolsVersion", visualCMeta.VCXProjToolsVersion); // define configurations in the project var configurationItemGroup = document.CreateVSItemGroup("ProjectConfigurations", projectEl); foreach (var config in this.Configurations) { var projectConfigEl = document.CreateVSElement("ProjectConfiguration", parentEl: configurationItemGroup); projectConfigEl.SetAttribute("Include", config.Value.FullName); document.CreateVSElement("Configuration", value: config.Value.ConfigurationName, parentEl: projectConfigEl); document.CreateVSElement("Platform", value: config.Value.PlatformName, parentEl: projectConfigEl); } // global properties var globalPropertyGroup = document.CreateVSPropertyGroup(label: "Globals", parentEl: projectEl); document.CreateVSElement("ProjectGuid", value: this.Guid.ToString("B").ToUpper(), parentEl: globalPropertyGroup); this.AddWindowsSDKVersion(document, globalPropertyGroup, visualCMeta); document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.Default.props", parentEl: projectEl); // configuration properties foreach (var config in this.Configurations) { config.Value.SerializeProperties(document, projectEl); } document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.props", parentEl: projectEl); if (this.AssemblyFiles.Any()) { var extensionSettings = document.CreateVSImportGroup("ExtensionSettings", parentEl: projectEl); document.CreateVSImport(@"$(VCTargetsPath)\BuildCustomizations\masm.props", parentEl: extensionSettings); } // configuration paths foreach (var config in this.Configurations) { config.Value.SerializePaths(document, projectEl); } // tool settings foreach (var config in this.Configurations) { config.Value.SerializeSettings(document, projectEl); } // input files (these are VSSettingsGroups, but configuration agnostic) if (this.Sources.Count > 0) { var sourcesGroup = document.CreateVSItemGroup(parentEl: projectEl); foreach (var group in this.Sources) { foreach (var config in this.Configurations) { if (!config.Value.ContainsSource(group)) { group.AddSetting( "ExcludedFromBuild", "true", config.Value.ConditionText ); } } group.Serialize(document, sourcesGroup); } } if (this.Headers.Count > 0) { var headersGroup = document.CreateVSItemGroup(parentEl: projectEl); foreach (var group in this.Headers) { foreach (var config in this.Configurations) { if (!config.Value.ContainsHeader(group)) { group.AddSetting( "ExcludedFromBuild", "true", config.Value.ConditionText ); } } group.Serialize(document, headersGroup); } } if (this.Others.Count > 0) { var otherGroup = document.CreateVSItemGroup(parentEl: projectEl); foreach (var group in this.Others) { group.Serialize(document, otherGroup); } } if (this.Resources.Count > 0) { var resourceGroup = document.CreateVSItemGroup(parentEl: projectEl); foreach (var group in this.Resources) { foreach (var config in this.Configurations) { if (!config.Value.ContainsResourceFile(group)) { group.AddSetting( "ExcludedFromBuild", "true", config.Value.ConditionText ); } } group.Serialize(document, resourceGroup); } } if (this.AssemblyFiles.Count > 0) { var assemblerGroup = document.CreateVSItemGroup(parentEl: projectEl); foreach (var group in this.AssemblyFiles) { foreach (var config in this.Configurations) { if (!config.Value.ContainsAssemblyFile(group)) { group.AddSetting( "ExcludedFromBuild", "true", config.Value.ConditionText ); } } group.Serialize(document, assemblerGroup); } } // dependent projects this.SerializeDependentProjects(document, projectEl); document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.targets", parentEl: projectEl); if (this.AssemblyFiles.Any()) { var extensionTargets = document.CreateVSImportGroup("ExtensionTargets", parentEl: projectEl); document.CreateVSImport(@"$(VCTargetsPath)\BuildCustomizations\masm.targets", parentEl: extensionTargets); } return document; } private System.Xml.XmlElement CreateRootProject( System.Xml.XmlDocument document) { var project = document.CreateVSElement("Project"); document.AppendChild(project); return project; } /// <summary> /// Query whether the .vcxproj corresponding to the Module is buildable. /// </summary> /// <param name="module">Module to query.</param> /// <returns>true if the project is buildable</returns> public static bool IsBuildable( Bam.Core.Module module) { var project = module.MetaData as VSProject; if (null == project) { return false; } var configuration = project.GetConfiguration(module); switch (configuration.Type) { case VSProjectConfiguration.EType.Application: case VSProjectConfiguration.EType.DynamicLibrary: case VSProjectConfiguration.EType.StaticLibrary: return true; case VSProjectConfiguration.EType.Utility: { // there are some utility projects just for copying files around (and no source files), which do need to build // so query whether the original module had the [C.Prebuilt] attribute var isPrebuilt = (module is C.CModule) && (module as C.CModule).IsPrebuilt; return !isPrebuilt; } default: throw new Bam.Core.Exception($"Unrecognized project type, {configuration.Type}"); } } } }
using System.Drawing; namespace openglFramework { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox2 = new System.Windows.Forms.GroupBox(); this.perspectiveButton = new openglFramework.ToggleButton(); this.fieldOfView = new System.Windows.Forms.NumericUpDown(); this.parallelButton = new openglFramework.ToggleButton(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.rotateButton = new openglFramework.ToggleButton(); this.panButton = new openglFramework.ToggleButton(); this.zoomButton = new openglFramework.ToggleButton(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.mainStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.springToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.loadingProgressBar = new System.Windows.Forms.ToolStripProgressBar(); this.selectedCountStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.openglVersionStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.fpsStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.oglfVersionStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.wireframeButton = new openglFramework.ToggleButton(); this.edgesButton = new openglFramework.ToggleButton(); this.shadedButton = new openglFramework.ToggleButton(); this.groupBox9 = new System.Windows.Forms.GroupBox(); this.showLabelsButton = new openglFramework.ToggleButton(); this.showOriginButton = new openglFramework.ToggleButton(); this.showBoundingBoxButton = new openglFramework.ToggleButton(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.oddB = new System.Windows.Forms.NumericUpDown(); this.oddG = new System.Windows.Forms.NumericUpDown(); this.oddR = new System.Windows.Forms.NumericUpDown(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.evenB = new System.Windows.Forms.NumericUpDown(); this.evenG = new System.Windows.Forms.NumericUpDown(); this.evenR = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.sideLength = new System.Windows.Forms.NumericUpDown(); this.cornerY = new System.Windows.Forms.NumericUpDown(); this.cornerX = new System.Windows.Forms.NumericUpDown(); this.openGLControl1 = new openglFramework.OpenGLControl(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.fieldOfView)).BeginInit(); this.groupBox4.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.groupBox6.SuspendLayout(); this.groupBox9.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.oddB)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.oddG)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.oddR)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.evenB)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.evenG)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.evenR)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.sideLength)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.cornerY)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.cornerX)).BeginInit(); this.SuspendLayout(); // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.perspectiveButton); this.groupBox2.Controls.Add(this.fieldOfView); this.groupBox2.Controls.Add(this.parallelButton); this.groupBox2.Location = new System.Drawing.Point(440, 53); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(298, 45); this.groupBox2.TabIndex = 3; this.groupBox2.TabStop = false; this.groupBox2.Text = "Projection"; // // perspectiveButton // this.perspectiveButton.Appearance = System.Windows.Forms.Appearance.Button; this.perspectiveButton.Location = new System.Drawing.Point(102, 17); this.perspectiveButton.Name = "perspectiveButton"; this.perspectiveButton.Size = new System.Drawing.Size(94, 22); this.perspectiveButton.TabIndex = 1; this.perspectiveButton.Text = "Perspective"; this.perspectiveButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.perspectiveButton.Click += new System.EventHandler(this.perspectiveButton_Click); // // fieldOfView // this.fieldOfView.Enabled = false; this.fieldOfView.Location = new System.Drawing.Point(199, 18); this.fieldOfView.Name = "fieldOfView"; this.fieldOfView.Size = new System.Drawing.Size(93, 21); this.fieldOfView.TabIndex = 2; this.fieldOfView.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.fieldOfView.ValueChanged += new System.EventHandler(this.fieldOfView_ValueChanged); // // parallelButton // this.parallelButton.Appearance = System.Windows.Forms.Appearance.Button; this.parallelButton.Location = new System.Drawing.Point(6, 17); this.parallelButton.Name = "parallelButton"; this.parallelButton.Size = new System.Drawing.Size(94, 22); this.parallelButton.TabIndex = 0; this.parallelButton.Text = "Parallel"; this.parallelButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.parallelButton.Click += new System.EventHandler(this.parallelButton_Click); // // groupBox4 // this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox4.Controls.Add(this.rotateButton); this.groupBox4.Controls.Add(this.panButton); this.groupBox4.Controls.Add(this.zoomButton); this.groupBox4.Location = new System.Drawing.Point(440, 99); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(298, 45); this.groupBox4.TabIndex = 4; this.groupBox4.TabStop = false; this.groupBox4.Text = "ZPR"; // // rotateButton // this.rotateButton.Appearance = System.Windows.Forms.Appearance.Button; this.rotateButton.Location = new System.Drawing.Point(198, 17); this.rotateButton.Name = "rotateButton"; this.rotateButton.Size = new System.Drawing.Size(94, 22); this.rotateButton.TabIndex = 2; this.rotateButton.Text = "Rotate"; this.rotateButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.rotateButton.Click += new System.EventHandler(this.rotateButton_Click); // // panButton // this.panButton.Appearance = System.Windows.Forms.Appearance.Button; this.panButton.Location = new System.Drawing.Point(102, 17); this.panButton.Name = "panButton"; this.panButton.Size = new System.Drawing.Size(94, 22); this.panButton.TabIndex = 1; this.panButton.Text = "Pan"; this.panButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.panButton.Click += new System.EventHandler(this.panButton_Click); // // zoomButton // this.zoomButton.Appearance = System.Windows.Forms.Appearance.Button; this.zoomButton.Location = new System.Drawing.Point(6, 17); this.zoomButton.Name = "zoomButton"; this.zoomButton.Size = new System.Drawing.Size(94, 22); this.zoomButton.TabIndex = 0; this.zoomButton.Text = "Zoom"; this.zoomButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.zoomButton.Click += new System.EventHandler(this.zoomButton_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mainStatusLabel, this.springToolStripStatusLabel, this.loadingProgressBar, this.selectedCountStatusLabel, this.openglVersionStatusLabel, this.fpsStatusLabel, this.oglfVersionStatusLabel}); this.statusStrip1.Location = new System.Drawing.Point(0, 673); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.ShowItemToolTips = true; this.statusStrip1.Size = new System.Drawing.Size(744, 23); this.statusStrip1.TabIndex = 52; this.statusStrip1.Text = "statusStrip1"; // // mainStatusLabel // this.mainStatusLabel.Name = "mainStatusLabel"; this.mainStatusLabel.Size = new System.Drawing.Size(496, 18); this.mainStatusLabel.Text = "Middle Mouse Button = Rotate, Ctrl + Middle = Pan, Shift + Middle = Zoom, Mouse W" + "heel = Zoom +/-"; // // springToolStripStatusLabel // this.springToolStripStatusLabel.Name = "springToolStripStatusLabel"; this.springToolStripStatusLabel.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.springToolStripStatusLabel.Size = new System.Drawing.Size(95, 18); this.springToolStripStatusLabel.Spring = true; // // loadingProgressBar // this.loadingProgressBar.Name = "loadingProgressBar"; this.loadingProgressBar.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.loadingProgressBar.Size = new System.Drawing.Size(105, 17); this.loadingProgressBar.Visible = false; // // selectedCountStatusLabel // this.selectedCountStatusLabel.AutoSize = false; this.selectedCountStatusLabel.AutoToolTip = true; this.selectedCountStatusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.selectedCountStatusLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.selectedCountStatusLabel.Margin = new System.Windows.Forms.Padding(0, 3, 5, 2); this.selectedCountStatusLabel.Name = "selectedCountStatusLabel"; this.selectedCountStatusLabel.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.selectedCountStatusLabel.Size = new System.Drawing.Size(64, 18); this.selectedCountStatusLabel.Text = "0"; this.selectedCountStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.selectedCountStatusLabel.ToolTipText = "Selected count"; // // openglVersionStatusLabel // this.openglVersionStatusLabel.AutoSize = false; this.openglVersionStatusLabel.AutoToolTip = true; this.openglVersionStatusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.openglVersionStatusLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.openglVersionStatusLabel.Margin = new System.Windows.Forms.Padding(0, 3, 5, 2); this.openglVersionStatusLabel.Name = "openglVersionStatusLabel"; this.openglVersionStatusLabel.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.openglVersionStatusLabel.Size = new System.Drawing.Size(64, 18); this.openglVersionStatusLabel.Text = "toolStripStatusLabel2"; this.openglVersionStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.openglVersionStatusLabel.ToolTipText = "OpenGL version"; // // fpsStatusLabel // this.fpsStatusLabel.AutoSize = false; this.fpsStatusLabel.AutoToolTip = true; this.fpsStatusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.fpsStatusLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.fpsStatusLabel.Margin = new System.Windows.Forms.Padding(0, 3, 5, 2); this.fpsStatusLabel.Name = "fpsStatusLabel"; this.fpsStatusLabel.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.fpsStatusLabel.Size = new System.Drawing.Size(64, 18); this.fpsStatusLabel.Text = "toolStripStatusLabel1"; this.fpsStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.fpsStatusLabel.ToolTipText = "Frames per second"; // // oglfVersionStatusLabel // this.oglfVersionStatusLabel.AutoSize = false; this.oglfVersionStatusLabel.AutoToolTip = true; this.oglfVersionStatusLabel.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.oglfVersionStatusLabel.Margin = new System.Windows.Forms.Padding(0, 3, 5, 2); this.oglfVersionStatusLabel.Name = "oglfVersionStatusLabel"; this.oglfVersionStatusLabel.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0); this.oglfVersionStatusLabel.Size = new System.Drawing.Size(64, 13); this.oglfVersionStatusLabel.Text = "toolStripStatusLabel1"; this.oglfVersionStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.oglfVersionStatusLabel.ToolTipText = "C# OpenGL Framework version"; // // groupBox6 // this.groupBox6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox6.Controls.Add(this.wireframeButton); this.groupBox6.Controls.Add(this.edgesButton); this.groupBox6.Controls.Add(this.shadedButton); this.groupBox6.Location = new System.Drawing.Point(440, 7); this.groupBox6.Name = "groupBox6"; this.groupBox6.Size = new System.Drawing.Size(298, 45); this.groupBox6.TabIndex = 2; this.groupBox6.TabStop = false; this.groupBox6.Text = "Shading"; // // wireframeButton // this.wireframeButton.Appearance = System.Windows.Forms.Appearance.Button; this.wireframeButton.Location = new System.Drawing.Point(6, 17); this.wireframeButton.Name = "wireframeButton"; this.wireframeButton.Size = new System.Drawing.Size(94, 22); this.wireframeButton.TabIndex = 0; this.wireframeButton.Text = "Wireframe"; this.wireframeButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.wireframeButton.Click += new System.EventHandler(this.wireframeButton_Click); // // edgesButton // this.edgesButton.Appearance = System.Windows.Forms.Appearance.Button; this.edgesButton.Location = new System.Drawing.Point(198, 17); this.edgesButton.Name = "edgesButton"; this.edgesButton.Size = new System.Drawing.Size(94, 22); this.edgesButton.TabIndex = 2; this.edgesButton.Text = "Shaded && Edges"; this.edgesButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.edgesButton.Click += new System.EventHandler(this.edgesButton_Click); // // shadedButton // this.shadedButton.Appearance = System.Windows.Forms.Appearance.Button; this.shadedButton.Location = new System.Drawing.Point(102, 17); this.shadedButton.Name = "shadedButton"; this.shadedButton.Size = new System.Drawing.Size(94, 22); this.shadedButton.TabIndex = 1; this.shadedButton.Text = "Shaded"; this.shadedButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.shadedButton.Click += new System.EventHandler(this.shadedButton_Click); // // groupBox9 // this.groupBox9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox9.Controls.Add(this.showLabelsButton); this.groupBox9.Controls.Add(this.showOriginButton); this.groupBox9.Controls.Add(this.showBoundingBoxButton); this.groupBox9.Location = new System.Drawing.Point(440, 145); this.groupBox9.Name = "groupBox9"; this.groupBox9.Size = new System.Drawing.Size(298, 45); this.groupBox9.TabIndex = 5; this.groupBox9.TabStop = false; this.groupBox9.Text = "Hide/Show"; // // showLabelsButton // this.showLabelsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.showLabelsButton.Appearance = System.Windows.Forms.Appearance.Button; this.showLabelsButton.Location = new System.Drawing.Point(199, 17); this.showLabelsButton.Name = "showLabelsButton"; this.showLabelsButton.Size = new System.Drawing.Size(94, 22); this.showLabelsButton.TabIndex = 2; this.showLabelsButton.Text = "Labels"; this.showLabelsButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.showLabelsButton.CheckedChanged += new System.EventHandler(this.showLabelsButton_CheckedChanged); // // showOriginButton // this.showOriginButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.showOriginButton.Appearance = System.Windows.Forms.Appearance.Button; this.showOriginButton.Location = new System.Drawing.Point(7, 17); this.showOriginButton.Name = "showOriginButton"; this.showOriginButton.Size = new System.Drawing.Size(94, 22); this.showOriginButton.TabIndex = 0; this.showOriginButton.Text = "Origin"; this.showOriginButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.showOriginButton.CheckedChanged += new System.EventHandler(this.showOriginButton_CheckedChanged); // // showBoundingBoxButton // this.showBoundingBoxButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.showBoundingBoxButton.Appearance = System.Windows.Forms.Appearance.Button; this.showBoundingBoxButton.Location = new System.Drawing.Point(103, 17); this.showBoundingBoxButton.Name = "showBoundingBoxButton"; this.showBoundingBoxButton.Size = new System.Drawing.Size(94, 22); this.showBoundingBoxButton.TabIndex = 1; this.showBoundingBoxButton.Text = "Extent Box"; this.showBoundingBoxButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.showBoundingBoxButton.CheckedChanged += new System.EventHandler(this.showBoundingBoxButton_CheckedChanged); // // backgroundWorker1 // this.backgroundWorker1.WorkerReportsProgress = true; this.backgroundWorker1.WorkerSupportsCancellation = true; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.oddB); this.groupBox1.Controls.Add(this.oddG); this.groupBox1.Controls.Add(this.oddR); this.groupBox1.Controls.Add(this.label9); this.groupBox1.Controls.Add(this.label10); this.groupBox1.Controls.Add(this.label11); this.groupBox1.Controls.Add(this.label12); this.groupBox1.Controls.Add(this.evenB); this.groupBox1.Controls.Add(this.evenG); this.groupBox1.Controls.Add(this.evenR); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.sideLength); this.groupBox1.Controls.Add(this.cornerY); this.groupBox1.Controls.Add(this.cornerX); this.groupBox1.Location = new System.Drawing.Point(483, 246); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(209, 330); this.groupBox1.TabIndex = 53; this.groupBox1.TabStop = false; this.groupBox1.Text = "Settings"; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // // oddB // this.oddB.DecimalPlaces = 2; this.oddB.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.oddB.Location = new System.Drawing.Point(64, 299); this.oddB.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.oddB.Name = "oddB"; this.oddB.Size = new System.Drawing.Size(93, 21); this.oddB.TabIndex = 26; this.oddB.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.oddB.Value = new decimal(new int[] { 1, 0, 0, 0}); this.oddB.ValueChanged += new System.EventHandler(this.oddB_ValueChanged); // // oddG // this.oddG.DecimalPlaces = 2; this.oddG.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.oddG.Location = new System.Drawing.Point(64, 273); this.oddG.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.oddG.Name = "oddG"; this.oddG.Size = new System.Drawing.Size(93, 21); this.oddG.TabIndex = 25; this.oddG.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.oddG.Value = new decimal(new int[] { 1, 0, 0, 0}); this.oddG.ValueChanged += new System.EventHandler(this.oddG_ValueChanged); // // oddR // this.oddR.DecimalPlaces = 2; this.oddR.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.oddR.Location = new System.Drawing.Point(64, 247); this.oddR.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.oddR.Name = "oddR"; this.oddR.Size = new System.Drawing.Size(93, 21); this.oddR.TabIndex = 24; this.oddR.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.oddR.Value = new decimal(new int[] { 1, 0, 0, 0}); this.oddR.ValueChanged += new System.EventHandler(this.oddR_ValueChanged); // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(45, 301); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(13, 13); this.label9.TabIndex = 23; this.label9.Text = "B"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(44, 275); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(14, 13); this.label10.TabIndex = 22; this.label10.Text = "G"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(44, 249); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(14, 13); this.label11.TabIndex = 21; this.label11.Text = "R"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(18, 236); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(31, 13); this.label12.TabIndex = 20; this.label12.Text = "Odd:"; // // evenB // this.evenB.DecimalPlaces = 2; this.evenB.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.evenB.Location = new System.Drawing.Point(64, 207); this.evenB.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.evenB.Name = "evenB"; this.evenB.Size = new System.Drawing.Size(93, 21); this.evenB.TabIndex = 19; this.evenB.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.evenB.ValueChanged += new System.EventHandler(this.evenB_ValueChanged); // // evenG // this.evenG.DecimalPlaces = 2; this.evenG.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.evenG.Location = new System.Drawing.Point(64, 181); this.evenG.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.evenG.Name = "evenG"; this.evenG.Size = new System.Drawing.Size(93, 21); this.evenG.TabIndex = 18; this.evenG.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.evenG.ValueChanged += new System.EventHandler(this.evenG_ValueChanged); // // evenR // this.evenR.DecimalPlaces = 2; this.evenR.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.evenR.Location = new System.Drawing.Point(64, 155); this.evenR.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.evenR.Name = "evenR"; this.evenR.Size = new System.Drawing.Size(93, 21); this.evenR.TabIndex = 17; this.evenR.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.evenR.ValueChanged += new System.EventHandler(this.evenR_ValueChanged); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(45, 209); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(13, 13); this.label8.TabIndex = 13; this.label8.Text = "B"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(44, 183); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(14, 13); this.label7.TabIndex = 12; this.label7.Text = "G"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(44, 157); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(14, 13); this.label6.TabIndex = 11; this.label6.Text = "R"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(18, 144); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(35, 13); this.label5.TabIndex = 10; this.label5.Text = "Even:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(84, 132); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(37, 13); this.label4.TabIndex = 9; this.label4.Text = "Colors"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(18, 73); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 13); this.label3.TabIndex = 8; this.label3.Text = "Side Length:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(18, 46); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 13); this.label2.TabIndex = 7; this.label2.Text = "Corner (y):"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(18, 17); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(61, 13); this.label1.TabIndex = 6; this.label1.Text = "Corner (x):"; // // sideLength // this.sideLength.Location = new System.Drawing.Point(102, 73); this.sideLength.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.sideLength.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.sideLength.Name = "sideLength"; this.sideLength.Size = new System.Drawing.Size(93, 21); this.sideLength.TabIndex = 5; this.sideLength.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.sideLength.Value = new decimal(new int[] { 325, 0, 0, 0}); this.sideLength.ValueChanged += new System.EventHandler(this.sideLength_ValueChanged); // // cornerY // this.cornerY.Location = new System.Drawing.Point(102, 46); this.cornerY.Name = "cornerY"; this.cornerY.Size = new System.Drawing.Size(93, 21); this.cornerY.TabIndex = 4; this.cornerY.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.cornerY.ValueChanged += new System.EventHandler(this.cornerY_ValueChanged); // // cornerX // this.cornerX.Location = new System.Drawing.Point(102, 17); this.cornerX.Name = "cornerX"; this.cornerX.Size = new System.Drawing.Size(93, 21); this.cornerX.TabIndex = 3; this.cornerX.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.cornerX.ValueChanged += new System.EventHandler(this.cornerX_ValueChanged); // // openGLControl1 // this.openGLControl1.AmbientLight = new float[] { 0.1F, 0.1F, 0.1F, 1F}; this.openGLControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.openGLControl1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.openGLControl1.BackFaceCulling = true; this.openGLControl1.BackgroundMode = openglFramework.OpenGLControl.backgroundType.Bitmap; this.openGLControl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.openGLControl1.CornerX = 0F; this.openGLControl1.CornerY = 0F; this.openGLControl1.EdgeWeight = 2F; this.openGLControl1.EvenB = 0F; this.openGLControl1.EvenG = 0F; this.openGLControl1.EvenR = 0F; this.openGLControl1.FieldOfView = 50F; this.openGLControl1.ForeColor = System.Drawing.SystemColors.ControlText; this.openGLControl1.Location = new System.Drawing.Point(8, 9); this.openGLControl1.MainLightDiffuse = new float[] { 0.75F, 0.75F, 0.75F, 1F}; this.openGLControl1.Name = "openGLControl1"; this.openGLControl1.OddB = 1F; this.openGLControl1.OddG = 1F; this.openGLControl1.OddR = 1F; this.openGLControl1.PanButtonDown = false; this.openGLControl1.PointSize = 4F; this.openGLControl1.ProjectionMode = openglFramework.OpenGLControl.projectionType.Parallel; this.openGLControl1.RotateButtonDown = false; this.openGLControl1.ShadingMode = openglFramework.OpenGLControl.shadingType.ShadedAndEdges; this.openGLControl1.ShadowMode = openglFramework.OpenGLControl.shadowType.Transparent; this.openGLControl1.ShowBoundingBox = true; this.openGLControl1.ShowLabels = true; this.openGLControl1.ShowLegend = true; this.openGLControl1.ShowOrigin = true; this.openGLControl1.ShowProgress = true; this.openGLControl1.ShowUCSIcon = true; this.openGLControl1.SideLength = 400F; this.openGLControl1.SideLightDiffuse = new float[] { 0.2F, 0.2F, 0.2F, 1F}; this.openGLControl1.Size = new System.Drawing.Size(426, 654); this.openGLControl1.TabIndex = 1; this.openGLControl1.WireframeWeight = 1.5F; this.openGLControl1.ZoomButtonDown = false; this.openGLControl1.ZoomWindowButtonDown = false; this.openGLControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.openGLControl1_Paint); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(744, 696); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox9); this.Controls.Add(this.groupBox6); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox2); this.Controls.Add(this.openGLControl1); this.Controls.Add(this.statusStrip1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultBounds; this.Text = "Shyam Guthikonda - Wallpaper Algorithm"; this.Load += new System.EventHandler(this.MainForm_Load); this.groupBox2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.fieldOfView)).EndInit(); this.groupBox4.ResumeLayout(false); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.groupBox6.ResumeLayout(false); this.groupBox9.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.oddB)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.oddG)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.oddR)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.evenB)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.evenG)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.evenR)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.sideLength)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.cornerY)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.cornerX)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel mainStatusLabel; private System.Windows.Forms.NumericUpDown fieldOfView; /*private*/ private System.Windows.Forms.GroupBox groupBox6; private System.Windows.Forms.ToolStripStatusLabel openglVersionStatusLabel; private System.Windows.Forms.ToolStripStatusLabel fpsStatusLabel; private System.Windows.Forms.ToolStripStatusLabel springToolStripStatusLabel; /*private*/ public System.Windows.Forms.ToolStripStatusLabel selectedCountStatusLabel; private System.Windows.Forms.GroupBox groupBox9; private ToggleButton perspectiveButton; private ToggleButton parallelButton; private ToggleButton rotateButton; private ToggleButton panButton; private ToggleButton zoomButton; private ToggleButton wireframeButton; private ToggleButton edgesButton; private ToggleButton shadedButton; private ToggleButton showLabelsButton; private ToggleButton showOriginButton; private ToggleButton showBoundingBoxButton; private OpenGLControl openGLControl1; private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.Windows.Forms.ToolStripProgressBar loadingProgressBar; private System.Windows.Forms.ToolStripStatusLabel oglfVersionStatusLabel; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown sideLength; private System.Windows.Forms.NumericUpDown cornerY; private System.Windows.Forms.NumericUpDown cornerX; private System.Windows.Forms.NumericUpDown evenR; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown evenB; private System.Windows.Forms.NumericUpDown evenG; private System.Windows.Forms.NumericUpDown oddB; private System.Windows.Forms.NumericUpDown oddG; private System.Windows.Forms.NumericUpDown oddR; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; } }