context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class ManagedLocationOperationsExtensions { /// <summary> /// Create / Update the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// The location update result. /// </returns> public static ManagedLocationCreateOrUpdateResult CreateOrUpdate(this IManagedLocationOperations operations, ManagedLocationCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedLocationOperations)s).CreateOrUpdateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create / Update the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// The location update result. /// </returns> public static Task<ManagedLocationCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedLocationOperations operations, ManagedLocationCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(parameters, CancellationToken.None); } /// <summary> /// Delete a location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='locationName'> /// Required. Name of location to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IManagedLocationOperations operations, string locationName) { return Task.Factory.StartNew((object s) => { return ((IManagedLocationOperations)s).DeleteAsync(locationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='locationName'> /// Required. Name of location to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IManagedLocationOperations operations, string locationName) { return operations.DeleteAsync(locationName, CancellationToken.None); } /// <summary> /// Get the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='locationName'> /// Required. The location name. /// </param> /// <returns> /// Location get result. /// </returns> public static ManagedLocationGetResult Get(this IManagedLocationOperations operations, string locationName) { return Task.Factory.StartNew((object s) => { return ((IManagedLocationOperations)s).GetAsync(locationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='locationName'> /// Required. The location name. /// </param> /// <returns> /// Location get result. /// </returns> public static Task<ManagedLocationGetResult> GetAsync(this IManagedLocationOperations operations, string locationName) { return operations.GetAsync(locationName, CancellationToken.None); } /// <summary> /// Get locations under subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <returns> /// The location list result. /// </returns> public static ManagedLocationListResult List(this IManagedLocationOperations operations) { return Task.Factory.StartNew((object s) => { return ((IManagedLocationOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get locations under subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <returns> /// The location list result. /// </returns> public static Task<ManagedLocationListResult> ListAsync(this IManagedLocationOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Get locations with the next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// The location list result. /// </returns> public static ManagedLocationListResult ListNext(this IManagedLocationOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IManagedLocationOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get locations with the next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedLocationOperations. /// </param> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// The location list result. /// </returns> public static Task<ManagedLocationListResult> ListNextAsync(this IManagedLocationOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using SafeCurlHandle = Interop.libcurl.SafeCurlHandle; using CURLoption = Interop.libcurl.CURLoption; using CURLcode = Interop.libcurl.CURLcode; using CURLINFO = Interop.libcurl.CURLINFO; using CURLProxyType = Interop.libcurl.curl_proxytype; namespace System.Net.Http { internal class CurlHandler : HttpMessageHandler { #region Constants private const string UriSchemeHttps = "https"; private readonly static string[] AuthenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes #endregion #region Fields private volatile bool _anyOperationStarted; private volatile bool _disposed; private bool _automaticRedirection = true; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; #endregion internal CurlHandler() { } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); if (value) { _proxyPolicy = ProxyUsePolicy.UseCustomProxy; } else { _proxyPolicy = ProxyUsePolicy.DoNotUseProxy; } } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { CheckDisposedOrStarted(); _serverCredentials = value; } } #endregion protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { throw NotImplemented.ByDesignWithMessage("HTTPS stack is not yet implemented"); } if (request.Content != null) { throw NotImplemented.ByDesignWithMessage("HTTP requests with a body are not yet supported"); } CheckDisposed(); SetOperationStarted(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create RequestCompletionSource object and save current values of handler settings. RequestCompletionSource state = new RequestCompletionSource(); state.CancellationToken = cancellationToken; state.RequestMessage = request; state.Handler = this; Task.Factory.StartNew( s => { var rcs = (RequestCompletionSource)s; rcs.Handler.StartRequest(rcs); }, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return state.Task; } #region Private methods private void StartRequest(RequestCompletionSource state) { HttpResponseMessage responseMessage = null; SafeCurlHandle requestHandle = null; if (state.CancellationToken.IsCancellationRequested) { state.TrySetCanceled(); return; } var cancellationTokenRegistration = state.CancellationToken.Register(x => ((RequestCompletionSource) x).TrySetCanceled(), state); try { requestHandle = CreateRequestHandle(state); state.CancellationToken.ThrowIfCancellationRequested(); int result = Interop.libcurl.curl_easy_perform(requestHandle); if (CURLcode.CURLE_OK != result) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } // TODO: Handle requests with body state.CancellationToken.ThrowIfCancellationRequested(); responseMessage = CreateResponseMessage(requestHandle, state.RequestMessage); state.TrySetResult(responseMessage); } catch (Exception ex) { HandleAsyncException(state, ex); } finally { SafeCurlHandle.DisposeAndClearHandle(ref requestHandle); cancellationTokenRegistration.Dispose(); } } private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private SafeCurlHandle CreateRequestHandle(RequestCompletionSource state) { // TODO: If this impacts perf, optimize using a handle pool SafeCurlHandle requestHandle = Interop.libcurl.curl_easy_init(); if (requestHandle.IsInvalid) { throw new HttpRequestException(SR.net_http_client_execution_error); } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_URL, state.RequestMessage.RequestUri.OriginalString); if (_automaticRedirection) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_FOLLOWLOCATION, 1); } SetProxyOptions(state, requestHandle); // TODO: Handle headers and other options return requestHandle; } private static void SetProxyOptions(RequestCompletionSource state, SafeCurlHandle requestHandle) { var requestUri = state.RequestMessage.RequestUri; Debug.Assert(state.Handler != null); if (state.Handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } if ((state.Handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) || (state.Handler.Proxy == null)) { return; } Debug.Assert( (state.Handler.Proxy != null) && (state.Handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy)); if (state.Handler.Proxy.IsBypassed(requestUri)) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } var proxyUri = state.Handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { return; } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP); Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri); Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); NetworkCredential credentials = GetCredentials(state.Handler.Proxy.Credentials, requestUri); if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } string credentialText; if (string.IsNullOrEmpty(credentials.Domain)) { credentialText = string.Format("{0}:{1}", credentials.UserName, credentials.Password); } else { credentialText = string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain); } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } private static NetworkCredential GetCredentials(ICredentials proxyCredentials, Uri requestUri) { if (proxyCredentials == null) { return null; } foreach (var authScheme in AuthenticationSchemes) { NetworkCredential proxyCreds = proxyCredentials.GetCredential(requestUri, authScheme); if (proxyCreds != null) { return proxyCreds; } } return null; } private HttpResponseMessage CreateResponseMessage(SafeCurlHandle requestHandle, HttpRequestMessage request) { var response = new HttpResponseMessage(); long httpStatusCode = 0; int result = Interop.libcurl.curl_easy_getinfo(requestHandle, CURLINFO.CURLINFO_RESPONSE_CODE, ref httpStatusCode); if (CURLcode.CURLE_OK != result) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } response.StatusCode = (HttpStatusCode)httpStatusCode; // TODO: Do error processing if needed and return actual response response.Content = new StringContent("SendAsync to " + request.RequestUri.OriginalString + " returned: " + response.StatusCode); return response; } private void HandleAsyncException(RequestCompletionSource state, Exception ex) { if (ex is OperationCanceledException) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. Debug.Assert(state.CancellationToken.IsCancellationRequested); state.TrySetCanceled(); } else if (ex is HttpRequestException) { state.TrySetException(ex); } else { state.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private string GetCurlErrorString(int code) { IntPtr ptr = Interop.libcurl.curl_easy_strerror(code); return Marshal.PtrToStringAnsi(ptr); } private Exception GetCurlException(int code) { return new Exception(GetCurlErrorString(code)); } #endregion private sealed class RequestCompletionSource : TaskCompletionSource<HttpResponseMessage> { public CancellationToken CancellationToken { get; set; } public HttpRequestMessage RequestMessage { get; set; } public CurlHandler Handler { get; set; } } private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapResponse.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Asn1; using Novell.Directory.Ldap.Rfc2251; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> A message received from an LdapServer /// in response to an asynchronous request. /// /// </summary> /// <seealso cref="LdapConnection.Search"> /// </seealso> /* * Note: Exceptions generated by the reader thread are returned * to the application as an exception in an LdapResponse. Thus * if <code>exception</code> has a value, it is not a server response, * but instad an exception returned to the application from the API. */ public class LdapResponse:LdapMessage { /// <summary> Returns any error message in the response. /// /// </summary> /// <returns> Any error message in the response. /// </returns> virtual public System.String ErrorMessage { get { if (exception != null) { return exception.LdapErrorMessage; } /* RfcResponse resp=(RfcResponse)( message.Response); if(resp == null) Console.WriteLine(" Response is null"); else Console.WriteLine(" Response is non null"); string str=resp.getErrorMessage().stringValue(); if( str==null) Console.WriteLine("str is null.."); Console.WriteLine(" Response is non null" + str); return str; */ return ((RfcResponse) message.Response).getErrorMessage().stringValue(); } } /// <summary> Returns the partially matched DN field from the server response, /// if the response contains one. /// /// </summary> /// <returns> The partially matched DN field, if the response contains one. /// /// </returns> virtual public System.String MatchedDN { get { if (exception != null) { return exception.MatchedDN; } return ((RfcResponse) message.Response).getMatchedDN().stringValue(); } } /// <summary> Returns all referrals in a server response, if the response contains any. /// /// </summary> /// <returns> All the referrals in the server response. /// </returns> virtual public System.String[] Referrals { get { System.String[] referrals = null; RfcReferral ref_Renamed = ((RfcResponse) message.Response).getReferral(); if (ref_Renamed == null) { referrals = new System.String[0]; } else { // convert RFC 2251 Referral to String[] int size = ref_Renamed.size(); referrals = new System.String[size]; for (int i = 0; i < size; i++) { System.String aRef = ((Asn1OctetString) ref_Renamed.get_Renamed(i)).stringValue(); try { // get the referral URL LdapUrl urlRef = new LdapUrl(aRef); if ((System.Object) urlRef.getDN() == null) { RfcLdapMessage origMsg = base.Asn1Object.RequestingMessage.Asn1Object; System.String dn; if ((System.Object) (dn = origMsg.RequestDN) != null) { urlRef.setDN(dn); aRef = urlRef.ToString(); } } } catch (System.UriFormatException mex) { ; } finally { referrals[i] = aRef; } } } return referrals; } } /// <summary> Returns the result code in a server response. /// /// For a list of result codes, see the LdapException class. /// /// </summary> /// <returns> The result code. /// </returns> virtual public int ResultCode { get { if (exception != null) { return exception.ResultCode; } return ((RfcResponse) message.Response).getResultCode().intValue(); } } /// <summary> Checks the resultCode and generates the appropriate exception or /// null if success. /// </summary> virtual internal LdapException ResultException { /* package */ get { LdapException ex = null; switch (ResultCode) { case LdapException.SUCCESS: case LdapException.COMPARE_TRUE: case LdapException.COMPARE_FALSE: break; case LdapException.REFERRAL: System.String[] refs = Referrals; ex = new LdapReferralException("Automatic referral following not enabled", LdapException.REFERRAL, ErrorMessage); ((LdapReferralException) ex).setReferrals(refs); break; default: ex = new LdapException(LdapException.resultCodeToString(ResultCode), ResultCode, ErrorMessage, MatchedDN); // ex = new LdapException("49", 49, "hello error", "hi error.."); break; } return ex; } } /// <summary> Returns any controls in the message. /// /// </summary> /// <seealso cref="Novell.Directory.Ldap.LdapMessage.Controls"> /// </seealso> override public LdapControl[] Controls { get { if (exception != null) { return null; } return base.Controls; } } /// <summary> Returns the message ID. /// /// </summary> /// <seealso cref="Novell.Directory.Ldap.LdapMessage.MessageID"> /// </seealso> override public int MessageID { get { if (exception != null) { return exception.MessageID; } return base.MessageID; } } /// <summary> Returns the Ldap operation type of the message. /// /// </summary> /// <returns> The operation type of the message. /// /// </returns> /// <seealso cref="Novell.Directory.Ldap.LdapMessage.Type"> /// </seealso> override public int Type { get { if (exception != null) { return exception.ReplyType; } return base.Type; } } /// <summary> Returns an embedded exception response /// /// </summary> /// <returns> an embedded exception if any /// </returns> virtual internal LdapException Exception { /*package*/ get { return exception; } } /// <summary> Indicates the referral instance being followed if the /// connection created to follow referrals. /// /// </summary> /// <returns> the referral being followed /// </returns> virtual internal ReferralInfo ActiveReferral { /*package*/ get { return activeReferral; } } private InterThreadException exception = null; private ReferralInfo activeReferral; /// <summary> Creates an LdapResponse using an LdapException. /// Used to wake up the user following an abandon. /// Note: The abandon doesn't have to be user initiated /// but may be the result of error conditions. /// /// Referral information is available if this connection created solely /// to follow a referral. /// /// </summary> /// <param name="ex"> The exception /// /// </param> /// <param name="activeReferral"> The referral actually used to create the /// connection /// </param> public LdapResponse(InterThreadException ex, ReferralInfo activeReferral) { exception = ex; this.activeReferral = activeReferral; return ; } /// <summary> Creates a response LdapMessage when receiving an asynchronous /// response from a server. /// /// </summary> /// <param name="message"> The RfcLdapMessage from a server. /// </param> /*package*/ internal LdapResponse(RfcLdapMessage message):base(message) { return ; } /// <summary> Creates a SUCCESS response LdapMessage. Typically the response /// comes from a source other than a BER encoded Ldap message, /// such as from DSML. Other values which are allowed in a response /// are set to their empty values. /// /// </summary> /// <param name="type"> The message type as defined in LdapMessage. /// /// </param> /// <seealso cref="LdapMessage"> /// </seealso> public LdapResponse(int type):this(type, LdapException.SUCCESS, null, null, null, null) { return ; } /// <summary> Creates a response LdapMessage from parameters. Typically the data /// comes from a source other than a BER encoded Ldap message, /// such as from DSML. /// /// </summary> /// <param name="type"> The message type as defined in LdapMessage. /// /// </param> /// <param name="resultCode"> The result code as defined in LdapException. /// /// </param> /// <param name="matchedDN"> The name of the lowest entry that was matched /// for some error result codes, an empty string /// or <code>null</code> if none. /// /// </param> /// <param name="serverMessage"> A diagnostic message returned by the server, /// an empty string or <code>null</code> if none. /// /// </param> /// <param name="referrals"> The referral URLs returned for a REFERRAL result /// code or <code>null</code> if none. /// /// </param> /// <param name="controls"> Any controls returned by the server or /// <code>null</code> if none. /// /// </param> /// <seealso cref="LdapMessage"> /// </seealso> /// <seealso cref="LdapException"> /// </seealso> public LdapResponse(int type, int resultCode, System.String matchedDN, System.String serverMessage, System.String[] referrals, LdapControl[] controls):base(new RfcLdapMessage(RfcResultFactory(type, resultCode, matchedDN, serverMessage, referrals))) { return ; } private static Asn1Sequence RfcResultFactory(int type, int resultCode, System.String matchedDN, System.String serverMessage, System.String[] referrals) { Asn1Sequence ret; if ((System.Object) matchedDN == null) matchedDN = ""; if ((System.Object) serverMessage == null) serverMessage = ""; switch (type) { case SEARCH_RESULT: ret = new RfcSearchResultDone(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case BIND_RESPONSE: ret = null; // Not yet implemented break; case SEARCH_RESPONSE: ret = null; // Not yet implemented break; case MODIFY_RESPONSE: ret = new RfcModifyResponse(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case ADD_RESPONSE: ret = new RfcAddResponse(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case DEL_RESPONSE: ret = new RfcDelResponse(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case MODIFY_RDN_RESPONSE: ret = new RfcModifyDNResponse(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case COMPARE_RESPONSE: ret = new RfcCompareResponse(new Asn1Enumerated(resultCode), new RfcLdapDN(matchedDN), new RfcLdapString(serverMessage), null); break; case SEARCH_RESULT_REFERENCE: ret = null; // Not yet implemented break; case EXTENDED_RESPONSE: ret = null; // Not yet implemented break; default: throw new System.SystemException("Type " + type + " Not Supported"); } return ret; } /// <summary> Checks the resultCode and throws the appropriate exception. /// /// </summary> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> /* package */ internal virtual void chkResultCode() { if (exception != null) { throw exception; } else { LdapException ex = ResultException; if (ex != null) { throw ex; } return ; } } /* Methods from LdapMessage */ /// <summary> Indicates if this response is an embedded exception response /// /// </summary> /// <returns> true if contains an embedded Ldapexception /// </returns> /*package*/ internal virtual bool hasException() { return (exception != null); } } }
#pragma warning disable 1591 using System; using System.IO; using System.IO.Compression; using System.Net; using System.Xml; using System.Text; using Braintree.Exceptions; namespace Braintree { public class BraintreeService { public string ApiVersion = "4"; protected Configuration Configuration; public Environment Environment { get { return Configuration.Environment; } } public string MerchantId { get { return Configuration.MerchantId; } } public string PublicKey { get { return Configuration.PublicKey; } } public string PrivateKey { get { return Configuration.PrivateKey; } } public string ClientId { get { return Configuration.ClientId; } } public string ClientSecret { get { return Configuration.ClientSecret; } } public BraintreeService(Configuration configuration) { this.Configuration = configuration; } public XmlNode Get(string URL) { return GetXmlResponse(URL, "GET", null); } internal void Delete(string URL) { GetXmlResponse(URL, "DELETE", null); } public XmlNode Post(string URL, Request requestBody) { return GetXmlResponse(URL, "POST", requestBody); } internal XmlNode Post(string URL) { return GetXmlResponse(URL, "POST", null); } public XmlNode Put(string URL) { return Put(URL, null); } internal XmlNode Put(string URL, Request requestBody) { return GetXmlResponse(URL, "PUT", requestBody); } private XmlNode GetXmlResponse(string URL, string method, Request requestBody) { try { var request = WebRequest.Create(Environment.GatewayURL + URL) as HttpWebRequest; request.Headers.Add("Authorization", GetAuthorizationHeader()); request.Headers.Add("X-ApiVersion", ApiVersion); request.Headers.Add("Accept-Encoding", "gzip"); request.Accept = "application/xml"; request.UserAgent = "Braintree .NET " + typeof(BraintreeService).Assembly.GetName().Version.ToString(); request.Method = method; request.KeepAlive = false; request.Timeout = 60000; request.ReadWriteTimeout = 60000; if (requestBody != null) { var xmlPrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; byte[] buffer = Encoding.UTF8.GetBytes(xmlPrefix + requestBody.ToXml()); request.ContentType = "application/xml"; request.ContentLength = buffer.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(buffer, 0, buffer.Length); requestStream.Close(); } var response = request.GetResponse() as HttpWebResponse; XmlNode doc = ParseResponseStream(GetResponseStream(response)); response.Close(); return doc; } catch (WebException e) { var response = (HttpWebResponse)e.Response; if (response == null) throw e; if (response.StatusCode == (HttpStatusCode)422) // UnprocessableEntity { XmlNode doc = ParseResponseStream(GetResponseStream((HttpWebResponse) e.Response)); e.Response.Close(); return doc; } ThrowExceptionIfErrorStatusCode(response.StatusCode, null); throw e; } } private Stream GetResponseStream(HttpWebResponse response) { var stream = response.GetResponseStream(); if (response.ContentEncoding.Equals("gzip", StringComparison.CurrentCultureIgnoreCase)) { stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); } return stream; } private XmlNode ParseResponseStream(Stream stream) { var body = new StreamReader(stream).ReadToEnd(); return StringToXmlNode(body); } internal XmlNode StringToXmlNode(string xml) { if (xml.Trim() == "") { return new XmlDocument(); } else { var doc = new XmlDocument(); doc.LoadXml(xml); if (doc.ChildNodes.Count == 1) return doc.ChildNodes[0]; return doc.ChildNodes[1]; } } public string BaseMerchantURL() { return Environment.GatewayURL + MerchantPath(); } public string MerchantPath() { return "/merchants/" + MerchantId; } public string GetAuthorizationHeader() { string credentials; if (Configuration.IsAccessToken) { return "Bearer " + Configuration.AccessToken; } else { if (Configuration.IsClientCredentials) { credentials = ClientId + ":" + ClientSecret; } else { credentials = PublicKey + ":" + PrivateKey; } return "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(credentials)).Trim(); } } public static void ThrowExceptionIfErrorStatusCode(HttpStatusCode httpStatusCode, string message) { if (httpStatusCode != HttpStatusCode.OK && httpStatusCode != HttpStatusCode.Created) { switch (httpStatusCode) { case HttpStatusCode.Unauthorized: throw new AuthenticationException(); case HttpStatusCode.Forbidden: throw new AuthorizationException(message); case HttpStatusCode.NotFound: throw new NotFoundException(); case HttpStatusCode.InternalServerError: throw new ServerException(); case HttpStatusCode.ServiceUnavailable: throw new DownForMaintenanceException(); case (HttpStatusCode) 426: throw new UpgradeRequiredException(); default: var exception = new UnexpectedException(); exception.Source = "Unexpected HTTP_RESPONSE " + httpStatusCode; throw exception; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // namespace System.Reflection.Emit { using System; using IList = System.Collections.IList; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; using System.IO; using System.Runtime.Versioning; using System.Diagnostics.SymbolStore; using System.Diagnostics.Contracts; // This is a package private class. This class hold all of the managed // data member for AssemblyBuilder. Note that what ever data members added to // this class cannot be accessed from the EE. internal class AssemblyBuilderData { internal AssemblyBuilderData( InternalAssemblyBuilder assembly, String strAssemblyName, AssemblyBuilderAccess access, String dir) { m_assembly = assembly; m_strAssemblyName = strAssemblyName; m_access = access; m_moduleBuilderList = new List<ModuleBuilder>(); m_resWriterList = new List<ResWriterData>(); //Init to null/0 done for you by the CLR. FXCop has spoken if (dir == null && access != AssemblyBuilderAccess.Run) m_strDir = Environment.CurrentDirectory; else m_strDir = dir; m_peFileKind = PEFileKinds.Dll; } // Helper to add a dynamic module into the tracking list internal void AddModule(ModuleBuilder dynModule) { m_moduleBuilderList.Add(dynModule); } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(CustomAttributeBuilder customBuilder) { // make sure we have room for this CA if (m_CABuilders == null) { m_CABuilders = new CustomAttributeBuilder[m_iInitialSize]; } if (m_iCABuilder == m_CABuilders.Length) { CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2]; Array.Copy(m_CABuilders, 0, tempCABuilders, 0, m_iCABuilder); m_CABuilders = tempCABuilders; } m_CABuilders[m_iCABuilder] = customBuilder; m_iCABuilder++; } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { // make sure we have room for this CA if (m_CABytes == null) { m_CABytes = new byte[m_iInitialSize][]; m_CACons = new ConstructorInfo[m_iInitialSize]; } if (m_iCAs == m_CABytes.Length) { // enlarge the arrays byte[][] temp = new byte[m_iCAs * 2][]; ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2]; for (int i = 0; i < m_iCAs; i++) { temp[i] = m_CABytes[i]; tempCon[i] = m_CACons[i]; } m_CABytes = temp; m_CACons = tempCon; } byte[] attrs = new byte[binaryAttribute.Length]; Buffer.BlockCopy(binaryAttribute, 0, attrs, 0, binaryAttribute.Length); m_CABytes[m_iCAs] = attrs; m_CACons[m_iCAs] = con; m_iCAs++; } // Helper to ensure the type name is unique underneath assemblyBuilder internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType) { BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )"); for (int i = 0; i < m_moduleBuilderList.Count; i++) { ModuleBuilder curModule = m_moduleBuilderList[i]; curModule.CheckTypeNameConflict(strTypeName, enclosingType); } // Right now dynamic modules can only be added to dynamic assemblies in which // all modules are dynamic. Otherwise we would also need to check loaded types. // We only need to make this test for non-nested types since any // duplicates in nested types will be caught at the top level. // if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null) // { // // Cannot have two types with the same name // throw new ArgumentException(SR.Argument_DuplicateTypeName); // } } internal List<ModuleBuilder> m_moduleBuilderList; internal List<ResWriterData> m_resWriterList; internal String m_strAssemblyName; internal AssemblyBuilderAccess m_access; private InternalAssemblyBuilder m_assembly; internal Type[] m_publicComTypeList; internal int m_iPublicComTypeCount; internal bool m_isSaved; internal const int m_iInitialSize = 16; internal String m_strDir; // hard coding the assembly def token internal const int m_tkAssembly = 0x20000001; // tracking AssemblyDef's CAs for persistence to disk internal CustomAttributeBuilder[] m_CABuilders; internal int m_iCABuilder; internal byte[][] m_CABytes; internal ConstructorInfo[] m_CACons; internal int m_iCAs; internal PEFileKinds m_peFileKind; // assembly file kind internal MethodInfo m_entryPointMethod; internal Assembly m_ISymWrapperAssembly; // For unmanaged resources internal String m_strResourceFileName; internal byte[] m_resourceBytes; internal NativeVersionInfo m_nativeVersion; internal bool m_hasUnmanagedVersionInfo; internal bool m_OverrideUnmanagedVersionInfo; } /********************************************** * * Internal structure to track the list of ResourceWriter for * AssemblyBuilder & ModuleBuilder. * **********************************************/ internal class ResWriterData { internal String m_strName; internal String m_strFileName; internal String m_strFullFileName; internal Stream m_memoryStream; internal ResWriterData m_nextResWriter; internal ResourceAttributes m_attribute; } internal class NativeVersionInfo { internal NativeVersionInfo() { m_strDescription = null; m_strCompany = null; m_strTitle = null; m_strCopyright = null; m_strTrademark = null; m_strProduct = null; m_strProductVersion = null; m_strFileVersion = null; m_lcid = -1; } internal String m_strDescription; internal String m_strCompany; internal String m_strTitle; internal String m_strCopyright; internal String m_strTrademark; internal String m_strProduct; internal String m_strProductVersion; internal String m_strFileVersion; internal int m_lcid; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiBook.ProcessingArchitecture.ProcessesApi.v2.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
//============================================================================== // TorqueLab -> Default Containers Profiles // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== //============================================================================== // GuiButtonCtrl Profiles //============================================================================== singleton SFXProfile(SFX_TLab_ButtonUp) { filename = "tlab/art/sound/button_up.ogg"; description = AudioGui; preload = true; }; singleton SFXProfile(SFX_TLab_ButtonDown) { filename = "tlab/art/sound/button_down.ogg"; description = AudioGui; preload = true; }; //============================================================================== //ToolsButtonProfile Style //------------------------------------------------------------------------------ singleton GuiControlProfile( ToolsButtonProfile : ToolsDefaultProfile ) { fontSize = "16"; fontType = "Calibri"; fontColor = "254 254 254 255"; justify = "center"; category = "ToolsButtons"; opaque = "1"; border = "-2"; fontColors[0] = "254 254 254 255"; fontColors[2] = "200 200 200 255"; fontColorNA = "200 200 200 255"; bitmap = "tlab/themes/Laborean/buttons-assets/GuiButtonProfile.png"; hasBitmapArray = "1"; fixedExtent = "0"; bevelColorLL = "255 0 255 255"; textOffset = "0 -1"; autoSizeWidth = "1"; autoSizeHeight = "1"; borderThickness = "0"; fontColors[9] = "Fuchsia"; fontColors[6] = "Fuchsia"; fontColors[4] = "255 0 255 255"; fontColorLink = "255 0 255 255"; fontColors[3] = "255 255 255 255"; fontColorSEL = "255 255 255 255"; fontColors[7] = "Magenta"; soundButtonDown = SFX_TLab_ButtonDown; soundButtonUp = SFX_TLab_ButtonUp; tab = "1"; }; //------------------------------------------------------------------------------ singleton GuiControlProfile(ToolsButtonProfile_S1 : ToolsButtonProfile) { fontSize = "14"; justify = "Top"; textOffset = "0 0"; }; singleton GuiControlProfile(ToolsButtonProfile_L : ToolsButtonProfile) { justify = "left"; }; //============================================================================== //ToolsButtonAlt Style - Inverted Color Style //------------------------------------------------------------------------------ singleton GuiControlProfile(ToolsButtonAlt : ToolsButtonProfile) { bitmap = "tlab/themes/Laborean/buttons-assets/GuiButtonAlt.png"; }; //------------------------------------------------------------------------------ //============================================================================== //ToolsButtonStyle - Various fancier styles //------------------------------------------------------------------------------ singleton GuiControlProfile(ToolsButtonStyleA : ToolsButtonProfile) { bitmap = "tlab/themes/Laborean/buttons-assets/GuiButtonStyleA.png"; border = "0"; }; //============================================================================== //ToolsButtonHighlight Style - Special style for highlighting stuff //------------------------------------------------------------------------------ singleton GuiControlProfile( ToolsButtonArray : ToolsButtonProfile) { fillColor = "225 243 252 255"; fillColorHL = "225 243 252 0"; fillColorNA = "225 243 252 0"; fillColorSEL = "225 243 252 0"; //tab = true; //canKeyFocus = true; fontSize = "14"; fontColor = "250 250 247 255"; fontColorSEL = "43 107 206"; fontColorHL = "244 244 244"; fontColorNA = "100 100 100"; border = "-2"; borderColor = "153 222 253 255"; borderColorHL = "156 156 156"; borderColorNA = "153 222 253 0"; //bevelColorHL = "255 255 255"; //bevelColorLL = "0 0 0"; fontColors[1] = "244 244 244 255"; fontColors[2] = "100 100 100 255"; fontColors[3] = "43 107 206 255"; fontColors[9] = "255 0 255 255"; fontColors[0] = "250 250 247 255"; modal = 1; bitmap = "tlab/themes/Laborean/buttons-assets/GuiButtonArray.png"; }; //------------------------------------------------------------------------------ //============================================================================== // GuiCheckboxCtrl Profiles //============================================================================== //============================================================================== //ToolsCheckBoxProfile Style //------------------------------------------------------------------------------ singleton GuiControlProfile( ToolsCheckBoxProfile : ToolsDefaultProfile ) { opaque = false; fillColor = "232 232 232"; border = false; borderColor = "100 100 100"; fontSize = "15"; fontColor = "234 234 234 255"; fontColorHL = "80 80 80"; fontColorNA = "200 200 200"; fixedExtent = 1; justify = "left"; bitmap = "tlab/themes/Laborean/buttons-assets/GuiCheckboxProfile.png"; hasBitmapArray = true; category = "Tools"; fontColors[0] = "234 234 234 255"; fontColors[1] = "80 80 80 255"; fontColors[2] = "200 200 200 255"; fontColors[4] = "Fuchsia"; fontColorLink = "Fuchsia"; textOffset = "0 -3"; fontColors[6] = "Fuchsia"; }; //============================================================================== //ToolsCheckBoxAlt Style //------------------------------------------------------------------------------ singleton GuiControlProfile( ToolsCheckBoxAlt : ToolsCheckBoxProfile ) { opaque = false; fillColor = "232 232 232"; border = false; borderColor = "100 100 100"; fontSize = "15"; fontColor = "234 234 234 255"; fontColorHL = "80 80 80"; fontColorNA = "200 200 200"; fixedExtent = 1; justify = "left"; bitmap = "tlab/themes/Laborean/buttons-assets/GuiCheckboxAlt.png"; hasBitmapArray = true; category = "Tools"; fontColors[0] = "234 234 234 255"; fontColors[1] = "80 80 80 255"; fontColors[2] = "200 200 200 255"; fontColors[4] = "Fuchsia"; fontColorLink = "Fuchsia"; textOffset = "0 -3"; fontColors[6] = "Fuchsia"; }; //============================================================================== // GuiRadioCtrl Profiles //============================================================================== //============================================================================== //ToolsRadioProfile Style //------------------------------------------------------------------------------ singleton GuiControlProfile(ToolsRadioProfile : ToolsDefaultProfile) { fillColor = "254 253 253 255"; fillColorHL = "221 221 221 255"; fillColorNA = "200 200 200 255"; fontSize = "14"; textOffset = "-3 10"; bitmap = "tlab/themes/Laborean/buttons-assets/GuiRadioProfile.png"; hasBitmapArray = "1"; fontColors[0] = "250 250 250 255"; fontColor = "250 250 250 255"; border = "0"; fontColors[2] = "Black"; fontColorNA = "Black"; justify = "Left"; category = "Tools"; fontColors[8] = "Magenta"; fontColors[7] = "255 0 255 255"; autoSizeHeight = "1"; }; //============================================================================== // Swatch Button Profile -> Used in stock code (Do not remove) //============================================================================== //------------------------------------------------------------------------------ singleton GuiControlProfile(ToolsSwatchButtonProfile : ToolsDefaultProfile) { fillColor = "254 254 254 255"; fillColorHL = "221 221 221 255"; fillColorNA = "200 200 200 255"; fontSize = "24"; textOffset = "16 10"; bitmap = "tlab/themes/Laborean/element-assets/GuiButtonProfile.png"; hasBitmapArray = "0"; fontColors[0] = "253 253 253 255"; fontColor = "253 253 253 255"; border = "0"; fontColors[2] = "Black"; fontColorNA = "Black"; category = "Tools"; modal = "0"; opaque = "1"; fillColorSEL = "99 101 138 156"; borderColor = "100 100 100 255"; cursorColor = "0 0 0 79"; };
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Capabilities; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Client.Linden { public class LLStandaloneLoginModule : IRegionModule, ILoginServiceToRegionsConnector { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected List<Scene> m_scenes = new List<Scene>(); protected Scene m_firstScene; protected bool m_enabled = false; // Module is only enabled if running in standalone mode public bool RegionLoginsEnabled { get { if (m_firstScene != null) { return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; } else { return false; } } } protected LLStandaloneLoginService m_loginService; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource source) { if (m_firstScene == null) { m_firstScene = scene; IConfig startupConfig = source.Configs["Startup"]; if (startupConfig != null) { m_enabled = !startupConfig.GetBoolean("gridmode", false); } if (m_enabled) { bool authenticate = true; string welcomeMessage = "Welcome to InWorldz", mapServerURI = ""; IConfig standaloneConfig = source.Configs["StandAlone"]; if (standaloneConfig != null) { authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true); welcomeMessage = standaloneConfig.GetString("welcome_message"); mapServerURI = standaloneConfig.GetString("map_server_uri", ""); } //TODO: fix casting. LibraryRootFolder rootFolder = m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder; IHttpServer httpServer = m_firstScene.CommsManager.HttpServer; //TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference m_loginService = new LLStandaloneLoginService((UserManagerBase)m_firstScene.CommsManager.UserAdminService, mapServerURI, welcomeMessage, m_firstScene.CommsManager.NetworkServersInfo, authenticate, rootFolder, this); httpServer.AddXmlRPCHandler("login_to_simulator", m_loginService.XmlRpcLoginMethod); // New Style httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), m_loginService.XmlRpcLoginMethod)); // provides the web form login httpServer.AddHTTPHandler("login", m_loginService.ProcessHTMLLogin); } } if (m_enabled) { AddScene(scene); } } public void PostInitialise() { } public void Close() { } public string Name { get { return "LLStandaloneLoginModule"; } } public bool IsSharedModule { get { return true; } } #endregion protected void AddScene(Scene scene) { lock (m_scenes) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); } } } public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent, bool firstLogin, out string reason) { Scene scene; if (TryGetRegion(regionHandle, out scene)) { if (firstLogin) { return scene.NewUserLogin(agent, out reason); } else { return scene.NewUserConnection(agent, out reason); } } reason = "Region not found."; return false; } public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message) { Scene scene; if (TryGetRegion(regionHandle, out scene)) { scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message); } } public RegionInfo RequestNeighbourInfo(ulong regionhandle) { Scene scene; if (TryGetRegion(regionhandle, out scene)) { return scene.RegionInfo; } return null; } public RegionInfo RequestClosestRegion(string region) { Scene scene; if (TryGetRegion(region, out scene)) { return scene.RegionInfo; } return null; } public RegionInfo RequestNeighbourInfo(UUID regionID) { Scene scene; if (TryGetRegion(regionID, out scene)) { return scene.RegionInfo; } return null; } protected bool TryGetRegion(ulong regionHandle, out Scene scene) { lock (m_scenes) { foreach (Scene nextScene in m_scenes) { if (nextScene.RegionInfo.RegionHandle == regionHandle) { scene = nextScene; return true; } } } scene = null; return false; } protected bool TryGetRegion(UUID regionID, out Scene scene) { lock (m_scenes) { foreach (Scene nextScene in m_scenes) { if (nextScene.RegionInfo.RegionID == regionID) { scene = nextScene; return true; } } } scene = null; return false; } protected bool TryGetRegion(string regionName, out Scene scene) { lock (m_scenes) { foreach (Scene nextScene in m_scenes) { if (nextScene.RegionInfo.RegionName == regionName) { scene = nextScene; return true; } } } scene = null; return false; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Last Years GL Combined Financial Trans /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class GLCFPREV : EduHubEntity { #region Navigation Property Cache private GLPREV Cache_CODE_GLPREV; private KGST Cache_GST_TYPE_KGST; private KGLSUB Cache_SUBPROGRAM_KGLSUB; private KGLINIT Cache_INITIATIVE_KGLINIT; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Transaction ID (internal) /// </summary> public int TID { get; internal set; } /// <summary> /// General Ledger Code /// [Uppercase Alphanumeric (10)] /// </summary> public string CODE { get; internal set; } /// <summary> /// Optional Family Code /// [Uppercase Alphanumeric (10)] /// </summary> public string FAMILY { get; internal set; } /// <summary> /// Student key /// [Uppercase Alphanumeric (10)] /// </summary> public string TRSTUD { get; internal set; } /// <summary> /// Batch number /// </summary> public int? TRBATCH { get; internal set; } /// <summary> /// GX period number eg. 199208 /// </summary> public int? TRPERD { get; internal set; } /// <summary> /// Transaction type /// J - Journal /// R - Receipt /// P - Payment /// [Uppercase Alphanumeric (1)] /// </summary> public string TRTYPE { get; internal set; } /// <summary> /// Transaction quantity /// </summary> public int? TRQTY { get; internal set; } /// <summary> /// Transaction unit cost /// </summary> public decimal? TRCOST { get; internal set; } /// <summary> /// Transaction date /// </summary> public DateTime? TRDATE { get; internal set; } /// <summary> /// Transaction reference /// [Alphanumeric (10)] /// </summary> public string TRREF { get; internal set; } /// <summary> /// Transaction amount /// </summary> public decimal? TRAMT { get; internal set; } /// <summary> /// Transaction description /// [Alphanumeric (30)] /// </summary> public string TRDET { get; internal set; } /// <summary> /// Ledger type eg DF, IV, AR, CR, DM /// [Uppercase Alphanumeric (2)] /// </summary> public string TRXLEDGER { get; internal set; } /// <summary> /// receipt Option, Shortcut, ledger * for acquisitions of stock or assets /// [Uppercase Alphanumeric (2)] /// </summary> public string POST_OPTION { get; internal set; } /// <summary> /// Post code for through posting to subledgers /// [Uppercase Alphanumeric (10)] /// </summary> public string TRXCODE { get; internal set; } /// <summary> /// TRTYPE for through posting to subledgers /// [Uppercase Alphanumeric (1)] /// </summary> public string TRXTRTYPE { get; internal set; } /// <summary> /// DR/CR short/key /// [Uppercase Alphanumeric (10)] /// </summary> public string TRSHORT { get; internal set; } /// <summary> /// Not used in JX leave for /// compatibility /// Bank account for multiple bank /// accounts /// [Uppercase Alphanumeric (10)] /// </summary> public string TRBANK { get; internal set; } /// <summary> /// Bank reconciliation flag /// Y - reconciled /// N - not yet reconciled /// Not used for RX set leave for /// compatibility /// [Alphanumeric (1)] /// </summary> public string RECONCILE { get; internal set; } /// <summary> /// "Y" - print cheque /// [Alphanumeric (1)] /// </summary> public string PRINT_CHEQUE { get; internal set; } /// <summary> /// Cheque number /// [Alphanumeric (10)] /// </summary> public string CHEQUE_NO { get; internal set; } /// <summary> /// Payee for cheques /// [Alphanumeric (30)] /// </summary> public string PAYEE { get; internal set; } /// <summary> /// Payee address /// [Alphanumeric (30)] /// </summary> public string ADDRESS01 { get; internal set; } /// <summary> /// Payee address /// [Alphanumeric (30)] /// </summary> public string ADDRESS02 { get; internal set; } /// <summary> /// Creditor transaction's TID No /// </summary> public int? CHQ_TID { get; internal set; } /// <summary> /// where does this appear in the BAS /// [Uppercase Alphanumeric (3)] /// </summary> public string GST_BOX { get; internal set; } /// <summary> /// what Period was this Reported /// </summary> public int? GST_PERD { get; internal set; } /// <summary> /// GST Dollar amount for this /// transaction /// </summary> public decimal? GST_AMOUNT { get; internal set; } /// <summary> /// Added for software compatibilty /// See gl receipts /// </summary> public decimal? TRNETT { get; internal set; } /// <summary> /// Gross amount which includes GST /// </summary> public decimal? TRGROSS { get; internal set; } /// <summary> /// what rate was the GST apllied /// </summary> public double? GST_RATE { get; internal set; } /// <summary> /// What type of GST /// [Uppercase Alphanumeric (4)] /// </summary> public string GST_TYPE { get; internal set; } /// <summary> /// Is this being claimed /// [Uppercase Alphanumeric (1)] /// </summary> public string GST_RECLAIM { get; internal set; } /// <summary> /// S, PO, PC indicates type of /// purchase or sale /// [Uppercase Alphanumeric (2)] /// </summary> public string GST_SALE_PURCH { get; internal set; } /// <summary> /// Source tid from creditors or GL /// </summary> public int? SOURCE_TID { get; internal set; } /// <summary> /// Amount of Withholding TAX for this /// invoice line /// </summary> public decimal? WITHHOLD_AMOUNT { get; internal set; } /// <summary> /// Required for GL payments with /// withheld amounts /// [Uppercase Alphanumeric (4)] /// </summary> public string WITHHOLD_TYPE { get; internal set; } /// <summary> /// Withhold Rate /// </summary> public double? WITHHOLD_RATE { get; internal set; } /// <summary> /// Was this transaction retianed by /// the eoy /// [Uppercase Alphanumeric (1)] /// </summary> public string EOY_KEPT { get; internal set; } /// <summary> /// Bank client /// [Alphanumeric (20)] /// </summary> public string DRAWER { get; internal set; } /// <summary> /// Bank/State/Branch (Cheque) /// [Alphanumeric (6)] /// </summary> public string BSB { get; internal set; } /// <summary> /// Bank name /// [Alphanumeric (20)] /// </summary> public string BANK { get; internal set; } /// <summary> /// Branch location /// [Alphanumeric (20)] /// </summary> public string BRANCH { get; internal set; } /// <summary> /// Bank account number /// </summary> public int? ACCOUNT_NUMBER { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string RTYPE { get; internal set; } /// <summary> /// Appeal fund /// [Uppercase Alphanumeric (10)] /// </summary> public string APPEAL { get; internal set; } /// <summary> /// Event Key /// [Uppercase Alphanumeric (4)] /// </summary> public string EVENT { get; internal set; } /// <summary> /// Fundraising Receipt type /// G - Gift /// P - Pledge /// B - Bequest /// F - Function/Event /// [Uppercase Alphanumeric (1)] /// </summary> public string FRTYPE { get; internal set; } /// <summary> /// Y/N field used in creditors asset invoice /// [Uppercase Alphanumeric (1)] /// </summary> public string TINCLUDE { get; internal set; } /// <summary> /// Posting to TDep: Cost ex GST /// Also used for the cost base for depreciation /// </summary> public decimal? TTRNETT { get; internal set; } /// <summary> /// Tax value of Asset transaction /// </summary> public decimal? TTRAMT { get; internal set; } /// <summary> /// Amount of GST for tax transactions, Posted to tax ORIG_GST /// </summary> public decimal? TGST_AMOUNT { get; internal set; } /// <summary> /// Memo field for asset repairs /// [Memo] /// </summary> public string AMEMO { get; internal set; } /// <summary> /// Copy Amemo field to Asset? Y/N /// [Uppercase Alphanumeric (1)] /// </summary> public string AMEMO_COPY { get; internal set; } /// <summary> /// Date for next service for asset repairs /// </summary> public DateTime? NEXT_SVC_DATE { get; internal set; } /// <summary> /// Mandatory field /// </summary> public int? LINE_NO { get; internal set; } /// <summary> /// Mandatory field /// </summary> public int? FLAG { get; internal set; } /// <summary> /// Mandatory field /// </summary> public decimal? DEBIT_TOTAL { get; internal set; } /// <summary> /// Mandatory field /// </summary> public decimal? CREDIT_TOTAL { get; internal set; } /// <summary> /// For every transaction there is a subprogram /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// A subprogram always belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GLPROGRAM { get; internal set; } /// <summary> /// Transaction might belong to an Initiative /// [Uppercase Alphanumeric (3)] /// </summary> public string INITIATIVE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// GLPREV (Last Years General Ledger) related entity by [GLCFPREV.CODE]-&gt;[GLPREV.CODE] /// General Ledger Code /// </summary> public GLPREV CODE_GLPREV { get { if (Cache_CODE_GLPREV == null) { Cache_CODE_GLPREV = Context.GLPREV.FindByCODE(CODE); } return Cache_CODE_GLPREV; } } /// <summary> /// KGST (GST Percentages) related entity by [GLCFPREV.GST_TYPE]-&gt;[KGST.KGSTKEY] /// What type of GST /// </summary> public KGST GST_TYPE_KGST { get { if (GST_TYPE == null) { return null; } if (Cache_GST_TYPE_KGST == null) { Cache_GST_TYPE_KGST = Context.KGST.FindByKGSTKEY(GST_TYPE); } return Cache_GST_TYPE_KGST; } } /// <summary> /// KGLSUB (General Ledger Sub Programs) related entity by [GLCFPREV.SUBPROGRAM]-&gt;[KGLSUB.SUBPROGRAM] /// For every transaction there is a subprogram /// </summary> public KGLSUB SUBPROGRAM_KGLSUB { get { if (SUBPROGRAM == null) { return null; } if (Cache_SUBPROGRAM_KGLSUB == null) { Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM); } return Cache_SUBPROGRAM_KGLSUB; } } /// <summary> /// KGLINIT (General Ledger Initiatives) related entity by [GLCFPREV.INITIATIVE]-&gt;[KGLINIT.INITIATIVE] /// Transaction might belong to an Initiative /// </summary> public KGLINIT INITIATIVE_KGLINIT { get { if (INITIATIVE == null) { return null; } if (Cache_INITIATIVE_KGLINIT == null) { Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE); } return Cache_INITIATIVE_KGLINIT; } } #endregion } }
#region using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Graphics; using Android.Net; using Android.OS; using Android.Util; using Newtonsoft.Json; using Xamarin; using Xsseract.Droid.Extensions; using Environment = Android.OS.Environment; using File = Java.IO.File; using Path = System.IO.Path; using Uri = System.Uri; #endregion namespace Xsseract.Droid { // TODO: Detect version changes when initializing (store current version in the shared prefs). public class XsseractContext { #region Fields private readonly XsseractApp context; private Image image; private string installationId; private bool meteredConnectionAccessApproved = false; public Func<bool> MeteredConnectionPermissionCallback; private ISharedPreferences preferences; private AppSettings settings; private Tesseractor tesseractor; #endregion public AppContextState State { get; private set; } public string DeviceId => Android.Provider.Settings.Secure.AndroidId; public string DeviceName { get; private set; } public string InstallationId { get { EnsureAppContextInitialized(); return installationId; } } public bool IsFirstRun { get { #if DEBUG // ReSharper disable once ConvertPropertyToExpressionBody return false; #else return Preferences.GetBoolean(PreferencesKeys.IsFirstRun, true); #endif } } public ISharedPreferences Preferences { get { return preferences = preferences ?? context.GetSharedPreferences(preferencesFile, FileCreationMode.Private); } } public AppSettings Settings => settings ?? (settings = GetAppSettings()); public File PublicFilesPath => new File(Environment.ExternalStorageDirectory, Path.Combine("Xsseract", "files")); public File TessDataFilesPath => new File(PublicFilesPath, "tessdata"); public bool HasImage => image != null; public event EventHandler<EventArgs> FirstTimeInitialize; #region .ctors public XsseractContext(XsseractApp underlyingContext) { if (null == underlyingContext) { throw new ArgumentNullException(nameof(underlyingContext)); } context = underlyingContext; DeviceName = GetDeviceName(); } #endregion public void Initialize() { if (State != AppContextState.None) { return; } try { EnsureAppContextInitialized(); tesseractor = new Tesseractor(PublicFilesPath.AbsolutePath); tesseractor.DownloadingDataFiles += (sender, e) => FirstTimeInitialize?.Invoke(this, EventArgs.Empty); tesseractor.Initialize(this); State = AppContextState.Initialized; } catch(WebException e) { State = AppContextState.InitializationErrors; // TODO: To resources. throw new DataConnectionException("Could not connect to the server for the tess data files download.", e); } catch(Exception) { State = AppContextState.InitializationErrors; throw; } } public async Task<Tesseractor> GetTessInstanceAsync() { if (null != tesseractor) { await Task.Yield(); return tesseractor; } tesseractor = new Tesseractor(PublicFilesPath.AbsolutePath); var result = await tesseractor.InitializeAsync(this); if (!result) { throw new ApplicationException("Error initializing tesseract."); } return tesseractor; } public void LogEvent(AppTrackingEvents @event) { Insights.Track(@event.ToString()); } public void LogEvent(AppTrackingEvents @event, Dictionary<string, string> extraData) { Insights.Track(@event.ToString(), extraData); } public ITrackHandle LogTimedEvent(AppTrackingEvents @event) { return Insights.TrackTime(@event.ToString()); } public void MarkHelpScreenCompleted() { var trans = Preferences.Edit(); trans.PutBoolean(PreferencesKeys.IsFirstRun, false); trans.Commit(); } public void LogDebug(string message) { #if DEBUG Log.Debug(tag, message); #endif } public void LogDebug(string format, params object[] args) { #if DEBUG Log.Debug(tag, format, args); #endif } public void LogInfo(string message) { Log.Info(tag, message); } public void LogInfo(string format, params object[] args) { Log.Info(tag, format, args); } public void LogWarn(string message) { Log.Warn(tag, message); } public void LogWarn(string format, params object[] args) { Log.Warn(tag, format, args); } public void LogError(string message) { Log.Error(tag, message); Insights.Report(new ApplicationException(message), Insights.Severity.Warning); } public void LogError(Exception e) { if (null == e) { LogError("Unspecified exception occured."); return; } Log.Error(tag, e.ToString()); Insights.Report(e, Insights.Severity.Warning); } public async Task<Bitmap> LoadImageAsync(string path, float rotation) { await DisposeImageAsync(); var tmpImg = await Task.Factory.StartNew( () => { var img = new Image(path, rotation); return img; }); this.image = tmpImg; LogInfo("Image sampling is {0}", image.SampleSize); return image.Bitmap; } public Bitmap LoadImage(string path, float rotation) { image?.Dispose(); image = new Image(path, rotation); LogInfo("Image sampling is {0}", image.SampleSize); return image.Bitmap; } public async Task DisposeImageAsync() { if (null == image) { await Task.Yield(); return; } await Task.Factory.StartNew( () => { image.Dispose(); image = null; }); } public Bitmap GetBitmap() { return image?.Bitmap; } public string GetImageUri() { return image?.Path; } public bool IsDataConnectionAvailable() { ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService); return cm.ActiveNetworkInfo?.IsConnected == true; } public void AskForMeteredConnectionPermission() { ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService); if (!cm.IsActiveNetworkMetered) { return; } if (null == MeteredConnectionPermissionCallback) { // TODO: To resources. throw new DataConnectionException("A metered data connection is active. Xsseract needs to download some rather large files, come back when you've hit WiFi."); } if (meteredConnectionAccessApproved) { return; } meteredConnectionAccessApproved = MeteredConnectionPermissionCallback(); if (!MeteredConnectionPermissionCallback()) { // TODO: To resources. throw new DataConnectionException("User denied data usage over a metered connection."); } } public void IncrementSuccessCounter() { var trans = Preferences.Edit(); int val = Preferences.GetInt(PreferencesKeys.SuccessfullImages, 0); trans.PutInt(PreferencesKeys.SuccessfullImages, val + 1); trans.Commit(); } public void SetDontRateFlag() { var trans = Preferences.Edit(); trans.PutBoolean(PreferencesKeys.DontRate, true); trans.Commit(); } public bool ShouldAskForRating() { if (Preferences.GetBoolean(PreferencesKeys.DontRate, false) || 0 == Settings.SuccessCountForRatingPrompt) { return false; } var count = Preferences.GetInt(PreferencesKeys.SuccessfullImages, 0); return 0 != count && 0 == count % Settings.SuccessCountForRatingPrompt; } public Stream GetAssetStream(Uri assetUri) { Stream s = context.Assets.Open(Path.GetFileNameWithoutExtension(assetUri.GetFileName())); if (null == s) { // TODO: To resources. throw new ApplicationException($"The specified asset could not be identified (${assetUri})"); } return s; } /** Returns the consumer friendly device name */ public static String GetDeviceName() { String manufacturer = Build.Manufacturer; String model = Build.Model; if (model.StartsWith(manufacturer)) { return Capitalize(model); } if (0 == String.Compare(manufacturer, "HTC", StringComparison.OrdinalIgnoreCase)) { // make sure "HTC" is fully capitalized. return "HTC " + model; } return Capitalize(manufacturer) + " " + model; } #region Private Methods private static String Capitalize(String str) { if (String.IsNullOrWhiteSpace(str)) { return str; } var capitalizeNext = true; String phrase = ""; foreach(char c in str) { if (capitalizeNext && Char.IsLetter(c)) { phrase += Char.ToUpper(c); capitalizeNext = false; continue; } if (Char.IsWhiteSpace(c)) { capitalizeNext = true; } phrase += c; } return phrase; } private void CreateInstalationFile(File installation) { #if DEBUG // For insights reporting during debug. var iid = Guid.Empty; #else var iid = Guid.NewGuid(); #endif var details = new InstallationDetails { InstallationId = iid.ToString() }; var s = new JsonSerializer(); using(var sw = new StreamWriter(installation.AbsolutePath, false, Encoding.UTF8)) { s.Serialize(sw, details); } installationId = details.InstallationId; } private void EnsureAppContextInitialized() { if (State != AppContextState.None) { return; } State = AppContextState.Initializing; using(File f = new File(context.FilesDir, InstallationFile)) { if (!f.Exists()) { CreateInstalationFile(f); } else { ReadInstallationFile(f); } } Insights.Identify(installationId, "UserId", String.Empty); } private AppSettings GetAppSettings() { #if DEBUG string fileName = "Settings.DEBUG.json"; #else string fileName = "Settings.RELEASE.json"; #endif var serializer = new JsonSerializer(); using(var file = context.Assets.Open(fileName)) { using(var stream = new StreamReader(file)) { return (AppSettings)serializer.Deserialize(stream, typeof(AppSettings)); } } } private void ReadInstallationFile(File installation) { var s = new JsonSerializer(); InstallationDetails details; using(var sw = new StreamReader(installation.AbsolutePath, Encoding.UTF8)) { details = (InstallationDetails)s.Deserialize(sw, typeof(InstallationDetails)); } installationId = details.InstallationId; } #endregion #region Inner Classes/Enums private class InstallationDetails { public string InstallationId { get; set; } } private static class PreferencesKeys { public const string IsFirstRun = "IsFirstRun", SuccessfullImages = "SuccessfullImages", DontRate = "DontRate"; } public enum AppContextState { None, Initializing, Initialized, InitializationErrors } #endregion private const string tag = "Xsseract.App"; public const string InstallationFile = "INSTALLATION"; private const string preferencesFile = "Prefs"; } }
using System; using System.Text; namespace Org.BouncyCastle.Math.EC { internal class IntArray { // TODO make m fixed for the IntArray, and hence compute T once and for all // TODO Use uint's internally? private int[] _ints; public IntArray(int intLen) { _ints = new int[intLen]; } private IntArray(int[] ints) { _ints = ints; } public IntArray(IBigInteger bigInt) : this(bigInt, 0) { } public IntArray(IBigInteger bigInt, int minIntLen) { if (bigInt.SignValue == -1) throw new ArgumentException(@"Only positive Integers allowed", "bigInt"); if (bigInt.SignValue == 0) { _ints = new int[] { 0 }; return; } var barr = bigInt.ToByteArrayUnsigned(); var barrLen = barr.Length; var intLen = (barrLen + 3) / 4; _ints = new int[System.Math.Max(intLen, minIntLen)]; var rem = barrLen % 4; var barrI = 0; if (0 < rem) { var temp = (int) barr[barrI++]; while (barrI < rem) { temp = temp << 8 | (int) barr[barrI++]; } _ints[--intLen] = temp; } while (intLen > 0) { var temp = (int) barr[barrI++]; for (var i = 1; i < 4; i++) { temp = temp << 8 | (int) barr[barrI++]; } _ints[--intLen] = temp; } } public int GetUsedLength() { int highestIntPos = _ints.Length; if (highestIntPos < 1) return 0; // Check if first element will act as sentinel if (_ints[0] != 0) { while (_ints[--highestIntPos] == 0) { } return highestIntPos + 1; } do { if (_ints[--highestIntPos] != 0) { return highestIntPos + 1; } } while (highestIntPos > 0); return 0; } public int BitLength { get { // JDK 1.5: see Integer.numberOfLeadingZeros() int intLen = GetUsedLength(); if (intLen == 0) return 0; var last = intLen - 1; var highest = (uint) _ints[last]; var bits = (last << 5) + 1; // A couple of binary search steps if (highest > 0x0000ffff) { if (highest > 0x00ffffff) { bits += 24; highest >>= 24; } else { bits += 16; highest >>= 16; } } else if (highest > 0x000000ff) { bits += 8; highest >>= 8; } while (highest > 1) { ++bits; highest >>= 1; } return bits; } } private int[] ResizedInts(int newLen) { var newInts = new int[newLen]; var oldLen = _ints.Length; var copyLen = oldLen < newLen ? oldLen : newLen; Array.Copy(_ints, 0, newInts, 0, copyLen); return newInts; } public IBigInteger ToBigInteger() { var usedLen = GetUsedLength(); if (usedLen == 0) { return BigInteger.Zero; } var highestInt = _ints[usedLen - 1]; var temp = new byte[4]; var barrI = 0; var trailingZeroBytesDone = false; for (var j = 3; j >= 0; j--) { var thisByte = (byte)((int)((uint) highestInt >> (8 * j))); if (!trailingZeroBytesDone && (thisByte == 0)) continue; trailingZeroBytesDone = true; temp[barrI++] = thisByte; } var barrLen = 4 * (usedLen - 1) + barrI; var barr = new byte[barrLen]; for (var j = 0; j < barrI; j++) { barr[j] = temp[j]; } // Highest value int is done now for (var iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--) { for (var j = 3; j >= 0; j--) { barr[barrI++] = (byte)((int)((uint)_ints[iarrJ] >> (8 * j))); } } return new BigInteger(1, barr); } public void ShiftLeft() { int usedLen = GetUsedLength(); if (usedLen == 0) { return; } if (_ints[usedLen - 1] < 0) { // highest bit of highest used byte is set, so shifting left will // make the IntArray one byte longer usedLen++; if (usedLen > _ints.Length) { // make the m_ints one byte longer, because we need one more // byte which is not available in m_ints _ints = ResizedInts(_ints.Length + 1); } } bool carry = false; for (int i = 0; i < usedLen; i++) { // nextCarry is true if highest bit is set bool nextCarry = _ints[i] < 0; _ints[i] <<= 1; if (carry) { // set lowest bit _ints[i] |= 1; } carry = nextCarry; } } public IntArray ShiftLeft(int n) { var usedLen = GetUsedLength(); if (usedLen == 0) { return this; } if (n == 0) { return this; } if (n > 31) { throw new ArgumentException("shiftLeft() for max 31 bits " + ", " + n + "bit shift is not possible", "n"); } var newInts = new int[usedLen + 1]; var nm32 = 32 - n; newInts[0] = _ints[0] << n; for (var i = 1; i < usedLen; i++) { newInts[i] = (_ints[i] << n) | (int)((uint)_ints[i - 1] >> nm32); } newInts[usedLen] = (int)((uint)_ints[usedLen - 1] >> nm32); return new IntArray(newInts); } public void AddShifted(IntArray other, int shift) { var usedLenOther = other.GetUsedLength(); var newMinUsedLen = usedLenOther + shift; if (newMinUsedLen > _ints.Length) { _ints = ResizedInts(newMinUsedLen); //Console.WriteLine("Resize required"); } for (var i = 0; i < usedLenOther; i++) { _ints[i + shift] ^= other._ints[i]; } } public int Length { get { return _ints.Length; } } public bool TestBit(int n) { // theInt = n / 32 var theInt = n >> 5; // theBit = n % 32 var theBit = n & 0x1F; var tester = 1 << theBit; return ((_ints[theInt] & tester) != 0); } public void FlipBit(int n) { // theInt = n / 32 var theInt = n >> 5; // theBit = n % 32 var theBit = n & 0x1F; var flipper = 1 << theBit; _ints[theInt] ^= flipper; } public void SetBit(int n) { // theInt = n / 32 var theInt = n >> 5; // theBit = n % 32 var theBit = n & 0x1F; var setter = 1 << theBit; _ints[theInt] |= setter; } public IntArray Multiply(IntArray other, int m) { // Lenght of c is 2m bits rounded up to the next int (32 bit) var t = (m + 31) >> 5; if (_ints.Length < t) { _ints = ResizedInts(t); } var b = new IntArray(other.ResizedInts(other.Length + 1)); var c = new IntArray((m + m + 31) >> 5); // IntArray c = new IntArray(t + t); int testBit = 1; for (int k = 0; k < 32; k++) { for (int j = 0; j < t; j++) { if ((_ints[j] & testBit) != 0) { // The kth bit of m_ints[j] is set c.AddShifted(b, j); } } testBit <<= 1; b.ShiftLeft(); } return c; } // public IntArray multiplyLeftToRight(IntArray other, int m) { // // Lenght of c is 2m bits rounded up to the next int (32 bit) // int t = (m + 31) / 32; // if (m_ints.Length < t) { // m_ints = resizedInts(t); // } // // IntArray b = new IntArray(other.resizedInts(other.getLength() + 1)); // IntArray c = new IntArray((m + m + 31) / 32); // // IntArray c = new IntArray(t + t); // int testBit = 1 << 31; // for (int k = 31; k >= 0; k--) { // for (int j = 0; j < t; j++) { // if ((m_ints[j] & testBit) != 0) { // // The kth bit of m_ints[j] is set // c.addShifted(b, j); // } // } // testBit >>>= 1; // if (k > 0) { // c.shiftLeft(); // } // } // return c; // } // TODO note, redPol.Length must be 3 for TPB and 5 for PPB public void Reduce(int m, int[] redPol) { for (var i = m + m - 2; i >= m; i--) { if (!TestBit(i)) continue; var bit = i - m; FlipBit(bit); FlipBit(i); var l = redPol.Length; while (--l >= 0) { FlipBit(redPol[l] + bit); } } _ints = ResizedInts((m + 31) >> 5); } public IntArray Square(int m) { // TODO make the table static readonly int[] table = { 0x0, 0x1, 0x4, 0x5, 0x10, 0x11, 0x14, 0x15, 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55 }; var t = (m + 31) >> 5; if (_ints.Length < t) { _ints = ResizedInts(t); } var c = new IntArray(t + t); // TODO twice the same code, put in separate private method for (var i = 0; i < t; i++) { var v0 = 0; for (var j = 0; j < 4; j++) { v0 = (int)((uint) v0 >> 8); var u = (int)((uint)_ints[i] >> (j * 4)) & 0xF; var w = table[u] << 24; v0 |= w; } c._ints[i + i] = v0; v0 = 0; var upper = (int)((uint) _ints[i] >> 16); for (var j = 0; j < 4; j++) { v0 = (int)((uint) v0 >> 8); var u = (int)((uint)upper >> (j * 4)) & 0xF; var w = table[u] << 24; v0 |= w; } c._ints[i + i + 1] = v0; } return c; } public override bool Equals(object o) { if (!(o is IntArray)) { return false; } var other = (IntArray) o; var usedLen = GetUsedLength(); if (other.GetUsedLength() != usedLen) { return false; } for (var i = 0; i < usedLen; i++) { if (_ints[i] != other._ints[i]) { return false; } } return true; } public override int GetHashCode() { var i = GetUsedLength(); var hc = i; while (--i >= 0) { hc *= 17; hc ^= _ints[i]; } return hc; } internal IntArray Copy() { return new IntArray((int[]) _ints.Clone()); } public override string ToString() { var usedLen = GetUsedLength(); if (usedLen == 0) { return "0"; } var sb = new StringBuilder(Convert.ToString(_ints[usedLen - 1], 2)); for (var iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--) { var hexString = Convert.ToString(_ints[iarrJ], 2); // Add leading zeroes, except for highest significant int for (var i = hexString.Length; i < 8; i++) { hexString = "0" + hexString; } sb.Append(hexString); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace EZOper.TechTester.EZWebTemplate.Areas.Help { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null)); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository("aName")); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository("aName") { Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>( () => client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName"))); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null)); } [Fact] public async Task UsesTheOrganizationsReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository("aName")); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<ApiValidationException>( () => client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("owner", "name"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name")); } [Fact] public async Task RequestsCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete(1); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Delete("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.Delete("owner", "")); } } public class TheGetMethod { [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Get("owner", "name"); connection.Received().Get<Repository>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/name"), null, "application/vnd.github.polaris-preview+json"); } [Fact] public async Task RequestsCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Get(1); connection.Received().Get<Repository>( Arg.Is<Uri>(u => u.ToString() == "repositories/1"), null, "application/vnd.github.polaris-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "")); } } public class TheGetAllPublicMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories")); } } public class TheGetAllPublicSinceMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(new PublicRepositoryRequest(364L)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364")); } [Fact] public async Task SendsTheCorrectParameter() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(new PublicRepositoryRequest(364L)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364")); } } public class TheGetAllForCurrentMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Args.ApiOptions); } [Fact] public async Task CanFilterByType() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.All }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "all"), Args.ApiOptions); } [Fact] public async Task CanFilterBySort() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Private, Sort = RepositorySort.FullName }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "private" && d["sort"] == "full_name"), Args.ApiOptions); } [Fact] public async Task CanFilterBySortDirection() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Member, Sort = RepositorySort.Updated, Direction = SortDirection.Ascending }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc"), Args.ApiOptions); } [Fact] public async Task CanFilterByVisibility() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Visibility = RepositoryVisibility.Private }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["visibility"] == "private"), Args.ApiOptions); } [Fact] public async Task CanFilterByAffiliation() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Affiliation = RepositoryAffiliation.Owner, Sort = RepositorySort.FullName }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["affiliation"] == "owner" && d["sort"] == "full_name"), Args.ApiOptions); } } public class TheGetAllForUserMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos"), Args.ApiOptions); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForUser("")); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser("user", null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForUser("", ApiOptions.None)); } } public class TheGetAllForOrgMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos"), Args.ApiOptions); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForOrg("")); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg("org", null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForOrg("", ApiOptions.None)); } } public class TheGetAllBranchesMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllBranches(1); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllBranches("owner", "name", options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllBranches(1, options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", "name", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "", ApiOptions.None)); } } public class TheGetAllContributorsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors("owner", "name"); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>(), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors(1); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Any<IDictionary<string, string>>(), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors("owner", "name", options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>(), options); } [Fact] public void RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; client.GetAllContributors(1, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Any<IDictionary<string, string>>(), options); } [Fact] public async Task RequestsTheCorrectUrlIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors("owner", "name", true); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors(1, true); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptionsIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors("owner", "name", true, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptionsIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors(1, true, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo", false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null, false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", "repo", false, null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(1, null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(1, false, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo", false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "", false, ApiOptions.None)); } } public class TheGetAllLanguagesMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages")); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages(1); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/languages")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTeams(1); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/teams"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTeams("owner", "name", options); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"), options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTeams(1, options); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/teams"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "", ApiOptions.None)); } } public class TheGetAllTagsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTags(1); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/tags"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTags("owner", "name", options); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"), options); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptionsWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTags(1, options); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/tags"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "", ApiOptions.None)); } } public class TheGetBranchMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetBranch(1, "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate("repo"); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>(), "application/vnd.github.polaris-preview+json"); } [Fact] public void PatchesCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate("repo"); client.Edit(1, update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories/1"), Arg.Any<RepositoryUpdate>(), "application/vnd.github.polaris-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head")); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch")); } } public class TheGetCommitMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Get("owner", "name", "reference"); connection.Received() .Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference")); } } public class TheGetAllCommitsMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null, ApiOptions.None)); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetAll("owner", "name"); connection.Received() .GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Args.EmptyDictionary, Args.ApiOptions); } } public class TheEditBranchMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch("owner", "repo", "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch(1, "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new BranchUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch(1, "", update)); } } public class TheGetSha1Method { [Fact] public void EnsuresNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("", "name", "reference")); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "", "reference")); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "name", "")); } [Fact] public async Task EnsuresNonEmptyArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1(null, "name", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", "name", null)); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetSha1("owner", "name", "reference"); connection.Received() .Get<string>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"), null, AcceptHeaders.CommitReferenceSha1Preview); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.HttpOverrides { public class HttpMethodOverrideMiddlewareTest { [Fact] public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(); app.Run(context => { assertsExecuted = true; Assert.Equal("DELETE", context.Request.Method); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Headers.Add("X-Http-Method-Override", "DELETE"); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } [Fact] public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(); app.Run(context => { Assert.Equal("POST", context.Request.Method); assertsExecuted = true; return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } [Fact] public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(); app.Run(context => { Assert.Equal("GET", context.Request.Method); assertsExecuted = true; return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } [Fact] public async Task FormFieldAvailableChangesRequestMethod() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(new HttpMethodOverrideOptions() { FormFieldName = "_METHOD" }); app.Run(context => { Assert.Equal("DELETE", context.Request.Method); assertsExecuted = true; return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary<string, string>() { { "_METHOD", "DELETE" } }); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } [Fact] public async Task FormFieldUnavailableDoesNotChangeRequestMethod() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(new HttpMethodOverrideOptions() { FormFieldName = "_METHOD" }); app.Run(context => { Assert.Equal("POST", context.Request.Method); assertsExecuted = true; return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary<string, string>() { }); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } [Fact] public async Task FormFieldEmptyDoesNotChangeRequestMethod() { var assertsExecuted = false; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseHttpMethodOverride(new HttpMethodOverrideOptions() { FormFieldName = "_METHOD" }); app.Run(context => { Assert.Equal("POST", context.Request.Method); assertsExecuted = true; return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary<string, string>() { { "_METHOD", "" } }); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; namespace System { // The class designed as to keep minimal the working set of Uri class. // The idea is to stay with static helper methods and strings internal static class IPv4AddressHelper { internal const long Invalid = -1; // Note: the native parser cannot handle MaxIPv4Value, only MaxIPv4Value - 1 private const long MaxIPv4Value = UInt32.MaxValue; private const int Octal = 8; private const int Decimal = 10; private const int Hex = 16; private const int NumberOfLabels = 4; // methods // Parse and canonicalize internal static string ParseCanonicalName(string str, int start, int end, ref bool isLoopback) { unsafe { byte* numbers = stackalloc byte[NumberOfLabels]; isLoopback = Parse(str, numbers, start, end); return numbers[0] + "." + numbers[1] + "." + numbers[2] + "." + numbers[3]; } } // Only called from the IPv6Helper, only parse the canonical format internal static int ParseHostNumber(string str, int start, int end) { unsafe { byte* numbers = stackalloc byte[NumberOfLabels]; ParseCanonical(str, numbers, start, end); return (numbers[0] << 24) + (numbers[1] << 16) + (numbers[2] << 8) + numbers[3]; } } // // IsValid // // Performs IsValid on a substring. Updates the index to where we // believe the IPv4 address ends // // Inputs: // <argument> name // string containing possible IPv4 address // // <argument> start // offset in <name> to start checking for IPv4 address // // <argument> end // offset in <name> of the last character we can touch in the check // // Outputs: // <argument> end // index of last character in <name> we checked // // <argument> allowIPv6 // enables parsing IPv4 addresses embedded in IPv6 address literals // // <argument> notImplicitFile // do not consider this URI holding an implicit filename // // <argument> unknownScheme // the check is made on an unknown scheme (suppress IPv4 canonicalization) // // Assumes: // The address string is terminated by either // end of the string, characters ':' '/' '\' '?' // // // Returns: // bool // // Throws: // Nothing // //Remark: MUST NOT be used unless all input indexes are are verified and trusted. internal unsafe static bool IsValid(char* name, int start, ref int end, bool allowIPv6, bool notImplicitFile, bool unknownScheme) { // IPv6 can only have canonical IPv4 embedded. Unknown schemes will not attempt parsing of non-canonical IPv4 addresses. if (allowIPv6 || unknownScheme) { return IsValidCanonical(name, start, ref end, allowIPv6, notImplicitFile); } else { return ParseNonCanonical(name, start, ref end, notImplicitFile) != Invalid; } } // // IsValidCanonical // // Checks if the substring is a valid canonical IPv4 address or an IPv4 address embedded in an IPv6 literal // This is an attempt to parse ABNF productions from RFC3986, Section 3.2.2: // IP-literal = "[" ( IPv6address / IPvFuture ) "]" // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet // dec-octet = DIGIT ; 0-9 // / %x31-39 DIGIT ; 10-99 // / "1" 2DIGIT ; 100-199 // / "2" %x30-34 DIGIT ; 200-249 // / "25" %x30-35 ; 250-255 // internal unsafe static bool IsValidCanonical(char* name, int start, ref int end, bool allowIPv6, bool notImplicitFile) { int dots = 0; int number = 0; bool haveNumber = false; bool firstCharIsZero = false; while (start < end) { char ch = name[start]; if (allowIPv6) { // for ipv4 inside ipv6 the terminator is either ScopeId, prefix or ipv6 terminator if (ch == ']' || ch == '/' || ch == '%') break; } else if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#'))) { break; } if (ch <= '9' && ch >= '0') { if (!haveNumber && (ch == '0')) { if ((start + 1 < end) && name[start + 1] == '0') { // 00 is not allowed as a prefix. return false; } firstCharIsZero = true; } haveNumber = true; number = number * 10 + (name[start] - '0'); if (number > 255) { return false; } } else if (ch == '.') { if (!haveNumber || (number > 0 && firstCharIsZero)) { // 0 is not allowed to prefix a number. return false; } ++dots; haveNumber = false; number = 0; firstCharIsZero = false; } else { return false; } ++start; } bool res = (dots == 3) && haveNumber; if (res) { end = start; } return res; } // Parse any canonical or noncanonical IPv4 formats and return a long between 0 and MaxIPv4Value. // Return Invalid (-1) for failures. // If the address has less than three dots, only the rightmost section is assumed to contain the combined value for // the missing sections: 0xFF00FFFF == 0xFF.0x00.0xFF.0xFF == 0xFF.0xFFFF internal unsafe static long ParseNonCanonical(char* name, int start, ref int end, bool notImplicitFile) { int numberBase = Decimal; char ch; long[] parts = new long[4]; long currentValue = 0; bool atLeastOneChar = false; // Parse one dotted section at a time int dotCount = 0; // Limit 3 int current = start; for (; current < end; current++) { ch = name[current]; currentValue = 0; // Figure out what base this section is in numberBase = Decimal; if (ch == '0') { numberBase = Octal; current++; atLeastOneChar = true; if (current < end) { ch = name[current]; if (ch == 'x' || ch == 'X') { numberBase = Hex; current++; atLeastOneChar = false; } } } // Parse this section for (; current < end; current++) { ch = name[current]; int digitValue; if ((numberBase == Decimal || numberBase == Hex) && '0' <= ch && ch <= '9') { digitValue = ch - '0'; } else if (numberBase == Octal && '0' <= ch && ch <= '7') { digitValue = ch - '0'; } else if (numberBase == Hex && 'a' <= ch && ch <= 'f') { digitValue = ch + 10 - 'a'; } else if (numberBase == Hex && 'A' <= ch && ch <= 'F') { digitValue = ch + 10 - 'A'; } else { break; // Invalid/terminator } currentValue = (currentValue * numberBase) + digitValue; if (currentValue > MaxIPv4Value) // Overflow { return Invalid; } atLeastOneChar = true; } if (current < end && name[current] == '.') { if (dotCount >= 3 // Max of 3 dots and 4 segments || !atLeastOneChar // No empty segmets: 1...1 // Only the last segment can be more than 255 (if there are less than 3 dots) || currentValue > 0xFF) { return Invalid; } parts[dotCount] = currentValue; dotCount++; atLeastOneChar = false; continue; } // We don't get here unless We find an invalid character or a terminator break; } // Terminators if (!atLeastOneChar) { return Invalid; // Empty trailing segment: 1.1.1. } else if (current >= end) { // end of string, allowed } else if ((ch = name[current]) == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#'))) { end = current; } else { // not a valid terminating character return Invalid; } parts[dotCount] = currentValue; // Parsed, reassemble and check for overflows switch (dotCount) { case 0: // 0xFFFFFFFF if (parts[0] > MaxIPv4Value) { return Invalid; } return parts[0]; case 1: // 0xFF.0xFFFFFF if (parts[1] > 0xffffff) { return Invalid; } return (parts[0] << 24) | (parts[1] & 0xffffff); case 2: // 0xFF.0xFF.0xFFFF if (parts[2] > 0xffff) { return Invalid; } return (parts[0] << 24) | ((parts[1] & 0xff) << 16) | (parts[2] & 0xffff); case 3: // 0xFF.0xFF.0xFF.0xFF if (parts[3] > 0xff) { return Invalid; } return (parts[0] << 24) | ((parts[1] & 0xff) << 16) | ((parts[2] & 0xff) << 8) | (parts[3] & 0xff); default: return Invalid; } } // // Parse // // Convert this IPv4 address into a sequence of 4 8-bit numbers // unsafe private static bool Parse(string name, byte* numbers, int start, int end) { fixed (char* ipString = name) { int changedEnd = end; long result = IPv4AddressHelper.ParseNonCanonical(ipString, start, ref changedEnd, true); // end includes ports, so changedEnd may be different from end Debug.Assert(result != Invalid, "Failed to parse after already validated: " + name); numbers[0] = (byte)(result >> 24); numbers[1] = (byte)(result >> 16); numbers[2] = (byte)(result >> 8); numbers[3] = (byte)(result); } return numbers[0] == 127; } // Assumes: // <Name> has been validated and contains only decimal digits in groups // of 8-bit numbers and the characters '.' // Address may terminate with ':' or with the end of the string // unsafe private static bool ParseCanonical(string name, byte* numbers, int start, int end) { for (int i = 0; i < NumberOfLabels; ++i) { byte b = 0; char ch; for (; (start < end) && (ch = name[start]) != '.' && ch != ':'; ++start) { b = (byte)(b * 10 + (byte)(ch - '0')); } numbers[i] = b; ++start; } return numbers[0] == 127; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Signum.Utilities; using Signum.Entities; using Signum.Utilities.Reflection; using Signum.Engine.Maps; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Reflection; using System.Reflection; namespace Signum.Engine.Linq { internal static class SmartEqualizer { public static ConstantExpression True = Expression.Constant(true); public static ConstantExpression False = Expression.Constant(false); static ConstantExpression NewId = Expression.Constant("NewID"); public static Expression EqualNullableGroupBy(Expression e1, Expression e2) { return Expression.Or(Expression.Equal(e1.Nullify(), e2.Nullify()), Expression.And(new IsNullExpression(e1), new IsNullExpression(e2))); } public static Expression EqualNullable(Expression e1, Expression e2) { if (e1 == NewId || e2 == NewId) return False; if (e1.Type.IsNullable() == e2.Type.IsNullable()) return Expression.Equal(e1, e2); return Expression.Equal(e1.Nullify(), e2.Nullify()); } public static Expression NotEqualNullable(Expression e1, Expression e2) { if (e1.Type.IsNullable() == e2.Type.IsNullable()) return Expression.NotEqual(e1, e2); return Expression.NotEqual(e1.Nullify(), e2.Nullify()); } public static Expression PolymorphicEqual(Expression exp1, Expression exp2) { if (exp1.NodeType == ExpressionType.New || exp2.NodeType == ExpressionType.New) { if (exp1.IsNull() || exp2.IsNull()) return Expression.Constant(false); exp1 = ConstanToNewExpression(exp1) ?? exp1; exp2 = ConstanToNewExpression(exp2) ?? exp2; return ((NewExpression)exp1).Arguments.ZipStrict( ((NewExpression)exp2).Arguments, (o, i) => SmartEqualizer.PolymorphicEqual(o, i)).AggregateAnd(); } Expression? result; result = PrimaryKeyEquals(exp1, exp2); if (result != null) return result; result = ObjectEquals(exp1, exp2); if (result != null) return result; result = ConditionalEquals(exp1, exp2); if (result != null) return result; result = CoalesceEquals(exp1, exp2); if (result != null) return result; result = LiteEquals(exp1, exp2); if (result != null) return result; result = EntityEquals(exp1, exp2); if (result != null) return result; result = TypeEquals(exp1, exp2); if (result != null) return result; result = MListElementEquals(exp1, exp2); if (result != null) return result; result = EnumEquals(exp1, exp2); if (result != null) return result; return EqualNullable(exp1, exp2); } private static Expression? EnumEquals(Expression exp1, Expression exp2) { bool anyEnum = false; var exp1Clean = RemoveConvertChain(exp1, ref anyEnum); var exp2Clean = RemoveConvertChain(exp2, ref anyEnum); if (exp1Clean.Type.UnNullify() == typeof(DayOfWeek) || exp2Clean.Type.UnNullify() == typeof(DayOfWeek)) { return SmartEqualizer.EqualNullable( ConstantToDayOfWeek(exp1Clean) ?? exp1Clean, ConstantToDayOfWeek(exp2Clean) ?? exp2Clean); } if (anyEnum) { var type = exp2.Type.IsNullable() ? exp1.Type.Nullify(): exp1.Type; return SmartEqualizer.EqualNullable(exp1Clean.TryConvert(type), exp2Clean.TryConvert(type)); } return null; } private static Expression? ConstantToDayOfWeek(Expression exp) { if (exp is ConstantExpression c) { if (c.Value == null) return Expression.Constant(null, typeof(DayOfWeek?)); return Expression.Constant((DayOfWeek)(int)c.Value, exp.Type.IsNullable() ? typeof(DayOfWeek?) : typeof(DayOfWeek)); } return null; } private static Expression RemoveConvertChain(Expression exp, ref bool anyEnum) { while (true) { var newExp = exp.TryRemoveConvert(t => t.UnNullify().IsEnum); if (newExp != null) anyEnum = true; else newExp = exp.TryRemoveConvert(t => ReflectionTools.IsIntegerNumber(t.UnNullify())); if (newExp == null) return exp; exp = newExp; } } private static Expression? ConstanToNewExpression(Expression exp) { var ce = exp as ConstantExpression; if (ce == null) return null; var type = ce.Value.GetType(); if (!type.IsAnonymous()) return null; var values = type.GetProperties().ToDictionary(a => a.Name, a => a.GetValue(ce.Value)); var ci = type.GetConstructors().SingleEx(); return Expression.New(ci, ci.GetParameters().Select(p => Expression.Constant(values.GetOrThrow(p.Name!), p.ParameterType))); } public static Expression? PrimaryKeyEquals(Expression exp1, Expression exp2) { if (exp1.Type.UnNullify() == typeof(PrimaryKey) || exp2.Type.UnNullify() == typeof(PrimaryKey)) { var left = UnwrapPrimaryKey(exp1); var right = UnwrapPrimaryKey(exp2); return EqualNullable(left.Nullify(), right.Nullify()); } return null; } public static Expression? ObjectEquals(Expression expr1, Expression expr2) { if (expr1.Type == typeof(object) && expr2.Type == typeof(object)) { var left = UncastObject(expr1); var right = UncastObject(expr2); if (left == null && right == null) return null; left = left ?? ChangeConstant(expr1, right!.Type); right = right ?? ChangeConstant(expr2, left!.Type); if (left == null || right == null) return null; return PolymorphicEqual(left, right); } return null; } private static Expression? ChangeConstant(Expression exp, Type type) { if (exp is ConstantExpression ce) { var val = ce.Value; if (val == null) { if (type.IsNullable() || !type.IsValueType) return Expression.Constant(val, type); else return null; } if (type.IsAssignableFrom(val.GetType())) return Expression.Constant(val, type); return null; } return null; } private static Expression? UncastObject(Expression expr) { if (expr.NodeType == ExpressionType.Convert) return ((UnaryExpression)expr).Operand; return null; } public static BinaryExpression UnwrapPrimaryKeyBinary(BinaryExpression b) { if (b.Left.Type.UnNullify() == typeof(PrimaryKey) || b.Right.Type.UnNullify() == typeof(PrimaryKey)) { var left = UnwrapPrimaryKey(b.Left); var right = UnwrapPrimaryKey(b.Right); if (left.Type.UnNullify() == typeof(Guid)) { return Expression.MakeBinary(b.NodeType, left.Nullify(), right.Nullify(), true, GuidComparer.GetMethod(b.NodeType)); } else { return Expression.MakeBinary(b.NodeType, left.Nullify(), right.Nullify()); } } return b; } static class GuidComparer { static bool GreaterThan(Guid a, Guid b) { return a.CompareTo(b) > 0; } static bool GreaterThanOrEqual(Guid a, Guid b) { return a.CompareTo(b) >= 0; } static bool LessThan(Guid a, Guid b) { return a.CompareTo(b) < 0; } static bool LessThanOrEqual(Guid a, Guid b) { return a.CompareTo(b) <= 0; } public static MethodInfo? GetMethod(ExpressionType type) { switch (type) { case ExpressionType.GreaterThan: return ReflectionTools.GetMethodInfo(() => GreaterThan(Guid.Empty, Guid.Empty)); case ExpressionType.GreaterThanOrEqual: return ReflectionTools.GetMethodInfo(() => GreaterThanOrEqual(Guid.Empty, Guid.Empty)); case ExpressionType.LessThan: return ReflectionTools.GetMethodInfo(() => LessThan(Guid.Empty, Guid.Empty)); case ExpressionType.LessThanOrEqual: return ReflectionTools.GetMethodInfo(() => LessThanOrEqual(Guid.Empty, Guid.Empty)); case ExpressionType.Equal: return null; case ExpressionType.NotEqual: return null; default: throw new InvalidOperationException("GuidComparer.GetMethod unexpected ExpressionType " + type); } } } public static Expression UnwrapPrimaryKey(Expression unary) { if (unary.NodeType == ExpressionType.Convert && unary.Type.UnNullify() == typeof(PrimaryKey)) return UnwrapPrimaryKey(((UnaryExpression)unary).Operand); if (unary is PrimaryKeyExpression pk) return pk.Value; if (unary is ConstantExpression ce) { var obj = ce.Value; if (obj == null) return Expression.Constant(null, unary.Type); return Expression.Constant(((PrimaryKey)obj).Object); } return unary; } private static Expression? ConditionalEquals(Expression exp1, Expression exp2) { if (Schema.Current.Settings.IsDbType(exp1.Type.UnNullify())|| Schema.Current.Settings.IsDbType(exp2.Type.UnNullify())) return null; if (exp1 is ConditionalExpression ce1) return DispachConditional(ce1, exp2); if (exp2 is ConditionalExpression ce2) return DispachConditional(ce2, exp1); return null; } private static Expression DispachConditional(ConditionalExpression ce, Expression exp) { var ifTrue = PolymorphicEqual(ce.IfTrue, exp); var ifFalse = PolymorphicEqual(ce.IfFalse, exp); return SmartOr(SmartAnd(ce.Test, ifTrue), SmartAnd(SmartNot(ce.Test), ifFalse)); } private static Expression? CoalesceEquals(Expression exp1, Expression exp2) { if (Schema.Current.Settings.IsDbType(exp1.Type.UnNullify()) || Schema.Current.Settings.IsDbType(exp2.Type.UnNullify())) return null; if (exp1.NodeType == ExpressionType.Coalesce) return DispachCoalesce((BinaryExpression)exp1, exp2); if (exp2.NodeType == ExpressionType.Coalesce) return DispachCoalesce((BinaryExpression)exp2, exp1); return null; } private static Expression DispachCoalesce(BinaryExpression be, Expression exp) { var leftNull = PolymorphicEqual(be.Left, Expression.Constant(null, be.Type)); var left = PolymorphicEqual(be.Left, exp); var right = PolymorphicEqual(be.Right, exp); return SmartOr(SmartAnd(SmartNot(leftNull), left), SmartAnd(leftNull, right)); } private static Expression SmartAnd(Expression e1, Expression e2) { if (e1 == True) return e2; if (e2 == True) return e1; if (e1 == False || e2 == False) return False; return Expression.And(e1, e2); } private static Expression SmartNot(Expression e) { if (e == True) return False; if (e == False) return True; return Expression.Not(e); } private static Expression SmartOr(Expression e1, Expression e2) { if (e1 == False) return e2; if (e2 == False) return e1; if (e1 == True || e2 == True) return True; return Expression.Or(e1, e2); } private static Expression? TypeEquals(Expression exp1, Expression exp2) { if (exp1.Type != typeof(Type) || exp2.Type != typeof(Type)) return null; if (exp1 is ConstantExpression c1) { if (exp2 is ConstantExpression c2) return TypeConstantConstantEquals(c1, c2); else if (exp2 is TypeEntityExpression te2) return TypeConstantEntityEquals(c1, te2); else if (exp2 is TypeImplementedByExpression tib2) return TypeConstantIbEquals(c1, tib2); else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeConstantIbaEquals(c1, tiba2); } else if (exp1 is TypeEntityExpression te1) { if (exp2 is ConstantExpression c2) return TypeConstantEntityEquals(c2, te1); else if (exp2 is TypeEntityExpression te2) return TypeEntityEntityEquals(te1, te2); else if (exp2 is TypeImplementedByExpression tib2) return TypeEntityIbEquals(te1, tib2); else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeEntityIbaEquals(te1, tiba2); } else if (exp1 is TypeImplementedByExpression tib1) { if (exp2 is ConstantExpression c2) return TypeConstantIbEquals(c2, tib1); else if (exp2 is TypeEntityExpression te2) return TypeEntityIbEquals(te2, tib1); else if (exp2 is TypeImplementedByExpression tib2) return TypeIbIbEquals(tib1, tib2); else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeIbIbaEquals(tib1, tiba2); } else if (exp1 is TypeImplementedByAllExpression tiba1) { if (exp2 is ConstantExpression c2) return TypeConstantIbaEquals(c2, tiba1); else if (exp2 is TypeEntityExpression te2) return TypeEntityIbaEquals(te2, tiba1); else if (exp2 is TypeImplementedByExpression tib2) return TypeIbIbaEquals(tib2, tiba1); else if (exp2 is TypeImplementedByAllExpression tiba2) return TypeIbaIbaEquals(tiba1, tiba2); } throw new InvalidOperationException("Impossible to resolve '{0}' equals '{1}'".FormatWith(exp1.ToString(), exp2.ToString())); } private static Expression TypeConstantEntityEquals(ConstantExpression ce, TypeEntityExpression typeEntity) { if (ce.IsNull()) return EqualsToNull(typeEntity.ExternalId); if (((Type)ce.Value == typeEntity.TypeValue)) return NotEqualToNull(typeEntity.ExternalId); return False; } private static Expression? TypeConstantIbEquals(ConstantExpression ce, TypeImplementedByExpression typeIb) { if (ce.IsNull()) { return typeIb.TypeImplementations.Select(imp => EqualsToNull(imp.Value)).AggregateAnd(); } Type type = (Type)ce.Value; var externalId = typeIb.TypeImplementations.TryGetC(type); return externalId == null ? False : NotEqualToNull(externalId); } private static Expression TypeConstantIbaEquals(ConstantExpression ce, TypeImplementedByAllExpression typeIba) { if (ce.IsNull()) return EqualsToNull(typeIba.TypeColumn); return EqualNullable(QueryBinder.TypeConstant((Type)ce.Value), typeIba.TypeColumn.Value); } private static Expression TypeConstantConstantEquals(ConstantExpression c1, ConstantExpression c2) { if (c1.IsNull()) { if (c2.IsNull()) return True; else return False; } else { if (c2.IsNull()) return False; if (c1.Value.Equals(c2.Value)) return True; else return False; } } private static Expression TypeEntityEntityEquals(TypeEntityExpression typeEntity1, TypeEntityExpression typeEntity2) { if (typeEntity1.TypeValue != typeEntity2.TypeValue) return False; return Expression.And(NotEqualToNull(typeEntity1.ExternalId), NotEqualToNull(typeEntity2.ExternalId)); } private static Expression TypeEntityIbEquals(TypeEntityExpression typeEntity, TypeImplementedByExpression typeIb) { var externalId = typeIb.TypeImplementations.TryGetC(typeEntity.TypeValue); if (externalId == null) return False; return Expression.And(NotEqualToNull(typeEntity.ExternalId), NotEqualToNull(externalId)); } private static Expression TypeEntityIbaEquals(TypeEntityExpression typeEntity, TypeImplementedByAllExpression typeIba) { return Expression.And(NotEqualToNull(typeEntity.ExternalId), EqualNullable(typeIba.TypeColumn, QueryBinder.TypeConstant(typeEntity.TypeValue))); } private static Expression TypeIbaIbaEquals(TypeImplementedByAllExpression t1, TypeImplementedByAllExpression t2) { return Expression.Equal(t1.TypeColumn, t2.TypeColumn); } private static Expression TypeIbIbEquals(TypeImplementedByExpression typeIb1, TypeImplementedByExpression typeIb2) { var joins = (from imp1 in typeIb1.TypeImplementations join imp2 in typeIb2.TypeImplementations on imp1.Key equals imp2.Key select Expression.And(NotEqualToNull(imp1.Value), NotEqualToNull(imp2.Value))).ToList(); return joins.AggregateOr(); } private static Expression TypeIbIbaEquals(TypeImplementedByExpression typeIb, TypeImplementedByAllExpression typeIba) { return typeIb.TypeImplementations .Select(imp => Expression.And(NotEqualToNull(imp.Value), EqualNullable(typeIba.TypeColumn, QueryBinder.TypeConstant(imp.Key)))) .AggregateOr(); } internal static Expression TypeIn(Expression typeExpr, IEnumerable<Type> collection) { if (collection.IsNullOrEmpty()) return False; if (typeExpr.NodeType == ExpressionType.Conditional) return DispachConditionalTypesIn((ConditionalExpression)typeExpr, collection); if (typeExpr.NodeType == ExpressionType.Constant) { Type type = (Type)((ConstantExpression)typeExpr).Value; return collection.Contains(type) ? True : False; } if (typeExpr is TypeEntityExpression typeEntity) { return collection.Contains(typeEntity.TypeValue) ? NotEqualToNull(typeEntity.ExternalId) : (Expression)False; } if (typeExpr is TypeImplementedByExpression typeIb) { return typeIb.TypeImplementations.Where(imp => collection.Contains(imp.Key)) .Select(imp => NotEqualToNull(imp.Value)).AggregateOr(); } if (typeExpr is TypeImplementedByAllExpression typeIba) { PrimaryKey[] ids = collection.Select(t => QueryBinder.TypeId(t)).ToArray(); return InPrimaryKey(typeIba.TypeColumn, ids); } throw new InvalidOperationException("Impossible to resolve '{0}' in '{1}'".FormatWith(typeExpr.ToString(), collection.ToString(t=>t.TypeName(), ", "))); } public static Expression In(Expression element, object[] values, bool isPostgres) { var nominate = DbExpressionNominator.FullNominate(element)!; if (nominate.RemoveUnNullify() is ToDayOfWeekExpression dowe) { if (isPostgres) { var sqlWeekDays = values.Cast<DayOfWeek>() .Select(a => (object)(int)a) .ToArray(); return InExpression.FromValues(dowe.Expression, sqlWeekDays); } else { byte dateFirs = ((SqlServerConnector)Connector.Current).DateFirst; var sqlWeekDays = values.Cast<DayOfWeek>() .Select(a => (object)ToDayOfWeekExpression.ToSqlWeekDay(a, dateFirs)) .ToArray(); return InExpression.FromValues(dowe.Expression, sqlWeekDays); } } else return InExpression.FromValues(nominate, values); } public static Expression InPrimaryKey(Expression element, PrimaryKey[] values) { var cleanValues = values.Select(a => a.Object).ToArray(); var cleanElement = SmartEqualizer.UnwrapPrimaryKey(element); if (cleanElement == NewId) return False; cleanElement = DbExpressionNominator.FullNominate(cleanElement)!; if (cleanElement.Type == typeof(string)) return InExpression.FromValues(cleanElement, cleanValues.Select(a => (object)a.ToString()!).ToArray()); else return InExpression.FromValues(cleanElement, cleanValues); } private static Expression DispachConditionalTypesIn(ConditionalExpression ce, IEnumerable<Type> collection) { var ifTrue = TypeIn(ce.IfTrue, collection); var ifFalse = TypeIn(ce.IfFalse, collection); return SmartOr(SmartAnd(ce.Test, ifTrue), SmartAnd(SmartNot(ce.Test), ifFalse)); } internal static Expression EntityIn(Expression newItem, IEnumerable<Entity> collection) { if (collection.IsEmpty()) return False; Dictionary<Type, PrimaryKey[]> entityIDs = collection.Where(a => a.IdOrNull.HasValue).AgGroupToDictionary(a => a.GetType(), gr => gr.Select(a => a.Id).ToArray()); return EntityIn(newItem, entityIDs); } internal static Expression EntityIn(LiteReferenceExpression liteReference, IEnumerable<Lite<IEntity>> collection) { if (collection.IsEmpty()) return False; Dictionary<Type, PrimaryKey[]> entityIDs = collection.Where(a => a.IdOrNull.HasValue).AgGroupToDictionary(a => a.EntityType, gr => gr.Select(a => a.Id).ToArray()); return EntityIn(liteReference.Reference, entityIDs); } static Expression EntityIn(Expression newItem, Dictionary<Type, PrimaryKey[]> entityIDs) { if (newItem is EntityExpression ee) return InPrimaryKey(ee.ExternalId, entityIDs.TryGetC(ee.Type) ?? new PrimaryKey[0]); if (newItem is ImplementedByExpression ib) return ib.Implementations.JoinDictionary(entityIDs, (t, f, values) => Expression.And(DbExpressionNominator.FullNominate(NotEqualToNull(f.ExternalId)), InPrimaryKey(f.ExternalId, values))) .Values.AggregateOr(); if (newItem is ImplementedByAllExpression iba) return entityIDs.Select(kvp => Expression.And( EqualNullable(new PrimaryKeyExpression(QueryBinder.TypeConstant(kvp.Key).Nullify()), iba.TypeId.TypeColumn), InPrimaryKey(iba.Id, kvp.Value))).AggregateOr(); throw new InvalidOperationException("EntityIn not defined for newItem of type {0}".FormatWith(newItem.Type.Name)); } public static Expression? LiteEquals(Expression e1, Expression e2) { if ( e1.Type.IsLite() || e2.Type.IsLite()) { if (!e1.Type.IsLite() && !e1.IsNull() || !e2.Type.IsLite() && !e2.IsNull()) throw new InvalidOperationException("Imposible to compare expressions of type {0} == {1}".FormatWith(e1.Type.TypeName(), e2.Type.TypeName())); return PolymorphicEqual(GetEntity(e1), GetEntity(e2)); //Conditional and Coalesce could be inside } return null; } public static Expression? MListElementEquals(Expression e1, Expression e2) { if (e1 is MListElementExpression || e2 is MListElementExpression) { if (e1.IsNull()) return EqualsToNull(((MListElementExpression)e2).RowId); if (e2.IsNull()) return EqualsToNull(((MListElementExpression)e1).RowId); return EqualNullable(((MListElementExpression)e1).RowId, ((MListElementExpression)e2).RowId); } return null; } private static Expression GetEntity(Expression liteExp) { liteExp = ConstantToLite(liteExp) ?? liteExp; if (liteExp.IsNull()) return Expression.Constant(null, liteExp.Type.CleanType()); if (liteExp is UnaryExpression ue && (ue.NodeType == ExpressionType.Convert || ue.NodeType == ExpressionType.ConvertChecked)) liteExp = ue.Operand; if (!(liteExp is LiteReferenceExpression liteReference)) throw new InvalidCastException("Impossible to convert expression to Lite: {0}".FormatWith(liteExp.ToString())); return liteReference.Reference; } public static Expression? EntityEquals(Expression e1, Expression e2) { e1 = ConstantToEntity(e1) ?? e1; e2 = ConstantToEntity(e2) ?? e2; if (e1 is EmbeddedEntityExpression && e2.IsNull()) return EmbeddedNullEquals((EmbeddedEntityExpression)e1); if (e2 is EmbeddedEntityExpression && e1.IsNull()) return EmbeddedNullEquals((EmbeddedEntityExpression)e2); if (e1 is EntityExpression ee1) { if (e2 is EntityExpression ee2) return EntityEntityEquals(ee1, ee2); else if (e2 is ImplementedByExpression ib2) return EntityIbEquals(ee1, ib2); else if (e2 is ImplementedByAllExpression iba2) return EntityIbaEquals(ee1, iba2); else if (e2.IsNull()) return EqualsToNull((ee1).ExternalId); else return null; } else if (e1 is ImplementedByExpression ib1) { if (e2 is EntityExpression ee2) return EntityIbEquals(ee2, ib1); else if (e2 is ImplementedByExpression ib2) return IbIbEquals(ib1, ib2); else if (e2 is ImplementedByAllExpression iba2) return IbIbaEquals(ib1, iba2); else if (e2.IsNull()) return (ib1).Implementations.Select(a => EqualsToNull(a.Value.ExternalId)).AggregateAnd(); else return null; } else if (e1 is ImplementedByAllExpression iba1) { if (e2 is EntityExpression ee2) return EntityIbaEquals(ee2, iba1); else if (e2 is ImplementedByExpression ib2) return IbIbaEquals(ib2, iba1); else if (e2 is ImplementedByAllExpression iba2) return IbaIbaEquals(iba1, iba2); else if (e2.IsNull()) return EqualsToNull((iba1).TypeId.TypeColumn); else return null; } else if (e1.IsNull()) { if (e2 is EntityExpression ee2) return EqualsToNull((ee2).ExternalId); else if (e2 is ImplementedByExpression ib2) return ib2.Implementations.Select(a => EqualsToNull(a.Value.ExternalId)).AggregateAnd(); else if (e2 is ImplementedByAllExpression iba2) return EqualsToNull(iba2.TypeId.TypeColumn); else if (e2.IsNull()) return True; else return null; } else return null; } static Expression EmbeddedNullEquals(EmbeddedEntityExpression eee) { return Expression.Not(eee.HasValue); } static Expression EntityEntityEquals(EntityExpression e1, EntityExpression e2) { if (e1.Type == e2.Type) return PolymorphicEqual(e1.ExternalId, e2.ExternalId).And(e1.ExternalPeriod.Overlaps(e2.ExternalPeriod)); else return False; } static Expression EntityIbEquals(EntityExpression ee, ImplementedByExpression ib) { var imp = ib.Implementations.TryGetC(ee.Type); if (imp == null) return False; return EntityEntityEquals(imp, ee); } static Expression EntityIbaEquals(EntityExpression ee, ImplementedByAllExpression iba) { return Expression.And( ee.ExternalId.Value == NewId ? False : EqualNullable(new SqlCastExpression(typeof(string), ee.ExternalId.Value), iba.Id), EqualNullable(QueryBinder.TypeConstant(ee.Type), iba.TypeId.TypeColumn.Value)) .And(ee.ExternalPeriod.Overlaps(iba.ExternalPeriod)); } static Expression IbIbEquals(ImplementedByExpression ib, ImplementedByExpression ib2) { var list = ib.Implementations.JoinDictionary(ib2.Implementations, (t, i, j) => EntityEntityEquals(i, j)).Values.ToList(); return list.AggregateOr(); } static Expression IbIbaEquals(ImplementedByExpression ib, ImplementedByAllExpression iba) { var list = ib.Implementations.Values.Select(i => Expression.And( i.ExternalId.Value == NewId ? (Expression)False : EqualNullable(iba.Id, new SqlCastExpression(typeof(string), i.ExternalId.Value)), EqualNullable(iba.TypeId.TypeColumn.Value, QueryBinder.TypeConstant(i.Type)))).ToList(); return list.AggregateOr(); } static Expression IbaIbaEquals(ImplementedByAllExpression iba, ImplementedByAllExpression iba2) { return Expression.And(EqualNullable(iba.Id, iba2.Id), EqualNullable(iba.TypeId.TypeColumn.Value, iba2.TypeId.TypeColumn.Value)); } static Expression EqualsToNull(PrimaryKeyExpression exp) { return EqualNullable(exp.Value, new SqlConstantExpression(null, exp.ValueType)); } static Expression NotEqualToNull(PrimaryKeyExpression exp) { return NotEqualNullable(exp.Value, new SqlConstantExpression(null, exp.ValueType)); } public static Expression? ConstantToEntity(Expression expression) { ConstantExpression? c = expression as ConstantExpression; if (c == null) return null; if (c.Value == null) return c; if (c.Type.IsIEntity()) { var ei = (Entity)c.Value; var id = GetPrimaryKeyValue(ei.IdOrNull, ei.GetType()); return new EntityExpression(ei.GetType(), new PrimaryKeyExpression(id), null, null, null, null, null, avoidExpandOnRetrieving: true); } return null; } public static Expression? ConstantToLite(Expression expression) { ConstantExpression? c = expression as ConstantExpression; if (c == null) return null; if (c.Value == null) return c; if (c.Type.IsLite()) { Lite<IEntity> lite = (Lite<IEntity>)c.Value; var id = GetPrimaryKeyValue(lite.IdOrNull, lite.EntityType); EntityExpression ere = new EntityExpression(lite.EntityType, new PrimaryKeyExpression(id), null, null, null, null, null, false); return new LiteReferenceExpression(Lite.Generate(lite.EntityType), ere, null, false, false); } return null; } private static Expression GetPrimaryKeyValue(PrimaryKey? idOrNull, Type type) { if (idOrNull == null) return SmartEqualizer.NewId; var pkType = PrimaryKey.Type(type).Nullify(); if (idOrNull.Value.VariableName != null && PrimaryKeyExpression.PreferVariableNameVariable.Value) return new SqlVariableExpression(idOrNull.Value.VariableName, pkType); return Expression.Constant(idOrNull.Value.Object, pkType); } } }
using System; using System.Drawing; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2003; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/ClassDef/*'/> internal class VS2003DockPaneCaption : DockPaneCaptionBase { #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private InertButton m_buttonClose; private InertButton m_buttonAutoHide; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Construct[@name="(DockPane)"]/*'/> protected internal VS2003DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); Font = SystemInformation.MenuFont; m_buttonClose = new InertButton(ImageCloseEnabled, ImageCloseDisabled); m_buttonAutoHide = new InertButton(); m_buttonClose.ToolTipText = ToolTipClose; m_buttonClose.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonClose.Click += new EventHandler(this.Close_Click); m_buttonAutoHide.ToolTipText = ToolTipAutoHide; m_buttonAutoHide.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.AddRange(new Control[] { m_buttonClose, m_buttonAutoHide }); ResumeLayout(); } #region Customizable Properties /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="TextGapTop"]/*'/> protected virtual int TextGapTop { get { return _TextGapTop; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="TextGapBottom"]/*'/> protected virtual int TextGapBottom { get { return _TextGapBottom; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="TextGapLeft"]/*'/> protected virtual int TextGapLeft { get { return _TextGapLeft; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="TextGapRight"]/*'/> protected virtual int TextGapRight { get { return _TextGapRight; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ButtonGapTop"]/*'/> protected virtual int ButtonGapTop { get { return _ButtonGapTop; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ButtonGapBottom"]/*'/> protected virtual int ButtonGapBottom { get { return _ButtonGapBottom; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ButtonGapLeft"]/*'/> protected virtual int ButtonGapLeft { get { return _ButtonGapLeft; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ButtonGapRight"]/*'/> protected virtual int ButtonGapRight { get { return _ButtonGapRight; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ButtonGapBetween"]/*'/> protected virtual int ButtonGapBetween { get { return _ButtonGapBetween; } } private static Image _imageCloseEnabled = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ImageCloseEnabled"]/*'/> protected virtual Image ImageCloseEnabled { get { if (_imageCloseEnabled == null) _imageCloseEnabled = Resources.DockPaneCaption_CloseEnabled; return _imageCloseEnabled; } } private static Image _imageCloseDisabled = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ImageCloseDisabled"]/*'/> protected virtual Image ImageCloseDisabled { get { if (_imageCloseDisabled == null) _imageCloseDisabled = Resources.DockPaneCaption_CloseDisabled; return _imageCloseDisabled; } } private static Image _imageAutoHideYes = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ImageAutoHideYes"]/*'/> protected virtual Image ImageAutoHideYes { get { if (_imageAutoHideYes == null) _imageAutoHideYes = Resources.DockPaneCaption_AutoHideYes; return _imageAutoHideYes; } } private static Image _imageAutoHideNo = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ImageAutoHideNo"]/*'/> protected virtual Image ImageAutoHideNo { get { if (_imageAutoHideNo == null) _imageAutoHideNo = Resources.DockPaneCaption_AutoHideNo; return _imageAutoHideNo; } } private static string _toolTipClose = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ToolTipClose"]/*'/> protected virtual string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneCaption_ToolTipClose; return _toolTipClose; } } private static string _toolTipAutoHide = null; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ToolTipAutoHide"]/*'/> protected virtual string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; return _toolTipAutoHide; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ActiveBackColor"]/*'/> protected virtual Color ActiveBackColor { get { return SystemColors.ActiveCaption; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="InactiveBackColor"]/*'/> protected virtual Color InactiveBackColor { get { return SystemColors.Control; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ActiveTextColor"]/*'/> protected virtual Color ActiveTextColor { get { return SystemColors.ActiveCaptionText; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="InactiveTextColor"]/*'/> protected virtual Color InactiveTextColor { get { return SystemColors.ControlText; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="InactiveBorderColor"]/*'/> protected virtual Color InactiveBorderColor { get { return SystemColors.GrayText; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="ActiveButtonBorderColor"]/*'/> protected virtual Color ActiveButtonBorderColor { get { return ActiveTextColor; } } /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="InactiveButtonBorderColor"]/*'/> protected virtual Color InactiveButtonBorderColor { get { return Color.Empty; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; /// <include file='CodeDoc/DockPaneCaptionVS2003.xml' path='//CodeDoc/Class[@name="DockPaneCaptionVS2003"]/Property[@name="TextStringFormat"]/*'/> protected virtual TextFormatFlags TextFormat { get { return _textFormat; } } #endregion /// <exclude/> protected override int MeasureHeight() { int height = Font.Height + TextGapTop + TextGapBottom; if (height < ImageCloseEnabled.Height + ButtonGapTop + ButtonGapBottom) height = ImageCloseEnabled.Height + ButtonGapTop + ButtonGapBottom; return height; } /// <exclude/> protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { BackColor = DockPane.IsActivated ? ActiveBackColor : InactiveBackColor; Rectangle rectCaption = ClientRectangle; if (!DockPane.IsActivated) { using (Pen pen = new Pen(InactiveBorderColor)) { g.DrawLine(pen, rectCaption.X + 1, rectCaption.Y, rectCaption.X + rectCaption.Width - 2, rectCaption.Y); g.DrawLine(pen, rectCaption.X + 1, rectCaption.Y + rectCaption.Height - 1, rectCaption.X + rectCaption.Width - 2, rectCaption.Y + rectCaption.Height - 1); g.DrawLine(pen, rectCaption.X, rectCaption.Y + 1, rectCaption.X, rectCaption.Y + rectCaption.Height - 2); g.DrawLine(pen, rectCaption.X + rectCaption.Width - 1, rectCaption.Y + 1, rectCaption.X + rectCaption.Width - 1, rectCaption.Y + rectCaption.Height - 2); } } m_buttonClose.ForeColor = m_buttonAutoHide.ForeColor = (DockPane.IsActivated ? ActiveTextColor : InactiveTextColor); m_buttonClose.BorderColor = m_buttonAutoHide.BorderColor = (DockPane.IsActivated ? ActiveButtonBorderColor : InactiveButtonBorderColor); Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; if (ShouldShowCloseButton && ShouldShowAutoHideButton) rectCaptionText.Width = rectCaption.Width - ButtonGapRight - ButtonGapLeft - TextGapLeft - TextGapRight - (m_buttonAutoHide.Width + ButtonGapBetween + m_buttonClose.Width); else if (ShouldShowCloseButton || ShouldShowAutoHideButton) rectCaptionText.Width = rectCaption.Width - ButtonGapRight - ButtonGapLeft - TextGapLeft - TextGapRight - m_buttonClose.Width; else rectCaptionText.Width = rectCaption.Width - TextGapLeft - TextGapRight; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; TextRenderer.DrawText(g, DockPane.CaptionText, Font, rectCaptionText, DockPane.IsActivated ? ActiveTextColor : InactiveTextColor, TextFormat); } /// <exclude/> protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } /// <exclude/> protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool ShouldShowCloseButton { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { m_buttonClose.Visible = ShouldShowCloseButton; m_buttonAutoHide.Visible = ShouldShowAutoHideButton; m_buttonAutoHide.ImageEnabled = DockPane.IsAutoHide ? ImageAutoHideYes : ImageAutoHideNo; SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ImageCloseEnabled.Width; int buttonHeight = ImageCloseEnabled.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } m_buttonClose.SuspendLayout(); m_buttonAutoHide.SuspendLayout(); Size buttonSize = new Size(buttonWidth, buttonHeight); m_buttonClose.Size = m_buttonAutoHide.Size = buttonSize; int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = m_buttonClose.Location = new Point(x, y); if (ShouldShowCloseButton) point.Offset(-(m_buttonAutoHide.Width + ButtonGapBetween), 0); m_buttonAutoHide.Location = point; m_buttonClose.ResumeLayout(); m_buttonAutoHide.ResumeLayout(); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (!DockPane.IsAutoHide) DockPane.Activate(); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- $PostFXManager::defaultPreset = "./default.postfxpreset.cs"; function PostFXManager::settingsSetEnabled(%this, %bEnablePostFX) { $PostFXManager::PostFX::Enabled = %bEnablePostFX; //if to enable the postFX, apply the ones that are enabled if ( %bEnablePostFX ) { //SSAO, HDR, LightRays, DOF if ( $PostFXManager::PostFX::EnableSSAO ) SSAOPostFx.enable(); else SSAOPostFx.disable(); if ( $PostFXManager::PostFX::EnableHDR ) HDRPostFX.enable(); else HDRPostFX.disable(); if ( $PostFXManager::PostFX::EnableLightRays ) LightRayPostFX.enable(); else LightRayPostFX.disable(); if ( $PostFXManager::PostFX::EnableDOF ) DOFPostEffect.enable(); else DOFPostEffect.disable(); if ( $PostFXManager::PostFX::EnableVignette ) VignettePostEffect.enable(); else VignettePostEffect.disable(); postVerbose("% - PostFX Manager - PostFX enabled"); } else { //Disable all postFX SSAOPostFx.disable(); HDRPostFX.disable(); LightRayPostFX.disable(); DOFPostEffect.disable(); VignettePostEffect.disable(); postVerbose("% - PostFX Manager - PostFX disabled"); } VolFogGlowPostFx.disable(); } function PostFXManager::settingsEffectSetEnabled(%this, %sName, %bEnable) { %postEffect = 0; //Determine the postFX to enable, and apply the boolean if(%sName $= "SSAO") { %postEffect = SSAOPostFx; $PostFXManager::PostFX::EnableSSAO = %bEnable; //$pref::PostFX::SSAO::Enabled = %bEnable; } else if(%sName $= "HDR") { %postEffect = HDRPostFX; $PostFXManager::PostFX::EnableHDR = %bEnable; //$pref::PostFX::HDR::Enabled = %bEnable; } else if(%sName $= "LightRays") { %postEffect = LightRayPostFX; $PostFXManager::PostFX::EnableLightRays = %bEnable; //$pref::PostFX::LightRays::Enabled = %bEnable; } else if(%sName $= "DOF") { %postEffect = DOFPostEffect; $PostFXManager::PostFX::EnableDOF = %bEnable; //$pref::PostFX::DOF::Enabled = %bEnable; } else if(%sName $= "Vignette") { %postEffect = VignettePostEffect; $PostFXManager::PostFX::EnableVignette = %bEnable; //$pref::PostFX::Vignette::Enabled = %bEnable; } // Apply the change if ( %bEnable == true ) { %postEffect.enable(); postVerbose("% - PostFX Manager - " @ %sName @ " enabled"); } else { %postEffect.disable(); postVerbose("% - PostFX Manager - " @ %sName @ " disabled"); } } function PostFXManager::settingsRefreshSSAO(%this) { //Apply the enabled flag ppOptionsEnableSSAO.setValue($PostFXManager::PostFX::EnableSSAO); //Add the items we need to display ppOptionsSSAOQuality.clear(); ppOptionsSSAOQuality.add("Low", 0); ppOptionsSSAOQuality.add("Medium", 1); ppOptionsSSAOQuality.add("High", 2); //Set the selected, after adding the items! ppOptionsSSAOQuality.setSelected($SSAOPostFx::quality); //SSAO - Set the values of the sliders, General Tab ppOptionsSSAOOverallStrength.setValue($SSAOPostFx::overallStrength); ppOptionsSSAOBlurDepth.setValue($SSAOPostFx::blurDepthTol); ppOptionsSSAOBlurNormal.setValue($SSAOPostFx::blurNormalTol); //SSAO - Set the values for the near tab ppOptionsSSAONearDepthMax.setValue($SSAOPostFx::sDepthMax); ppOptionsSSAONearDepthMin.setValue($SSAOPostFx::sDepthMin); ppOptionsSSAONearRadius.setValue($SSAOPostFx::sRadius); ppOptionsSSAONearStrength.setValue($SSAOPostFx::sStrength); ppOptionsSSAONearToleranceNormal.setValue($SSAOPostFx::sNormalTol); ppOptionsSSAONearTolerancePower.setValue($SSAOPostFx::sNormalPow); //SSAO - Set the values for the far tab ppOptionsSSAOFarDepthMax.setValue($SSAOPostFx::lDepthMax); ppOptionsSSAOFarDepthMin.setValue($SSAOPostFx::lDepthMin); ppOptionsSSAOFarRadius.setValue($SSAOPostFx::lRadius); ppOptionsSSAOFarStrength.setValue($SSAOPostFx::lStrength); ppOptionsSSAOFarToleranceNormal.setValue($SSAOPostFx::lNormalTol); ppOptionsSSAOFarTolerancePower.setValue($SSAOPostFx::lNormalPow); } function PostFXManager::settingsRefreshHDR(%this) { //Apply the enabled flag ppOptionsEnableHDR.setValue($PostFXManager::PostFX::EnableHDR); ppOptionsHDRBloom.setValue($HDRPostFX::enableBloom); ppOptionsHDRBloomBlurBrightPassThreshold.setValue($HDRPostFX::brightPassThreshold); ppOptionsHDRBloomBlurMean.setValue($HDRPostFX::gaussMean); ppOptionsHDRBloomBlurMultiplier.setValue($HDRPostFX::gaussMultiplier); ppOptionsHDRBloomBlurStdDev.setValue($HDRPostFX::gaussStdDev); ppOptionsHDRBrightnessAdaptRate.setValue($HDRPostFX::adaptRate); ppOptionsHDREffectsBlueShift.setValue($HDRPostFX::enableBlueShift); ppOptionsHDREffectsBlueShiftColor.BaseColor = $HDRPostFX::blueShiftColor; ppOptionsHDREffectsBlueShiftColor.PickColor = $HDRPostFX::blueShiftColor; ppOptionsHDRKeyValue.setValue($HDRPostFX::keyValue); ppOptionsHDRMinLuminance.setValue($HDRPostFX::minLuminace); ppOptionsHDRToneMapping.setValue($HDRPostFX::enableToneMapping); ppOptionsHDRToneMappingAmount.setValue($HDRPostFX::enableToneMapping); ppOptionsHDRWhiteCutoff.setValue($HDRPostFX::whiteCutoff); %this-->ColorCorrectionFileName.Text = $HDRPostFX::colorCorrectionRamp; } function PostFXManager::settingsRefreshLightrays(%this) { //Apply the enabled flag ppOptionsEnableLightRays.setValue($PostFXManager::PostFX::EnableLightRays); ppOptionsLightRaysBrightScalar.setValue($LightRayPostFX::brightScalar); ppOptionsLightRaysSampleScalar.setValue($LightRayPostFX::numSamples); ppOptionsLightRaysDensityScalar.setValue($LightRayPostFX::density); ppOptionsLightRaysWeightScalar.setValue($LightRayPostFX::weight); ppOptionsLightRaysDecayScalar.setValue($LightRayPostFX::decay); } function PostFXManager::settingsRefreshDOF(%this) { //Apply the enabled flag ppOptionsEnableDOF.setValue($PostFXManager::PostFX::EnableDOF); //ppOptionsDOFEnableDOF.setValue($PostFXManager::PostFX::EnableDOF); ppOptionsDOFEnableAutoFocus.setValue($DOFPostFx::EnableAutoFocus); ppOptionsDOFFarBlurMinSlider.setValue($DOFPostFx::BlurMin); ppOptionsDOFFarBlurMaxSlider.setValue($DOFPostFx::BlurMax); ppOptionsDOFFocusRangeMinSlider.setValue($DOFPostFx::FocusRangeMin); ppOptionsDOFFocusRangeMaxSlider.setValue($DOFPostFx::FocusRangeMax); ppOptionsDOFBlurCurveNearSlider.setValue($DOFPostFx::BlurCurveNear); ppOptionsDOFBlurCurveFarSlider.setValue($DOFPostFx::BlurCurveFar); } function PostFXManager::settingsRefreshVignette(%this) { //Apply the enabled flag ppOptionsEnableVignette.setValue($PostFXManager::PostFX::EnableVignette); } function PostFXManager::settingsRefreshAll(%this) { $PostFXManager::PostFX::Enabled = $pref::enablePostEffects; $PostFXManager::PostFX::EnableSSAO = SSAOPostFx.isEnabled(); $PostFXManager::PostFX::EnableHDR = HDRPostFX.isEnabled(); $PostFXManager::PostFX::EnableLightRays = LightRayPostFX.isEnabled(); $PostFXManager::PostFX::EnableDOF = DOFPostEffect.isEnabled(); $PostFXManager::PostFX::EnableVignette = VignettePostEffect.isEnabled(); //For all the postFX here, apply the active settings in the system //to the gui controls. %this.settingsRefreshSSAO(); %this.settingsRefreshHDR(); %this.settingsRefreshLightrays(); %this.settingsRefreshDOF(); %this.settingsRefreshVignette(); ppOptionsEnable.setValue($PostFXManager::PostFX::Enabled); postVerbose("% - PostFX Manager - GUI values updated."); } function PostFXManager::settingsApplyFromPreset(%this) { postVerbose("% - PostFX Manager - Applying from preset"); //SSAO Settings $SSAOPostFx::blurDepthTol = $PostFXManager::Settings::SSAO::blurDepthTol; $SSAOPostFx::blurNormalTol = $PostFXManager::Settings::SSAO::blurNormalTol; $SSAOPostFx::lDepthMax = $PostFXManager::Settings::SSAO::lDepthMax; $SSAOPostFx::lDepthMin = $PostFXManager::Settings::SSAO::lDepthMin; $SSAOPostFx::lDepthPow = $PostFXManager::Settings::SSAO::lDepthPow; $SSAOPostFx::lNormalPow = $PostFXManager::Settings::SSAO::lNormalPow; $SSAOPostFx::lNormalTol = $PostFXManager::Settings::SSAO::lNormalTol; $SSAOPostFx::lRadius = $PostFXManager::Settings::SSAO::lRadius; $SSAOPostFx::lStrength = $PostFXManager::Settings::SSAO::lStrength; $SSAOPostFx::overallStrength = $PostFXManager::Settings::SSAO::overallStrength; $SSAOPostFx::quality = $PostFXManager::Settings::SSAO::quality; $SSAOPostFx::sDepthMax = $PostFXManager::Settings::SSAO::sDepthMax; $SSAOPostFx::sDepthMin = $PostFXManager::Settings::SSAO::sDepthMin; $SSAOPostFx::sDepthPow = $PostFXManager::Settings::SSAO::sDepthPow; $SSAOPostFx::sNormalPow = $PostFXManager::Settings::SSAO::sNormalPow; $SSAOPostFx::sNormalTol = $PostFXManager::Settings::SSAO::sNormalTol; $SSAOPostFx::sRadius = $PostFXManager::Settings::SSAO::sRadius; $SSAOPostFx::sStrength = $PostFXManager::Settings::SSAO::sStrength; //HDR settings $HDRPostFX::adaptRate = $PostFXManager::Settings::HDR::adaptRate; $HDRPostFX::blueShiftColor = $PostFXManager::Settings::HDR::blueShiftColor; $HDRPostFX::brightPassThreshold = $PostFXManager::Settings::HDR::brightPassThreshold; $HDRPostFX::enableBloom = $PostFXManager::Settings::HDR::enableBloom; $HDRPostFX::enableBlueShift = $PostFXManager::Settings::HDR::enableBlueShift; $HDRPostFX::enableToneMapping = $PostFXManager::Settings::HDR::enableToneMapping; $HDRPostFX::gaussMean = $PostFXManager::Settings::HDR::gaussMean; $HDRPostFX::gaussMultiplier = $PostFXManager::Settings::HDR::gaussMultiplier; $HDRPostFX::gaussStdDev = $PostFXManager::Settings::HDR::gaussStdDev; $HDRPostFX::keyValue = $PostFXManager::Settings::HDR::keyValue; $HDRPostFX::minLuminace = $PostFXManager::Settings::HDR::minLuminace; $HDRPostFX::whiteCutoff = $PostFXManager::Settings::HDR::whiteCutoff; $HDRPostFX::colorCorrectionRamp = $PostFXManager::Settings::ColorCorrectionRamp; //Light rays settings $LightRayPostFX::brightScalar = $PostFXManager::Settings::LightRays::brightScalar; $LightRayPostFX::numSamples = $PostFXManager::Settings::LightRays::numSamples; $LightRayPostFX::density = $PostFXManager::Settings::LightRays::density; $LightRayPostFX::weight = $PostFXManager::Settings::LightRays::weight; $LightRayPostFX::decay = $PostFXManager::Settings::LightRays::decay; //DOF settings $DOFPostFx::EnableAutoFocus = $PostFXManager::Settings::DOF::EnableAutoFocus; $DOFPostFx::BlurMin = $PostFXManager::Settings::DOF::BlurMin; $DOFPostFx::BlurMax = $PostFXManager::Settings::DOF::BlurMax; $DOFPostFx::FocusRangeMin = $PostFXManager::Settings::DOF::FocusRangeMin; $DOFPostFx::FocusRangeMax = $PostFXManager::Settings::DOF::FocusRangeMax; $DOFPostFx::BlurCurveNear = $PostFXManager::Settings::DOF::BlurCurveNear; $DOFPostFx::BlurCurveFar = $PostFXManager::Settings::DOF::BlurCurveFar; //Vignette settings $VignettePostEffect::VMax = $PostFXManager::Settings::Vignette::VMax; $VignettePostEffect::VMin = $PostFXManager::Settings::Vignette::VMin; if ( $PostFXManager::forceEnableFromPresets ) { $PostFXManager::PostFX::Enabled = $PostFXManager::Settings::EnablePostFX; $PostFXManager::PostFX::EnableDOF = $pref::PostFX::EnableDOF ? $PostFXManager::Settings::EnableDOF : false; $PostFXManager::PostFX::EnableVignette = $pref::PostFX::EnableVignette ? $PostFXManager::Settings::EnableVignette : false; $PostFXManager::PostFX::EnableLightRays = $pref::PostFX::EnableLightRays ? $PostFXManager::Settings::EnableLightRays : false; $PostFXManager::PostFX::EnableHDR = $pref::PostFX::EnableHDR ? $PostFXManager::Settings::EnableHDR : false; $PostFXManager::PostFX::EnableSSAO = $pref::PostFX::EnabledSSAO ? $PostFXManager::Settings::EnableSSAO : false; %this.settingsSetEnabled( true ); } //make sure we apply the correct settings to the DOF ppOptionsUpdateDOFSettings(); // Update the actual GUI controls if its awake ( otherwise it will when opened ). if ( PostFXManager.isAwake() ) %this.settingsRefreshAll(); } function PostFXManager::settingsApplySSAO(%this) { $PostFXManager::Settings::SSAO::blurDepthTol = $SSAOPostFx::blurDepthTol; $PostFXManager::Settings::SSAO::blurNormalTol = $SSAOPostFx::blurNormalTol; $PostFXManager::Settings::SSAO::lDepthMax = $SSAOPostFx::lDepthMax; $PostFXManager::Settings::SSAO::lDepthMin = $SSAOPostFx::lDepthMin; $PostFXManager::Settings::SSAO::lDepthPow = $SSAOPostFx::lDepthPow; $PostFXManager::Settings::SSAO::lNormalPow = $SSAOPostFx::lNormalPow; $PostFXManager::Settings::SSAO::lNormalTol = $SSAOPostFx::lNormalTol; $PostFXManager::Settings::SSAO::lRadius = $SSAOPostFx::lRadius; $PostFXManager::Settings::SSAO::lStrength = $SSAOPostFx::lStrength; $PostFXManager::Settings::SSAO::overallStrength = $SSAOPostFx::overallStrength; $PostFXManager::Settings::SSAO::quality = $SSAOPostFx::quality; $PostFXManager::Settings::SSAO::sDepthMax = $SSAOPostFx::sDepthMax; $PostFXManager::Settings::SSAO::sDepthMin = $SSAOPostFx::sDepthMin; $PostFXManager::Settings::SSAO::sDepthPow = $SSAOPostFx::sDepthPow; $PostFXManager::Settings::SSAO::sNormalPow = $SSAOPostFx::sNormalPow; $PostFXManager::Settings::SSAO::sNormalTol = $SSAOPostFx::sNormalTol; $PostFXManager::Settings::SSAO::sRadius = $SSAOPostFx::sRadius; $PostFXManager::Settings::SSAO::sStrength = $SSAOPostFx::sStrength; postVerbose("% - PostFX Manager - Settings Saved - SSAO"); } function PostFXManager::settingsApplyHDR(%this) { $PostFXManager::Settings::HDR::adaptRate = $HDRPostFX::adaptRate; $PostFXManager::Settings::HDR::blueShiftColor = $HDRPostFX::blueShiftColor; $PostFXManager::Settings::HDR::brightPassThreshold = $HDRPostFX::brightPassThreshold; $PostFXManager::Settings::HDR::enableBloom = $HDRPostFX::enableBloom; $PostFXManager::Settings::HDR::enableBlueShift = $HDRPostFX::enableBlueShift; $PostFXManager::Settings::HDR::enableToneMapping = $HDRPostFX::enableToneMapping; $PostFXManager::Settings::HDR::gaussMean = $HDRPostFX::gaussMean; $PostFXManager::Settings::HDR::gaussMultiplier = $HDRPostFX::gaussMultiplier; $PostFXManager::Settings::HDR::gaussStdDev = $HDRPostFX::gaussStdDev; $PostFXManager::Settings::HDR::keyValue = $HDRPostFX::keyValue; $PostFXManager::Settings::HDR::minLuminace = $HDRPostFX::minLuminace; $PostFXManager::Settings::HDR::whiteCutoff = $HDRPostFX::whiteCutoff; $PostFXManager::Settings::ColorCorrectionRamp = $HDRPostFX::colorCorrectionRamp; postVerbose("% - PostFX Manager - Settings Saved - HDR"); } function PostFXManager::settingsApplyLightRays(%this) { $PostFXManager::Settings::LightRays::brightScalar = $LightRayPostFX::brightScalar; $PostFXManager::Settings::LightRays::numSamples = $LightRayPostFX::numSamples; $PostFXManager::Settings::LightRays::density = $LightRayPostFX::density; $PostFXManager::Settings::LightRays::weight = $LightRayPostFX::weight; $PostFXManager::Settings::LightRays::decay = $LightRayPostFX::decay; postVerbose("% - PostFX Manager - Settings Saved - Light Rays"); } function PostFXManager::settingsApplyDOF(%this) { $PostFXManager::Settings::DOF::EnableAutoFocus = $DOFPostFx::EnableAutoFocus; $PostFXManager::Settings::DOF::BlurMin = $DOFPostFx::BlurMin; $PostFXManager::Settings::DOF::BlurMax = $DOFPostFx::BlurMax; $PostFXManager::Settings::DOF::FocusRangeMin = $DOFPostFx::FocusRangeMin; $PostFXManager::Settings::DOF::FocusRangeMax = $DOFPostFx::FocusRangeMax; $PostFXManager::Settings::DOF::BlurCurveNear = $DOFPostFx::BlurCurveNear; $PostFXManager::Settings::DOF::BlurCurveFar = $DOFPostFx::BlurCurveFar; postVerbose("% - PostFX Manager - Settings Saved - DOF"); } function PostFXManager::settingsApplyVignette(%this) { $PostFXManager::Settings::Vignette::VMax = $VignettePostEffect::VMax; $PostFXManager::Settings::Vignette::VMin = $VignettePostEffect::VMin; postVerbose("% - PostFX Manager - Settings Saved - Vignette"); } function PostFXManager::settingsApplyAll(%this, %sFrom) { // Apply settings which control if effects are on/off altogether. $PostFXManager::Settings::EnablePostFX = $PostFXManager::PostFX::Enabled; $PostFXManager::Settings::EnableDOF = $PostFXManager::PostFX::EnableDOF; $PostFXManager::Settings::EnableVignette = $PostFXManager::PostFX::EnableVignette; $PostFXManager::Settings::EnableLightRays = $PostFXManager::PostFX::EnableLightRays; $PostFXManager::Settings::EnableHDR = $PostFXManager::PostFX::EnableHDR; $PostFXManager::Settings::EnableSSAO = $PostFXManager::PostFX::EnableSSAO; // Apply settings should save the values in the system to the // the preset structure ($PostFXManager::Settings::*) // SSAO Settings %this.settingsApplySSAO(); // HDR settings %this.settingsApplyHDR(); // Light rays settings %this.settingsApplyLightRays(); // DOF %this.settingsApplyDOF(); // Vignette %this.settingsApplyVignette(); postVerbose("% - PostFX Manager - All Settings applied to $PostFXManager::Settings"); } function PostFXManager::settingsApplyDefaultPreset(%this) { PostFXManager::loadPresetHandler($PostFXManager::defaultPreset); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.ConfigModels; using ContentPatcher.Framework.Patches; using ContentPatcher.Framework.Tokens; using ContentPatcher.Framework.Validators; using Microsoft.Xna.Framework.Graphics; using Pathoschild.Stardew.Common.Utilities; using StardewModdingAPI; using xTile; namespace ContentPatcher.Framework { /// <summary>Manages loaded patches.</summary> internal class PatchManager : IAssetLoader, IAssetEditor { /********* ** Fields *********/ /**** ** State ****/ /// <summary>Manages the available contextual tokens.</summary> private readonly TokenManager TokenManager; /// <summary>Encapsulates monitoring and logging.</summary> private readonly IMonitor Monitor; /// <summary>Handle special validation logic on loaded or edited assets.</summary> private readonly IAssetValidator[] AssetValidators; /// <summary>The patches which are permanently disabled for this session.</summary> private readonly IList<DisabledPatch> PermanentlyDisabledPatches = new List<DisabledPatch>(); /// <summary>The patches to apply.</summary> private readonly SortedSet<IPatch> Patches = new(PatchIndexComparer.Instance); /// <summary>The patches to apply, indexed by token.</summary> private readonly InvariantDictionary<SortedSet<IPatch>> PatchesAffectedByToken = new(); /// <summary>The patches to apply, indexed by asset name.</summary> private readonly InvariantDictionary<SortedSet<IPatch>> PatchesByCurrentTarget = new(); /// <summary>The new patches which haven't received a context update yet.</summary> private readonly HashSet<IPatch> PendingPatches = new(); /// <summary>Assets for which patches were removed, which should be reloaded on the next context update.</summary> private readonly InvariantHashSet AssetsWithRemovedPatches = new(); /// <summary>The token changes queued for periodic update types.</summary> private readonly IDictionary<ContextUpdateType, InvariantHashSet> QueuedTokenChanges = new Dictionary<ContextUpdateType, InvariantHashSet> { [ContextUpdateType.OnTimeChange] = new(), [ContextUpdateType.OnLocationChange] = new(), [ContextUpdateType.All] = new() }; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="tokenManager">Manages the available contextual tokens.</param> /// <param name="assetValidators">Handle special validation logic on loaded or edited assets.</param> public PatchManager(IMonitor monitor, TokenManager tokenManager, IAssetValidator[] assetValidators) { this.Monitor = monitor; this.TokenManager = tokenManager; this.AssetValidators = assetValidators; } /**** ** Patching ****/ /// <inheritdoc /> public bool CanLoad<T>(IAssetInfo asset) { // get load patches IPatch[] patches = this.GetCurrentLoaders(asset).ToArray(); // validate if (patches.Length > 1) { // show simple error for most common cases string[] modNames = patches.Select(p => p.ContentPack.Manifest.Name).Distinct().OrderByHuman().ToArray(); string[] patchNames = patches.Select(p => p.Path.ToString()).OrderByHuman().ToArray(); switch (modNames.Length) { case 1: this.Monitor.Log($"'{modNames[0]}' has multiple patches which load the '{asset.AssetName}' asset at the same time ({string.Join(", ", patchNames)}). None will be applied. You should report this to the content pack author.", LogLevel.Error); break; case 2: this.Monitor.Log($"Two content packs want to load the '{asset.AssetName}' asset ({string.Join(" and ", modNames)}). Neither will be applied. You should remove one of the content packs, or ask the authors about compatibility.", LogLevel.Error); this.Monitor.Log($"Affected patches: {string.Join(", ", patchNames)}"); break; default: this.Monitor.Log($"Multiple content packs want to load the '{asset.AssetName}' asset ({string.Join(", ", modNames)}). None will be applied. You should remove some of the content packs, or ask the authors about compatibility.", LogLevel.Error); this.Monitor.Log($"Affected patches: {string.Join(", ", patchNames)}"); break; } return false; } if (patches.Length == 1 && !patches[0].FromAssetExists()) { this.Monitor.Log($"Can't apply load \"{patches[0].Path}\" to {patches[0].TargetAsset}: the {nameof(PatchConfig.FromFile)} file '{patches[0].FromAsset}' doesn't exist.", LogLevel.Warn); return false; } // return result bool canLoad = patches.Any(); this.Monitor.VerboseLog($"check: [{(canLoad ? "X" : " ")}] can load {asset.AssetName}"); return canLoad; } /// <inheritdoc /> public bool CanEdit<T>(IAssetInfo asset) { bool canEdit = this.GetCurrentEditors(asset).Any(); this.Monitor.VerboseLog($"check: [{(canEdit ? "X" : " ")}] can edit {asset.AssetName}"); return canEdit; } /// <inheritdoc /> public T Load<T>(IAssetInfo asset) { // get applicable patches for context IPatch[] patches = this.GetCurrentLoaders(asset).ToArray(); if (!patches.Any()) throw new InvalidOperationException($"Can't load asset key '{asset.AssetName}' because no patches currently apply. This should never happen because it means validation failed."); if (patches.Length > 1) throw new InvalidOperationException($"Can't load asset key '{asset.AssetName}' because multiple patches apply ({string.Join(", ", from entry in patches.OrderByHuman(p => p.Path.ToString()) select entry.Path)}). This should never happen because it means validation failed."); // apply patch IPatch patch = patches.Single(); if (this.Monitor.IsVerbose) this.Monitor.VerboseLog($"Patch \"{patch.Path}\" loaded {asset.AssetName}."); else this.Monitor.Log($"{patch.ContentPack.Manifest.Name} loaded {asset.AssetName}."); T data = patch.Load<T>(asset); foreach (IAssetValidator validator in this.AssetValidators) { if (!validator.TryValidate(asset, data, patch, out string error)) { this.Monitor.Log($"Can't apply patch {patch.Path} to {asset.AssetName}: {error}.", LogLevel.Error); return default; } } patch.IsApplied = true; return data; } /// <inheritdoc /> public void Edit<T>(IAssetData asset) { IPatch[] patches = this.GetCurrentEditors(asset).ToArray(); if (!patches.Any()) throw new InvalidOperationException($"Can't edit asset key '{asset.AssetName}' because no patches currently apply. This should never happen."); InvariantHashSet loggedContentPacks = new InvariantHashSet(); foreach (IPatch patch in patches) { if (this.Monitor.IsVerbose) this.Monitor.VerboseLog($"Applied patch \"{patch.Path}\" to {asset.AssetName}."); else if (loggedContentPacks.Add(patch.ContentPack.Manifest.Name)) this.Monitor.Log($"{patch.ContentPack.Manifest.Name} edited {asset.AssetName}."); try { patch.Edit<T>(asset); patch.IsApplied = true; } catch (Exception ex) { this.Monitor.Log($"Unhandled exception applying patch: {patch.Path}.\n{ex}", LogLevel.Error); patch.IsApplied = false; } } } /// <summary>Update the current context.</summary> /// <param name="contentHelper">The content helper through which to invalidate assets.</param> /// <param name="globalChangedTokens">The global token values which changed.</param> /// <param name="updateType">The context update type.</param> public void UpdateContext(IContentHelper contentHelper, InvariantHashSet globalChangedTokens, ContextUpdateType updateType) { this.Monitor.VerboseLog($"Updating context for {updateType} tick..."); // Patches can have variable update rates, so we keep track of updated tokens here so // we update patches at their next update point. if (updateType == ContextUpdateType.All) { // all token updates apply at day start globalChangedTokens = new InvariantHashSet(globalChangedTokens); foreach (var tokenQueue in this.QueuedTokenChanges.Values) { globalChangedTokens.AddMany(tokenQueue); tokenQueue.Clear(); } } else { // queue token changes for other update points foreach (KeyValuePair<ContextUpdateType, InvariantHashSet> pair in this.QueuedTokenChanges) { if (pair.Key != updateType) pair.Value.AddMany(globalChangedTokens); } // get queued changes for the current update point globalChangedTokens.AddMany(this.QueuedTokenChanges[updateType]); this.QueuedTokenChanges[updateType].Clear(); } // get changes to apply Queue<IPatch> patchQueue = new Queue<IPatch>(this.GetPatchesToUpdate(globalChangedTokens, updateType)); InvariantHashSet reloadAssetNames = new InvariantHashSet(this.AssetsWithRemovedPatches); if (!patchQueue.Any() && !reloadAssetNames.Any()) return; // reset queued patches // This needs to be done *before* we update patches, to avoid clearing patches added by Include patches IPatch[] wasPending = this.PendingPatches.ToArray(); this.PendingPatches.Clear(); this.AssetsWithRemovedPatches.Clear(); // init for verbose logging List<PatchAuditChange> verbosePatchesReloaded = this.Monitor.IsVerbose ? new() : null; // update patches string prevAssetName = null; HashSet<IPatch> newPatches = new(new ObjectReferenceComparer<IPatch>()); while (patchQueue.Any()) { IPatch patch = patchQueue.Dequeue(); // log asset name if (this.Monitor.IsVerbose && prevAssetName != patch.TargetAsset) { this.Monitor.VerboseLog($" {patch.TargetAsset}:"); prevAssetName = patch.TargetAsset; } // track old values string wasFromAsset = patch.FromAsset; string wasTargetAsset = patch.TargetAsset; bool wasReady = patch.IsReady && !wasPending.Contains(patch); // update patch IContext tokenContext = this.TokenManager.TrackLocalTokens(patch.ContentPack); bool changed; try { changed = patch.UpdateContext(tokenContext); } catch (Exception ex) { this.Monitor.Log($"Patch error: {patch.Path} failed on context update (see log file for details).\n{ex.Message}", LogLevel.Error); this.Monitor.Log(ex.ToString()); changed = false; } bool isReady = patch.IsReady; // handle specific patch types switch (patch.Type) { case PatchType.EditData: // force reindex // This is only needed for EditData patches which use FromFile, since the // loaded file may include tokens which couldn't be analyzed when the patch // was added. This scenario was deprecated in Content Patcher 1.16, when // Include patches were added. if (patch.FromAsset != wasFromAsset) { this.RemovePatchFromIndexes(patch); this.IndexPatch(patch, indexByToken: true); } break; case PatchType.Include: // queue new patches if (patch is IncludePatch { PatchesJustLoaded: not null } include) { foreach (IPatch includedPatch in include.PatchesJustLoaded) { newPatches.Add(includedPatch); patchQueue.Enqueue(includedPatch); } } break; case PatchType.Load: // warn for invalid load patch // Other patch types show an error when they're applied instead, but that's // not possible for a load patch since we can't cleanly abort a load. if (patch is LoadPatch loadPatch && patch.IsReady && !patch.FromAssetExists()) this.Monitor.Log($"Patch error: {patch.Path} has a {nameof(PatchConfig.FromFile)} which matches non-existent file '{loadPatch.FromAsset}'.", LogLevel.Error); break; } // if the patch was just added via Include, it implicitly changed too changed = changed || newPatches.Contains(patch); // track patches to reload bool reloadAsset = isReady != wasReady || (isReady && changed); if (reloadAsset) { patch.IsApplied = false; if (wasReady) reloadAssetNames.Add(wasTargetAsset); if (isReady) reloadAssetNames.Add(patch.TargetAsset); } // log change verbosePatchesReloaded?.Add(new PatchAuditChange(patch, wasReady, wasFromAsset, wasTargetAsset, reloadAsset)); if (this.Monitor.IsVerbose) { IList<string> changes = new List<string>(); if (wasReady != isReady) changes.Add(isReady ? "enabled" : "disabled"); if (wasTargetAsset != patch.TargetAsset) changes.Add($"target: {wasTargetAsset} => {patch.TargetAsset}"); string changesStr = string.Join(", ", changes); this.Monitor.VerboseLog($" [{(isReady ? "X" : " ")}] {patch.Path}: {(changes.Any() ? changesStr : "OK")}"); } } // reset indexes this.Reindex(patchListChanged: false); // log changes if (verbosePatchesReloaded?.Count > 0) { StringBuilder report = new StringBuilder(); report.AppendLine($"{verbosePatchesReloaded.Count} patches were rechecked for {updateType} tick."); foreach (PatchAuditChange entry in verbosePatchesReloaded.OrderByHuman(p => p.Patch.Path.ToString())) { var patch = entry.Patch; List<string> notes = new List<string>(); if (entry.WillInvalidate) { var assetNames = new[] { entry.WasTargetAsset, patch.TargetAsset } .Select(p => p?.Trim()) .Where(p => !string.IsNullOrEmpty(p)) .Distinct(StringComparer.OrdinalIgnoreCase); notes.Add($"invalidates {string.Join(", ", assetNames.OrderByHuman())}"); } if (entry.WasReady != patch.IsReady) notes.Add(patch.IsReady ? "=> ready" : "=> not ready"); if (entry.WasFromAsset != patch.FromAsset) notes.Add($"{nameof(patch.FromAsset)} '{entry.WasFromAsset}' => '{patch.FromAsset}'"); if (entry.WasTargetAsset != patch.TargetAsset) notes.Add($"{nameof(patch.TargetAsset)} '{entry.WasTargetAsset}' => '{patch.TargetAsset}'"); report.AppendLine($" - {patch.Type} {patch.Path}"); foreach (string note in notes) report.AppendLine($" - {note}"); } this.Monitor.Log(report.ToString()); } // reload assets if needed if (reloadAssetNames.Any()) { this.Monitor.VerboseLog($" reloading {reloadAssetNames.Count} assets: {string.Join(", ", reloadAssetNames.OrderByHuman())}"); contentHelper.InvalidateCache(asset => { this.Monitor.VerboseLog($" [{(reloadAssetNames.Contains(asset.AssetName) ? "X" : " ")}] reload {asset.AssetName}"); return reloadAssetNames.Contains(asset.AssetName); }); } } /**** ** Patches ****/ /// <summary>Add a patch.</summary> /// <param name="patch">The patch to add.</param> /// <param name="reindex">Whether to reindex the patch list immediately.</param> public void Add(IPatch patch, bool reindex = true) { // set initial context ModTokenContext modContext = this.TokenManager.TrackLocalTokens(patch.ContentPack); patch.UpdateContext(modContext); // add to patch list this.Monitor.VerboseLog($" added {patch.Type} {patch.TargetAsset}."); this.Patches.Add(patch); this.PendingPatches.Add(patch); // rebuild indexes if (reindex) this.Reindex(patchListChanged: true); } /// <summary>Remove a patch.</summary> /// <param name="patch">The patch to remove.</param> /// <param name="reindex">Whether to reindex the patch list immediately.</param> public void Remove(IPatch patch, bool reindex = true) { // remove from patch list this.Monitor.VerboseLog($" removed {patch.Path}."); if (!this.Patches.Remove(patch)) return; // mark asset to reload if (patch.IsApplied) this.AssetsWithRemovedPatches.Add(patch.TargetAsset); // rebuild indexes if (reindex) this.Reindex(patchListChanged: true); } /// <summary>Rebuild the internal patch lookup indexes. This should only be called manually if patches were added/removed with the reindex option disabled.</summary> /// <param name="patchListChanged">Whether patches were added or removed.</param> public void Reindex(bool patchListChanged) { // reset this.PatchesByCurrentTarget.Clear(); if (patchListChanged) this.PatchesAffectedByToken.Clear(); // reindex foreach (IPatch patch in this.Patches) this.IndexPatch(patch, indexByToken: patchListChanged); } /// <summary>Add a patch that's permanently disabled for this session.</summary> /// <param name="patch">The patch to add.</param> public void AddPermanentlyDisabled(DisabledPatch patch) { this.PermanentlyDisabledPatches.Add(patch); } /// <summary>Get valid patches regardless of context.</summary> public IEnumerable<IPatch> GetPatches() { return this.Patches; } /// <summary>Get valid patches regardless of context.</summary> /// <param name="assetName">The asset name for which to find patches.</param> public IEnumerable<IPatch> GetPatches(string assetName) { if (this.PatchesByCurrentTarget.TryGetValue(assetName, out SortedSet<IPatch> patches)) return patches; return Array.Empty<IPatch>(); } /// <summary>Get all valid patches grouped by their current target value.</summary> public IEnumerable<KeyValuePair<string, IEnumerable<IPatch>>> GetPatchesByTarget() { foreach (KeyValuePair<string, SortedSet<IPatch>> pair in this.PatchesByCurrentTarget) yield return new KeyValuePair<string, IEnumerable<IPatch>>(pair.Key, pair.Value); } /// <summary>Get patches which are permanently disabled for this session, along with the reason they were.</summary> public IEnumerable<DisabledPatch> GetPermanentlyDisabledPatches() { return this.PermanentlyDisabledPatches; } /// <summary>Get patches which load the given asset in the current context.</summary> /// <param name="asset">The asset being intercepted.</param> public IEnumerable<IPatch> GetCurrentLoaders(IAssetInfo asset) { return this .GetPatches(asset.AssetName) .Where(patch => patch.Type == PatchType.Load && patch.IsReady); } /// <summary>Get patches which edit the given asset in the current context.</summary> /// <param name="asset">The asset being intercepted.</param> public IEnumerable<IPatch> GetCurrentEditors(IAssetInfo asset) { PatchType? patchType = this.GetEditType(asset.DataType); if (patchType == null) return Array.Empty<IPatch>(); return this .GetPatches(asset.AssetName) .Where(patch => patch.Type == patchType && patch.IsReady); } /********* ** Private methods *********/ /// <summary>Get the patch type which applies when editing a given asset type.</summary> /// <param name="assetType">The asset type.</param> private PatchType? GetEditType(Type assetType) { if (typeof(Texture2D).IsAssignableFrom(assetType)) return PatchType.EditImage; if (typeof(Map).IsAssignableFrom(assetType)) return PatchType.EditMap; else return PatchType.EditData; } /// <summary>Get the tokens which need a context update.</summary> /// <param name="globalChangedTokens">The global token values which changed.</param> /// <param name="updateType">The context update type.</param> private HashSet<IPatch> GetPatchesToUpdate(InvariantHashSet globalChangedTokens, ContextUpdateType updateType) { // add patches which depend on a changed token var patches = new HashSet<IPatch>(new ObjectReferenceComparer<IPatch>()); foreach (string tokenName in globalChangedTokens) { if (this.PatchesAffectedByToken.TryGetValue(tokenName, out SortedSet<IPatch> affectedPatches)) { foreach (IPatch patch in affectedPatches) { if (updateType == ContextUpdateType.All || patch.UpdateRate.HasFlag((UpdateRate)updateType)) patches.Add(patch); } } } // add uninitialized patches patches.AddMany(this.PendingPatches); return patches; } /// <summary>Add a patch to the lookup indexes.</summary> /// <param name="patch">The patch to index.</param> /// <param name="indexByToken">Whether to also index by tokens used.</param> private void IndexPatch(IPatch patch, bool indexByToken) { // index by target asset if (patch.TargetAsset != null) { if (!this.PatchesByCurrentTarget.TryGetValue(patch.TargetAsset, out SortedSet<IPatch> list)) this.PatchesByCurrentTarget[patch.TargetAsset] = list = new SortedSet<IPatch>(PatchIndexComparer.Instance); list.Add(patch); } // index by tokens used if (indexByToken) { void IndexForToken(string tokenName) { if (!this.PatchesAffectedByToken.TryGetValue(tokenName, out SortedSet<IPatch> affected)) this.PatchesAffectedByToken[tokenName] = affected = new SortedSet<IPatch>(PatchIndexComparer.Instance); affected.Add(patch); } // get mod context ModTokenContext modContext = this.TokenManager.TrackLocalTokens(patch.ContentPack); // get direct tokens InvariantHashSet tokensUsed = new InvariantHashSet(patch.GetTokensUsed().Select(name => this.TokenManager.ResolveAlias(patch.ContentPack.Manifest.UniqueID, name))); foreach (string tokenName in tokensUsed) IndexForToken(tokenName); // get indirect tokens foreach (IToken token in this.TokenManager.GetTokens(enforceContext: false)) { if (!tokensUsed.Contains(token.Name) && modContext.GetTokensAffectedBy(token.Name).Any(name => tokensUsed.Contains(name))) IndexForToken(token.Name); } } } /// <summary>Whether to remove a patch from the indexes. Normally the indexes should be cleared and rebuilt instead; this method should only be used when forcefully reindexing a patch, which is only needed if it couldn't be analyzed when the patch was added, which in turn should only be the case for <see cref="PatchType.EditData"/> patches which use <see cref="PatchConfig.FromFile"/> (which was deprecated in Content Patcher 1.16).</summary> /// <param name="patch">The patch to remove.</param> private void RemovePatchFromIndexes(IPatch patch) { foreach (var lookup in new[] { this.PatchesByCurrentTarget, this.PatchesAffectedByToken }) { foreach (string key in lookup.Keys.ToArray()) { ISet<IPatch> list = lookup[key]; if (list.Contains(patch)) { list.Remove(patch); if (!list.Any()) lookup.Remove(key); } } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Python.Runtime { public class Finalizer { public class CollectArgs : EventArgs { public int ObjectCount { get; set; } } public class ErrorArgs : EventArgs { public Exception Error { get; set; } } public static readonly Finalizer Instance = new Finalizer(); public event EventHandler<CollectArgs> CollectOnce; public event EventHandler<ErrorArgs> ErrorHandler; public int Threshold { get; set; } public bool Enable { get; set; } private ConcurrentQueue<IntPtr> _objQueue = new ConcurrentQueue<IntPtr>(); private int _throttled; #region FINALIZER_CHECK #if FINALIZER_CHECK private readonly object _queueLock = new object(); public bool RefCountValidationEnabled { get; set; } = true; #else public readonly bool RefCountValidationEnabled = false; #endif // Keep these declarations for compat even no FINALIZER_CHECK public class IncorrectFinalizeArgs : EventArgs { public IntPtr Handle { get; internal set; } public ICollection<IntPtr> ImpactedObjects { get; internal set; } } public class IncorrectRefCountException : Exception { public IntPtr PyPtr { get; internal set; } private string _message; public override string Message => _message; public IncorrectRefCountException(IntPtr ptr) { PyPtr = ptr; IntPtr pyname = Runtime.PyObject_Unicode(PyPtr); string name = Runtime.GetManagedString(pyname); Runtime.XDecref(pyname); _message = $"<{name}> may has a incorrect ref count"; } } public delegate bool IncorrectRefCntHandler(object sender, IncorrectFinalizeArgs e); #pragma warning disable 414 public event IncorrectRefCntHandler IncorrectRefCntResolver = null; #pragma warning restore 414 public bool ThrowIfUnhandleIncorrectRefCount { get; set; } = true; #endregion private Finalizer() { Enable = true; Threshold = 200; } public void Collect() => this.DisposeAll(); internal void ThrottledCollect() { _throttled = unchecked(this._throttled + 1); if (!Enable || _throttled < Threshold) return; _throttled = 0; this.Collect(); } internal List<IntPtr> GetCollectedObjects() { return _objQueue.ToList(); } internal void AddFinalizedObject(ref IntPtr obj) { if (!Enable || obj == IntPtr.Zero) { return; } #if FINALIZER_CHECK lock (_queueLock) #endif { this._objQueue.Enqueue(obj); } obj = IntPtr.Zero; } internal static void Shutdown() { Instance.DisposeAll(); } private void DisposeAll() { #if DEBUG // only used for testing CollectOnce?.Invoke(this, new CollectArgs() { ObjectCount = _objQueue.Count }); #endif #if FINALIZER_CHECK lock (_queueLock) #endif { #if FINALIZER_CHECK ValidateRefCount(); #endif IntPtr obj; Runtime.PyErr_Fetch(out var errType, out var errVal, out var traceback); try { while (_objQueue.TryDequeue(out obj)) { Runtime.XDecref(obj); try { Runtime.CheckExceptionOccurred(); } catch (Exception e) { var handler = ErrorHandler; if (handler is null) { throw new FinalizationException( "Python object finalization failed", disposable: obj, innerException: e); } handler.Invoke(this, new ErrorArgs() { Error = e }); } } } finally { // Python requires finalizers to preserve exception: // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation Runtime.PyErr_Restore(errType, errVal, traceback); } } } #if FINALIZER_CHECK private void ValidateRefCount() { if (!RefCountValidationEnabled) { return; } var counter = new Dictionary<IntPtr, long>(); var holdRefs = new Dictionary<IntPtr, long>(); var indexer = new Dictionary<IntPtr, List<IntPtr>>(); foreach (var obj in _objQueue) { var handle = obj; if (!counter.ContainsKey(handle)) { counter[handle] = 0; } counter[handle]++; if (!holdRefs.ContainsKey(handle)) { holdRefs[handle] = Runtime.Refcount(handle); } List<IntPtr> objs; if (!indexer.TryGetValue(handle, out objs)) { objs = new List<IntPtr>(); indexer.Add(handle, objs); } objs.Add(obj); } foreach (var pair in counter) { IntPtr handle = pair.Key; long cnt = pair.Value; // Tracked handle's ref count is larger than the object's holds // it may take an unspecified behaviour if it decref in Dispose if (cnt > holdRefs[handle]) { var args = new IncorrectFinalizeArgs() { Handle = handle, ImpactedObjects = indexer[handle] }; bool handled = false; if (IncorrectRefCntResolver != null) { var funcList = IncorrectRefCntResolver.GetInvocationList(); foreach (IncorrectRefCntHandler func in funcList) { if (func(this, args)) { handled = true; break; } } } if (!handled && ThrowIfUnhandleIncorrectRefCount) { throw new IncorrectRefCountException(handle); } } // Make sure no other references for PyObjects after this method indexer[handle].Clear(); } indexer.Clear(); } #endif } public class FinalizationException : Exception { public IntPtr PythonObject { get; } public FinalizationException(string message, IntPtr disposable, Exception innerException) : base(message, innerException) { if (disposable == IntPtr.Zero) throw new ArgumentNullException(nameof(disposable)); this.PythonObject = disposable; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.LongRunning.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOperationsClientTest { [xunit::FactAttribute] public void GetOperationRequestObject() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); GetOperationRequest request = new GetOperationRequest { Name = "name1c9368b0", }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation response = client.GetOperation(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetOperationRequestObjectAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); GetOperationRequest request = new GetOperationRequest { Name = "name1c9368b0", }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation responseCallSettings = await client.GetOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Operation responseCancellationToken = await client.GetOperationAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetOperation() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); GetOperationRequest request = new GetOperationRequest { Name = "name1c9368b0", }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation response = client.GetOperation(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetOperationAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); GetOperationRequest request = new GetOperationRequest { Name = "name1c9368b0", }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation responseCallSettings = await client.GetOperationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Operation responseCancellationToken = await client.GetOperationAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteOperationRequestObject() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); DeleteOperationRequest request = new DeleteOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); client.DeleteOperation(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteOperationRequestObjectAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); DeleteOperationRequest request = new DeleteOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); await client.DeleteOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteOperationAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteOperation() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); DeleteOperationRequest request = new DeleteOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); client.DeleteOperation(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteOperationAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); DeleteOperationRequest request = new DeleteOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); await client.DeleteOperationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteOperationAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CancelOperationRequestObject() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); CancelOperationRequest request = new CancelOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CancelOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); client.CancelOperation(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CancelOperationRequestObjectAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); CancelOperationRequest request = new CancelOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CancelOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); await client.CancelOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CancelOperationAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CancelOperation() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); CancelOperationRequest request = new CancelOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CancelOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); client.CancelOperation(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CancelOperationAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); CancelOperationRequest request = new CancelOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.CancelOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); await client.CancelOperationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.CancelOperationAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void WaitOperationRequestObject() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); WaitOperationRequest request = new WaitOperationRequest { Name = "name1c9368b0", Timeout = new wkt::Duration(), }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.WaitOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation response = client.WaitOperation(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WaitOperationRequestObjectAsync() { moq::Mock<Operations.OperationsClient> mockGrpcClient = new moq::Mock<Operations.OperationsClient>(moq::MockBehavior.Strict); WaitOperationRequest request = new WaitOperationRequest { Name = "name1c9368b0", Timeout = new wkt::Duration(), }; Operation expectedResponse = new Operation { Name = "name1c9368b0", Metadata = new wkt::Any(), Done = true, Error = new gr::Status(), Response = new wkt::Any(), }; mockGrpcClient.Setup(x => x.WaitOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OperationsClient client = new OperationsClientImpl(mockGrpcClient.Object, null); Operation responseCallSettings = await client.WaitOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Operation responseCancellationToken = await client.WaitOperationAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Web.Security; using Rotativa.Options; namespace Rotativa { public abstract class AsResultBase : ActionResult { protected AsResultBase() { this.WkhtmlPath = string.Empty; this.FormsAuthenticationCookieName = ".ASPXAUTH"; } /// <summary> /// This will be send to the browser as a name of the generated PDF file. /// </summary> public string FileName { get; set; } /// <summary> /// Path to wkhtmltopdf\wkhtmltoimage binary. /// </summary> public string WkhtmlPath { get; set; } /// <summary> /// Custom name of authentication cookie used by forms authentication. /// </summary> [Obsolete("Use FormsAuthenticationCookieName instead of CookieName.")] public string CookieName { get { return this.FormsAuthenticationCookieName; } set { this.FormsAuthenticationCookieName = value; } } /// <summary> /// Custom name of authentication cookie used by forms authentication. /// </summary> public string FormsAuthenticationCookieName { get; set; } /// <summary> /// Sets custom headers. /// </summary> [OptionFlag("--custom-header")] public Dictionary<string, string> CustomHeaders { get; set; } /// <summary> /// Sets cookies. /// </summary> [OptionFlag("--cookie")] public Dictionary<string, string> Cookies { get; set; } /// <summary> /// Sets post values. /// </summary> [OptionFlag("--post")] public Dictionary<string, string> Post { get; set; } /// <summary> /// Indicates whether the page can run JavaScript. /// </summary> [OptionFlag("-n")] public bool IsJavaScriptDisabled { get; set; } /// <summary> /// Minimum font size. /// </summary> [OptionFlag("--minimum-font-size")] public int? MinimumFontSize { get; set; } /// <summary> /// Sets proxy server. /// </summary> [OptionFlag("-p")] public string Proxy { get; set; } /// <summary> /// HTTP Authentication username. /// </summary> [OptionFlag("--username")] public string UserName { get; set; } /// <summary> /// HTTP Authentication password. /// </summary> [OptionFlag("--password")] public string Password { get; set; } /// <summary> /// Use this if you need another switches that are not currently supported by Rotativa. /// </summary> [OptionFlag("")] public string CustomSwitches { get; set; } [Obsolete(@"Use BuildFile(this.ControllerContext) method instead and use the resulting binary data to do what needed.")] public string SaveOnServerPath { get; set; } protected abstract string GetUrl(HttpContext context); /// <summary> /// Returns properties with OptionFlag attribute as one line that can be passed to wkhtmltopdf binary. /// </summary> /// <returns>Command line parameter that can be directly passed to wkhtmltopdf binary.</returns> protected virtual string GetConvertOptions() { var result = new StringBuilder(); var fields = this.GetType().GetProperties(); foreach (var fi in fields) { var of = fi.GetCustomAttributes(typeof(OptionFlag), true).FirstOrDefault() as OptionFlag; if (of == null) continue; object value = fi.GetValue(this, null); if (value == null) continue; if (fi.PropertyType == typeof(Dictionary<string, string>)) { var dictionary = (Dictionary<string, string>)value; foreach (var d in dictionary) { result.AppendFormat(" {0} {1} {2}", of.Name, d.Key, d.Value); } } else if (fi.PropertyType == typeof(bool)) { if ((bool)value) result.AppendFormat(CultureInfo.InvariantCulture, " {0}", of.Name); } else { result.AppendFormat(CultureInfo.InvariantCulture, " {0} {1}", of.Name, value); } } return result.ToString().Trim(); } private string GetWkParams(ControllerContext context = null) { var httpContext = HttpContext.Current; var switches = string.Empty; HttpCookie authenticationCookie = null; if (httpContext != null && httpContext.Request.Cookies != null && httpContext.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) { authenticationCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; } if (authenticationCookie != null) { var authCookieValue = authenticationCookie.Value; switches += " --cookie " + this.FormsAuthenticationCookieName + " " + authCookieValue; } switches += " " + this.GetConvertOptions(); var url = this.GetUrl(httpContext); switches += " " + url; return switches; } protected virtual byte[] CallTheDriver(ControllerContext context = null) { var switches = this.GetWkParams(context); var fileContent = this.WkhtmlConvert(switches); return fileContent; } protected abstract byte[] WkhtmlConvert(string switches); public byte[] BuildFile(ControllerContext context = null) { if (this.WkhtmlPath == string.Empty) this.WkhtmlPath = context == null ? HttpContext.Current.Server.MapPath("~/Rotativa") : context.HttpContext.Server.MapPath("~/Rotativa"); var fileContent = this.CallTheDriver(context); if (string.IsNullOrEmpty(this.SaveOnServerPath) == false) { File.WriteAllBytes(this.SaveOnServerPath, fileContent); } return fileContent; } public override void ExecuteResult(ControllerContext context) { var fileContent = this.BuildFile(context); var response = this.PrepareResponse(context.HttpContext.Response); response.OutputStream.Write(fileContent, 0, fileContent.Length); } private static string SanitizeFileName(string name) { string invalidChars = Regex.Escape(new string(Path.GetInvalidPathChars()) + new string(Path.GetInvalidFileNameChars())); string invalidCharsPattern = string.Format(@"[{0}]+", invalidChars); string result = Regex.Replace(name, invalidCharsPattern, "_"); return result; } protected HttpResponseBase PrepareResponse(HttpResponseBase response) { response.ContentType = this.GetContentType(); if (!String.IsNullOrEmpty(this.FileName)) response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", SanitizeFileName(this.FileName))); response.AddHeader("Content-Type", this.GetContentType()); return response; } protected abstract string GetContentType(); } }
// 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 TCulture { /// <summary> /// Culture: A specific culture /// Note: On cultures with a true for Valid can be set to a thread /// The true value is specifing the language as culture specific /// </summary> class Culture { private string strCultureName; private int intCultureID; private string strLanguage; private bool bValid; public Culture(string CN, int ID, string L, bool V) { strCultureName = CN; intCultureID = Convert.ToInt32(ID); strLanguage = L; bValid = V; } public string CultureName(){ return strCultureName; } public string Language(){ return strLanguage; } public int CultureID(){ return intCultureID; } public bool Valid(){ return bValid; } } public class CultureNames { private Culture[] cultures; public CultureNames() { CN_Setup(); } public int GetLength(){ return cultures.Length; } public string GetName(int i){ return cultures[i].CultureName(); } public string GetLanguage(int i){ return cultures[i].Language(); } public int GetID(int i){ return cultures[i].CultureID(); } public bool Valid(int i){ return cultures[i].Valid(); } private void CN_Setup() { cultures = new Culture[191]; cultures[0] = new Culture("",0x007F,"invariant culture",true); cultures[1] = new Culture("af",0x0036,"Afrikaans",true); cultures[2] = new Culture("af-ZA",0x0436,"Afrikaans - South Africa",true); cultures[3] = new Culture("sq",0x001C,"Albanian",true); cultures[4] = new Culture("sq-AL",0x041C,"Albanian - Albania",true); cultures[5] = new Culture("ar",0x0001,"Arabic",true); cultures[6] = new Culture("ar-DZ",0x1401,"Arabic - Algeria",true); cultures[7] = new Culture("ar-BH",0x3C01,"Arabic - Bahrain",true); cultures[8] = new Culture("ar-EG",0x0C01,"Arabic - Egypt",true); cultures[9] = new Culture("ar-IQ",0x0801,"Arabic - Iraq",true); cultures[10] = new Culture("ar-JO",0x2C01,"Arabic - Jordan",true); cultures[11] = new Culture("ar-KW",0x3401,"Arabic - Kuwait",true); cultures[12] = new Culture("ar-LB",0x3001,"Arabic - Lebanon",true); cultures[13] = new Culture("ar-LY",0x1001,"Arabic - Libya",true); cultures[14] = new Culture("ar-MA",0x1801,"Arabic - Morocco",true); cultures[15] = new Culture("ar-OM",0x2001,"Arabic - Oman",true); cultures[16] = new Culture("ar-QA",0x4001,"Arabic - Qatar",true); cultures[17] = new Culture("ar-SA",0x0401,"Arabic - Saudi Arabia",true); cultures[18] = new Culture("ar-SY",0x2801,"Arabic - Syria",true); cultures[19] = new Culture("ar-TN",0x1C01,"Arabic - Tunisia",true); cultures[20] = new Culture("ar-AE",0x3801,"Arabic - United Arab Emirates",true); cultures[21] = new Culture("ar-YE",0x2401,"Arabic - Yemen",true); cultures[22] = new Culture("hy",0x002B,"Armenian",true); cultures[23] = new Culture("hy-AM",0x042B,"Armenian - Armenia",true); cultures[24] = new Culture("az",0x002C,"Azeri",true); cultures[25] = new Culture("az-Cyrl-AZ",0x082C,"Azeri (Cyrillic) - Azerbaijan",true); cultures[26] = new Culture("az-Latn-AZ",0x042C,"Azeri (Latin) - Azerbaijan",true); cultures[27] = new Culture("eu",0x002D,"Basque",true); cultures[28] = new Culture("eu-ES",0x042D,"Basque - Basque",true); cultures[29] = new Culture("be",0x0023,"Belarusian",true); cultures[30] = new Culture("be-BY",0x0423,"Belarusian - Belarus",true); cultures[31] = new Culture("bg",0x0002,"Bulgarian",true); cultures[32] = new Culture("bg-BG",0x0402,"Bulgarian - Bulgaria",true); cultures[33] = new Culture("ca",0x0003,"Catalan",true); cultures[34] = new Culture("ca-ES",0x0403,"Catalan - Catalan",true); cultures[35] = new Culture("hr",0x001A,"Croatian",true); cultures[36] = new Culture("hr-HR",0x041A,"Croatian - Croatia",true); cultures[37] = new Culture("cs",0x0005,"Czech",true); cultures[38] = new Culture("cs-CZ",0x0405,"Czech - Czech Republic",true); cultures[39] = new Culture("da",0x0006,"Danish",true); cultures[40] = new Culture("da-DK",0x0406,"Danish - Denmark",true); cultures[41] = new Culture("dv",0x0065,"Dhivehi",true); cultures[42] = new Culture("dv-MV",0x0465,"Dhivehi - Maldives",true); cultures[43] = new Culture("nl",0x0013,"Dutch",true); cultures[44] = new Culture("nl-BE",0x0813,"Dutch - Belgium",true); cultures[45] = new Culture("nl-NL",0x0413,"Dutch - The Netherlands",true); cultures[46] = new Culture("en",0x0009,"English",true); cultures[47] = new Culture("en-AU",0x0C09,"English - Australia",true); cultures[48] = new Culture("en-BZ",0x2809,"English - Belize",true); cultures[49] = new Culture("en-CA",0x1009,"English - Canada",true); cultures[50] = new Culture("en-029",0x2409,"English - Caribbean",true); cultures[51] = new Culture("en-IE",0x1809,"English - Ireland",true); cultures[52] = new Culture("en-JM",0x2009,"English - Jamaica",true); cultures[53] = new Culture("en-NZ",0x1409,"English - New Zealand",true); cultures[54] = new Culture("en-PH",0x3409,"English - Philippines",true); cultures[55] = new Culture("en-ZA",0x1C09,"English - South Africa",true); cultures[56] = new Culture("en-TT",0x2C09,"English - Trinidad and Tobago",true); cultures[57] = new Culture("en-GB",0x0809,"English - United Kingdom",true); cultures[58] = new Culture("en-US",0x0409,"English - United States",true); cultures[59] = new Culture("en-ZW",0x3009,"English - Zimbabwe",true); cultures[60] = new Culture("et",0x0025,"Estonian",true); cultures[61] = new Culture("et-EE",0x0425,"Estonian - Estonia",true); cultures[62] = new Culture("fo",0x0038,"Faroese",true); cultures[63] = new Culture("fo-FO",0x0438,"Faroese - Faroe Islands",true); cultures[64] = new Culture("fa",0x0029,"Farsi",true); cultures[65] = new Culture("fa-IR",0x0429,"Farsi - Iran",true); cultures[66] = new Culture("fi",0x000B,"Finnish",true); cultures[67] = new Culture("fi-FI",0x040B,"Finnish - Finland",true); cultures[68] = new Culture("fr",0x000C,"French",true); cultures[69] = new Culture("fr-BE",0x080C,"French - Belgium",true); cultures[70] = new Culture("fr-CA",0x0C0C,"French - Canada",true); cultures[71] = new Culture("fr-FR",0x040C,"French - France",true); cultures[72] = new Culture("fr-LU",0x140C,"French - Luxembourg",true); cultures[73] = new Culture("fr-MC",0x180C,"French - Monaco",true); cultures[74] = new Culture("fr-CH",0x100C,"French - Switzerland",true); cultures[75] = new Culture("gl",0x0056,"Galician",true); cultures[76] = new Culture("gl-ES",0x0456,"Galician - Galician",true); cultures[77] = new Culture("ka",0x0037,"Georgian",true); cultures[78] = new Culture("ka-GE",0x0437,"Georgian - Georgia",true); cultures[79] = new Culture("de",0x0007,"German",true); cultures[80] = new Culture("de-AT",0x0C07,"German - Austria",true); cultures[81] = new Culture("de-DE",0x0407,"German - Germany",true); cultures[82] = new Culture("de-LI",0x1407,"German - Liechtenstein",true); cultures[83] = new Culture("de-LU",0x1007,"German - Luxembourg",true); cultures[84] = new Culture("de-CH",0x0807,"German - Switzerland",true); cultures[85] = new Culture("el",0x0008,"Greek",true); cultures[86] = new Culture("el-GR",0x0408,"Greek - Greece",true); cultures[87] = new Culture("gu",0x0047,"Gujarati",true); cultures[88] = new Culture("gu-IN",0x0447,"Gujarati - India",true); cultures[89] = new Culture("he",0x000D,"Hebrew",true); cultures[90] = new Culture("he-IL",0x040D,"Hebrew - Israel",true); cultures[91] = new Culture("hi",0x0039,"Hindi",true); cultures[92] = new Culture("hi-IN",0x0439,"Hindi - India",true); cultures[93] = new Culture("hu",0x000E,"Hungarian",true); cultures[94] = new Culture("hu-HU",0x040E,"Hungarian - Hungary",true); cultures[95] = new Culture("is",0x000F,"Icelandic",true); cultures[96] = new Culture("is-IS",0x040F,"Icelandic - Iceland",true); cultures[97] = new Culture("id",0x0021,"Indonesian",true); cultures[98] = new Culture("id-ID",0x0421,"Indonesian - Indonesia",true); cultures[99] = new Culture("it",0x0010,"Italian",true); cultures[100] = new Culture("it-IT",0x0410,"Italian - Italy",true); cultures[101] = new Culture("it-CH",0x0810,"Italian - Switzerland",true); cultures[102] = new Culture("kn",0x004B,"Kannada",true); cultures[103] = new Culture("kn-IN",0x044B,"Kannada - India",true); cultures[104] = new Culture("kk",0x003F,"Kazakh",true); cultures[105] = new Culture("kk-KZ",0x043F,"Kazakh - Kazakhstan",true); cultures[106] = new Culture("kok",0x0057,"Konkani",true); cultures[107] = new Culture("kok-IN",0x0457,"Konkani - India",true); cultures[108] = new Culture("ky",0x0040,"Kyrgyz",true); cultures[109] = new Culture("ky-KG",0x0440,"Kyrgyz - Kazakhstan",true); cultures[110] = new Culture("lv",0x0026,"Latvian",true); cultures[111] = new Culture("lv-LV",0x0426,"Latvian - Latvia",true); cultures[112] = new Culture("lt",0x0027,"Lithuanian",true); cultures[113] = new Culture("lt-LT",0x0427,"Lithuanian - Lithuania",true); cultures[114] = new Culture("mk",0x002F,"Macedonian",true); cultures[115] = new Culture("mk-MK",0x042F,"Macedonian - FYROM",true); cultures[116] = new Culture("ms",0x003E,"Malay",true); cultures[117] = new Culture("ms-BN",0x083E,"Malay - Brunei",true); cultures[118] = new Culture("ms-MY",0x043E,"Malay - Malaysia",true); cultures[119] = new Culture("mr",0x004E,"Marathi",true); cultures[120] = new Culture("mr-IN",0x044E,"Marathi - India",true); cultures[121] = new Culture("mn",0x0050,"Mongolian",true); cultures[122] = new Culture("mn-MN",0x0450,"Mongolian - Mongolia",true); cultures[123] = new Culture("no",0x0014,"Norwegian",true); cultures[124] = new Culture("nb-NO",0x0414,"Norwegian (Bokm\u00e5l) - Norway",true); cultures[125] = new Culture("nn-NO",0x0814,"Norwegian (Nynorsk) - Norway",true); cultures[126] = new Culture("pl",0x0015,"Polish",true); cultures[127] = new Culture("pl-PL",0x0415,"Polish - Poland",true); cultures[128] = new Culture("pt",0x0016,"Portuguese",true); cultures[129] = new Culture("pt-BR",0x0416,"Portuguese - Brazil",true); cultures[130] = new Culture("pt-PT",0x0816,"Portuguese - Portugal",true); cultures[131] = new Culture("pa",0x0046,"Punjabi",true); cultures[132] = new Culture("pa-IN",0x0446,"Punjabi - India",true); cultures[133] = new Culture("ro",0x0018,"Romanian",true); cultures[134] = new Culture("ro-RO",0x0418,"Romanian - Romania",true); cultures[135] = new Culture("ru",0x0019,"Russian",true); cultures[136] = new Culture("ru-RU",0x0419,"Russian - Russia",true); cultures[137] = new Culture("sa",0x004F,"Sanskrit",true); cultures[138] = new Culture("sa-IN",0x044F,"Sanskrit - India",true); cultures[139] = new Culture("sr-Cyrl-CS",0x0C1A,"Serbian (Cyrillic) - Serbia",true); cultures[140] = new Culture("sr-Latn-CS",0x081A,"Serbian (Latin) - Serbia",true); cultures[141] = new Culture("sk",0x001B,"Slovak",true); cultures[142] = new Culture("sk-SK",0x041B,"Slovak - Slovakia",true); cultures[143] = new Culture("sl",0x0024,"Slovenian",true); cultures[144] = new Culture("sl-SI",0x0424,"Slovenian - Slovenia",true); cultures[145] = new Culture("es",0x000A,"Spanish",true); cultures[146] = new Culture("es-AR",0x2C0A,"Spanish - Argentina",true); cultures[147] = new Culture("es-BO",0x400A,"Spanish - Bolivia",true); cultures[148] = new Culture("es-CL",0x340A,"Spanish - Chile",true); cultures[149] = new Culture("es-CO",0x240A,"Spanish - Colombia",true); cultures[150] = new Culture("es-CR",0x140A,"Spanish - Costa Rica",true); cultures[151] = new Culture("es-DO",0x1C0A,"Spanish - Dominican Republic",true); cultures[152] = new Culture("es-EC",0x300A,"Spanish - Ecuador",true); cultures[153] = new Culture("es-SV",0x440A,"Spanish - El Salvador",true); cultures[154] = new Culture("es-GT",0x100A,"Spanish - Guatemala",true); cultures[155] = new Culture("es-HN",0x480A,"Spanish - Honduras",true); cultures[156] = new Culture("es-MX",0x080A,"Spanish - Mexico",true); cultures[157] = new Culture("es-NI",0x4C0A,"Spanish - Nicaragua",true); cultures[158] = new Culture("es-PA",0x180A,"Spanish - Panama",true); cultures[159] = new Culture("es-PY",0x3C0A,"Spanish - Paraguay",true); cultures[160] = new Culture("es-PE",0x280A,"Spanish - Peru",true); cultures[161] = new Culture("es-PR",0x500A,"Spanish - Puerto Rico",true); cultures[162] = new Culture("es-ES",0x0C0A,"Spanish - Spain",true); cultures[163] = new Culture("es-UY",0x380A,"Spanish - Uruguay",true); cultures[164] = new Culture("es-VE",0x200A,"Spanish - Venezuela",true); cultures[165] = new Culture("sw",0x0041,"Swahili",true); cultures[166] = new Culture("sw-KE",0x0441,"Swahili - Kenya",true); cultures[167] = new Culture("sv",0x001D,"Swedish",true); cultures[168] = new Culture("sv-FI",0x081D,"Swedish - Finland",true); cultures[169] = new Culture("sv-SE",0x041D,"Swedish - Sweden",true); cultures[170] = new Culture("syr",0x005A,"Syriac",true); cultures[171] = new Culture("syr-SY",0x045A,"Syriac - Syria",true); cultures[172] = new Culture("ta",0x0049,"Tamil",true); cultures[173] = new Culture("ta-IN",0x0449,"Tamil - India",true); cultures[174] = new Culture("tt",0x0044,"Tatar",true); cultures[175] = new Culture("tt-RU",0x0444,"Tatar - Russia",true); cultures[176] = new Culture("te",0x004A,"Telugu",true); cultures[177] = new Culture("te-IN",0x044A,"Telugu - India",true); cultures[178] = new Culture("th",0x001E,"Thai",true); cultures[179] = new Culture("th-TH",0x041E,"Thai - Thailand",true); cultures[180] = new Culture("tr",0x001F,"Turkish",true); cultures[181] = new Culture("tr-TR",0x041F,"Turkish - Turkey",true); cultures[182] = new Culture("uk",0x0022,"Ukrainian",true); cultures[183] = new Culture("uk-UA",0x0422,"Ukrainian - Ukraine",true); cultures[184] = new Culture("ur",0x0020,"Urdu",true); cultures[185] = new Culture("ur-PK",0x0420,"Urdu - Pakistan",true); cultures[186] = new Culture("uz",0x0043,"Uzbek",true); cultures[187] = new Culture("uz-Cyrl-UZ",0x0843,"Uzbek (Cyrillic) - Uzbekistan",true); cultures[188] = new Culture("uz-Latn-UZ",0x0443,"Uzbek (Latin) - Uzbekistan",true); cultures[189] = new Culture("vi",0x002A,"Vietnamese",true); cultures[190] = new Culture("vi-VN",0x042A,"Vietnamese - Vietnam",true); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class CtorIntHybridDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { HybridDictionary hd; const int BIG_LENGTH = 100; string[] valuesLong = new string[BIG_LENGTH]; string[] keysLong = new string[BIG_LENGTH]; int len; for (int i = 0; i < BIG_LENGTH; i++) { valuesLong[i] = "Item" + i; keysLong[i] = "keY" + i; } // [] HybridDictionary is constructed as expected //----------------------------------------------------------------- hd = new HybridDictionary(0); if (hd == null) { Assert.False(true, string.Format("Error, dictionary is null after default ctor")); } if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count)); } if (hd["key"] != null) { Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor")); } System.Collections.ICollection keys = hd.Keys; if (keys.Count != 0) { Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count)); } System.Collections.ICollection values = hd.Values; if (values.Count != 0) { Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count)); } // // [] Add(string, string) // hd.Add("Name", "Value"); if (hd.Count != 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count)); } if (String.Compare(hd["Name"].ToString(), "Value") != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value")); } // by default should be case sensitive if (hd["NAME"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key")); } // // [] Clear() short dictionary // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } if (hd["Name"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()")); } // // [] numerous Add(string, string) // len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value", i)); } if (hd[keysLong[i].ToUpper()] != null) { Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i)); } } // // [] Clear() dictionary with many entires // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } // // [] few elements not overriding Equals() // hd.Clear(); Hashtable[] lbls = new Hashtable[2]; ArrayList[] bs = new ArrayList[2]; lbls[0] = new Hashtable(); lbls[1] = new Hashtable(); bs[0] = new ArrayList(); bs[1] = new ArrayList(); hd.Add(lbls[0], bs[0]); hd.Add(lbls[1], bs[1]); if (hd.Count != 2) { Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count)); } if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } if (!hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, doesn't contain 2nd special item")); } if (hd.Values.Count != 2) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count)); } hd.Remove(lbls[1]); if (hd.Count != 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // // [] many elements not overriding Equals() // hd.Clear(); lbls = new Hashtable[BIG_LENGTH]; bs = new ArrayList[BIG_LENGTH]; for (int i = 0; i < BIG_LENGTH; i++) { lbls[i] = new Hashtable(); bs[i] = new ArrayList(); hd.Add(lbls[i], bs[i]); } if (hd.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH)); } for (int i = 0; i < BIG_LENGTH; i++) { if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } } if (hd.Values.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH)); } hd.Remove(lbls[0]); if (hd.Count != BIG_LENGTH - 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // -------------------------------------------------------------- // [] Capacity 10 // -------------------------------------------------------------- hd = new HybridDictionary(10); if (hd == null) { Assert.False(true, string.Format("Error, dictionary is null after default ctor")); } if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count)); } if (hd["key"] != null) { Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor")); } keys = hd.Keys; if (keys.Count != 0) { Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count)); } values = hd.Values; if (values.Count != 0) { Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count)); } // // [] Add(string, string) // hd.Add("Name", "Value"); if (hd.Count != 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count)); } if (String.Compare(hd["Name"].ToString(), "Value") != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value")); } // by default should be case sensitive if (hd["NAME"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key")); } // // [] Clear() short dictionary // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } if (hd["Name"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()")); } // // [] numerous Add(string, string) // len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value", i)); } if (hd[keysLong[i].ToUpper()] != null) { Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i)); } } // // [] Clear() long dictionary // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } // // [] few elements not overriding Equals() // hd.Clear(); lbls = new Hashtable[2]; bs = new ArrayList[2]; lbls[0] = new Hashtable(); lbls[1] = new Hashtable(); bs[0] = new ArrayList(); bs[1] = new ArrayList(); hd.Add(lbls[0], bs[0]); hd.Add(lbls[1], bs[1]); if (hd.Count != 2) { Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count)); } if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } if (!hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, doesn't contain 2nd special item")); } if (hd.Values.Count != 2) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count)); } hd.Remove(lbls[1]); if (hd.Count != 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // // [] many elements not overriding Equals() // hd.Clear(); lbls = new Hashtable[BIG_LENGTH]; bs = new ArrayList[BIG_LENGTH]; for (int i = 0; i < BIG_LENGTH; i++) { lbls[i] = new Hashtable(); bs[i] = new ArrayList(); hd.Add(lbls[i], bs[i]); } if (hd.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH)); } for (int i = 0; i < BIG_LENGTH; i++) { if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } } if (hd.Values.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH)); } hd.Remove(lbls[0]); if (hd.Count != BIG_LENGTH - 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // -------------------------------------------------------------- // [] Capacity 100 // -------------------------------------------------------------- hd = new HybridDictionary(100); if (hd == null) { Assert.False(true, string.Format("Error, dictionary is null after default ctor")); } if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count)); } if (hd["key"] != null) { Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor")); } keys = hd.Keys; if (keys.Count != 0) { Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count)); } values = hd.Values; if (values.Count != 0) { Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count)); } // // [] Add(string, string) // hd.Add("Name", "Value"); if (hd.Count != 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count)); } if (String.Compare(hd["Name"].ToString(), "Value") != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value")); } // by default should be case sensitive if (hd["NAME"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key")); } // // [] Clear() short dictionary // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } if (hd["Name"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()")); } // // [] numerous Add(string, string) // len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value", i)); } if (hd[keysLong[i].ToUpper()] != null) { Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i)); } } // // [] Clear() long dictionary // hd.Clear(); if (hd.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count)); } // // [] few elements not overriding Equals() // hd.Clear(); lbls = new Hashtable[2]; bs = new ArrayList[2]; lbls[0] = new Hashtable(); lbls[1] = new Hashtable(); bs[0] = new ArrayList(); bs[1] = new ArrayList(); hd.Add(lbls[0], bs[0]); hd.Add(lbls[1], bs[1]); if (hd.Count != 2) { Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count)); } if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } if (!hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, doesn't contain 2nd special item")); } if (hd.Values.Count != 2) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count)); } hd.Remove(lbls[1]); if (hd.Count != 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[1])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // // [] many elements not overriding Equals() // hd.Clear(); lbls = new Hashtable[BIG_LENGTH]; bs = new ArrayList[BIG_LENGTH]; for (int i = 0; i < BIG_LENGTH; i++) { lbls[i] = new Hashtable(); bs[i] = new ArrayList(); hd.Add(lbls[i], bs[i]); } if (hd.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH)); } for (int i = 0; i < BIG_LENGTH; i++) { if (!hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } } if (hd.Values.Count != BIG_LENGTH) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH)); } hd.Remove(lbls[0]); if (hd.Count != BIG_LENGTH - 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (hd.Contains(lbls[0])) { Assert.False(true, string.Format("Error, failed to remove special item")); } // if Capacity is < 6, it's ignored - ListDictionary doesn't have capacity ctor hd = new HybridDictionary(-1); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Xml; using System.Diagnostics; using Smrf.AppLib; namespace Smrf.XmlLib { //***************************************************************************** // Class: XmlUtil2 // /// <summary> /// XML utility methods. /// </summary> /// /// <remarks> /// This class contains utility methods for dealing with XML. All methods are /// static. /// /// <para> /// This is an improved replacement for XmlUtil, which should not be used in /// new projects. /// </para> /// /// </remarks> //***************************************************************************** public static class XmlUtil2 { //************************************************************************* // Method: SelectRequiredSingleNode() // /// <summary> /// Selects a required XML node. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <returns> /// The selected node. /// </returns> /// /// <remarks> /// If the specified node is missing, an XmlException is thrown. /// </remarks> //************************************************************************* public static XmlNode SelectRequiredSingleNode ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); XmlNode oSelectedNode; if ( !TrySelectSingleNode(node, xPath, xmlNamespaceManager, out oSelectedNode) ) { throw new XmlException( String.Format( "An XML node with the name \"{0}\" is missing a required" + " descendent node. The XPath is \"{1}\"." , node.Name, xPath ) ); } return (oSelectedNode); } //************************************************************************* // Method: SelectRequiredSingleNodeAsString() // /// <summary> /// Selects a required XML node and gets its String value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <returns> /// The selected node's String value. /// </returns> /// /// <remarks> /// If the specified node is missing or its value is an empty string, an /// XmlException is thrown. /// </remarks> //************************************************************************* public static String SelectRequiredSingleNodeAsString ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); String sValue; if ( !TrySelectSingleNodeAsString(node, xPath, xmlNamespaceManager, out sValue) ) { throw new XmlException( String.Format( "An XML node with the name \"{0}\" is missing a required" + " descendent node whose value must be a non-empty String." + " The XPath is \"{1}\"." , node.Name, xPath ) ); } return (sValue); } //************************************************************************* // Method: SelectRequiredSingleNodeAsInt32() // /// <summary> /// Selects a required XML node and gets its Int32 value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <returns> /// The selected node's Int32 value. /// </returns> /// /// <remarks> /// If the specified node is missing or its value isn't an Int32, an /// XmlException is thrown. /// </remarks> //************************************************************************* public static Int32 SelectRequiredSingleNodeAsInt32 ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); Int32 iValue; if ( !TrySelectSingleNodeAsInt32(node, xPath, xmlNamespaceManager, out iValue) ) { throw new XmlException( String.Format( "An XML node with the name \"{0}\" is missing a required" + " descendent node whose value must be an Int32. The XPath" + " is \"{1}\"." , node.Name, xPath ) ); } return (iValue); } //************************************************************************* // Method: SelectRequiredSingleNodeAsDouble() // /// <summary> /// Selects a required XML node and gets its Double value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <returns> /// The selected node's Double value. /// </returns> /// /// <remarks> /// If the specified node is missing or its value isn't a Double, an /// XmlException is thrown. /// </remarks> //************************************************************************* public static Double SelectRequiredSingleNodeAsDouble ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); Double dValue; if ( !TrySelectSingleNodeAsDouble(node, xPath, xmlNamespaceManager, out dValue) ) { throw new XmlException( String.Format( "An XML node with the name \"{0}\" is missing a required" + " descendent node whose value must be a Double. The XPath" + " is \"{1}\"." , node.Name, xPath ) ); } return (dValue); } //************************************************************************* // Method: SelectRequiredSingleNodeAsBoolean() // /// <summary> /// Selects a required XML node and gets its Boolean value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <returns> /// The selected node's Boolean value. /// </returns> /// /// <remarks> /// If the specified node is missing or its value isn't a Boolean, an /// XmlException is thrown. /// </remarks> //************************************************************************* public static Boolean SelectRequiredSingleNodeAsBoolean ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); Boolean bValue; if ( !TrySelectSingleNodeAsBoolean(node, xPath, xmlNamespaceManager, out bValue) ) { throw new XmlException( String.Format( "An XML node with the name \"{0}\" is missing a required" + " descendent node whose value must be a Boolean. The XPath" + " is \"{1}\"." , node.Name, xPath ) ); } return (bValue); } //************************************************************************* // Method: TrySelectSingleNode() // /// <summary> /// Attempts to select an XML node. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="selectedNode"> /// Where the selected node gets stored if true is returned. /// </param> /// /// <returns> /// true if the specified node was found. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNode ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out XmlNode selectedNode ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); selectedNode = null; if (xmlNamespaceManager != null) { selectedNode = node.SelectSingleNode(xPath, xmlNamespaceManager); } else { selectedNode = node.SelectSingleNode(xPath); } return (selectedNode != null); } //************************************************************************* // Method: TrySelectSingleNodeAsString() // /// <summary> /// Attempts to select an XML node and get its String value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="value"> /// Where the selected node's String value gets stored if true is returned. /// If false is returned, this gets set to null. /// </param> /// /// <returns> /// true if the specified node was found and its value was a non-empty /// string. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNodeAsString ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out String value ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); value = null; XmlNode oSelectedNode; if ( !TrySelectSingleNode(node, xPath, xmlNamespaceManager, out oSelectedNode) ) { return (false); } value = oSelectedNode.Value; return ( !String.IsNullOrEmpty(value) ); } //************************************************************************* // Method: TrySelectSingleNodeAsInt32() // /// <summary> /// Attempts to select an XML node and get its Int32 value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="value"> /// Where the selected node's Int32 value gets stored if true is returned. /// </param> /// /// <returns> /// true if the specified node was found and its value was an Int32. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNodeAsInt32 ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out Int32 value ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); value = Int32.MinValue; String sValue; return ( TrySelectSingleNodeAsString(node, xPath, xmlNamespaceManager, out sValue) && MathUtil.TryParseCultureInvariantInt32(sValue, out value) ); } //************************************************************************* // Method: TrySelectSingleNodeAsUInt32() // /// <summary> /// Attempts to select an XML node and get its UInt32 value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="value"> /// Where the selected node's UInt32 value gets stored if true is returned. /// </param> /// /// <returns> /// true if the specified node was found and its value was a UInt32. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNodeAsUInt32 ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out UInt32 value ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); value = UInt32.MinValue; String sValue; return ( TrySelectSingleNodeAsString(node, xPath, xmlNamespaceManager, out sValue) && MathUtil.TryParseCultureInvariantUInt32(sValue, out value) ); } //************************************************************************* // Method: TrySelectSingleNodeAsDouble() // /// <summary> /// Attempts to select an XML node and get its Double value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="value"> /// Where the selected node's Double value gets stored if true is returned. /// </param> /// /// <returns> /// true if the specified node was found and its value was a Double. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNodeAsDouble ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out Double value ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); value = Double.MinValue; String sValue; return ( TrySelectSingleNodeAsString(node, xPath, xmlNamespaceManager, out sValue) && MathUtil.TryParseCultureInvariantDouble(sValue, out value) ); } //************************************************************************* // Method: TrySelectSingleNodeAsBoolean() // /// <summary> /// Attempts to select an XML node and get its Boolean value. /// </summary> /// /// <param name="node"> /// Node to select from. /// </param> /// /// <param name="xPath"> /// XPath expression. /// </param> /// /// <param name="xmlNamespaceManager"> /// NamespaceManager to use, or null to not use one. /// </param> /// /// <param name="value"> /// Where the selected node's Boolean value gets stored if true is /// returned. /// </param> /// /// <returns> /// true if the specified node was found and its value was a Boolean. /// </returns> //************************************************************************* public static Boolean TrySelectSingleNodeAsBoolean ( XmlNode node, String xPath, XmlNamespaceManager xmlNamespaceManager, out Boolean value ) { Debug.Assert(node != null); Debug.Assert( !String.IsNullOrEmpty(xPath) ); value = false; String sValue; return ( TrySelectSingleNodeAsString(node, xPath, xmlNamespaceManager, out sValue) && Boolean.TryParse(sValue, out value) ); } //************************************************************************* // Method: AppendNewNode() // /// <summary> /// Creates a new XML node with an optional namespace and appends it to a /// parent node. /// </summary> /// /// <param name="parentNode"> /// Node to append the new node to. /// </param> /// /// <param name="childName"> /// Name of the new node. /// </param> /// /// <param name="namespaceUri"> /// Optional namespace URI of the new node. If null or empty, no namespace /// is used. /// </param> /// /// <returns> /// The new node. /// </returns> //************************************************************************* static public XmlNode AppendNewNode ( XmlNode parentNode, String childName, String namespaceUri ) { Debug.Assert(parentNode != null); Debug.Assert( !String.IsNullOrEmpty(childName) ); // Get the owner document. XmlDocument oOwnerDocument = parentNode.OwnerDocument; // Unfortunately, the root node's OwnerDocument property returns null, // so we have to check for this special case. if (oOwnerDocument == null) { oOwnerDocument = (XmlDocument)parentNode; } XmlElement oNewNode; if ( String.IsNullOrEmpty(namespaceUri) ) { oNewNode = oOwnerDocument.CreateElement(childName); } else { oNewNode = oOwnerDocument.CreateElement(childName, namespaceUri); } return ( parentNode.AppendChild(oNewNode) ); } //************************************************************************* // Method: SetAttributes() // /// <summary> /// Sets multiple attributes on an XML node. /// </summary> /// /// <param name="node"> /// XmlNode. Node to set attributes on. /// </param> /// /// <param name="nameValuePairs"> /// String[]. One or more pairs of strings. The first string in each pair /// is an attribute name and the second is the attribute value. /// </param> /// /// <remarks> /// This sets multiple attributes on an XML node in one call. It's an /// alternative to calling <see /// cref="XmlElement.SetAttribute(String, String)" /> repeatedly. /// </remarks> //************************************************************************* public static void SetAttributes ( XmlNode node, params String[] nameValuePairs ) { Int32 iNameValueStrings = nameValuePairs.Length; if (iNameValueStrings % 2 != 0) { throw new System.ArgumentException("nameValuePairs must contain" + " an even number of strings."); } XmlElement oElement = (XmlElement)node; for (Int32 i = 0; i < iNameValueStrings; i+= 2) { String sName = nameValuePairs[i + 0]; String sValue = nameValuePairs[i + 1]; oElement.SetAttribute(sName, sValue); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fluid; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OrchardCore.Autoroute.Drivers; using OrchardCore.Autoroute.Models; using OrchardCore.Autoroute.ViewModels; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Records; using OrchardCore.ContentManagement.Routing; using OrchardCore.Environment.Cache; using OrchardCore.Liquid; using OrchardCore.Settings; using YesSql; namespace OrchardCore.Autoroute.Handlers { public class AutoroutePartHandler : ContentPartHandler<AutoroutePart> { private readonly IAutorouteEntries _entries; private readonly AutorouteOptions _options; private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISiteService _siteService; private readonly ITagCache _tagCache; private readonly ISession _session; private readonly IServiceProvider _serviceProvider; private readonly IStringLocalizer S; private IContentManager _contentManager; public AutoroutePartHandler( IAutorouteEntries entries, IOptions<AutorouteOptions> options, ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager, ISiteService siteService, ITagCache tagCache, ISession session, IServiceProvider serviceProvider, IStringLocalizer<AutoroutePartHandler> stringLocalizer) { _entries = entries; _options = options.Value; _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; _siteService = siteService; _tagCache = tagCache; _session = session; _serviceProvider = serviceProvider; S = stringLocalizer; } public override async Task PublishedAsync(PublishContentContext context, AutoroutePart part) { // Remove entry if part is disabled. if (part.Disabled) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); } // Add parent content item path, and children, only if parent has a valid path. if (!String.IsNullOrWhiteSpace(part.Path) && !part.Disabled) { var entriesToAdd = new List<AutorouteEntry> { new AutorouteEntry(part.ContentItem.ContentItemId, part.Path) }; if (part.RouteContainedItems) { _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(context.PublishingItem); await PopulateContainedContentItemRoutes(entriesToAdd, part.ContentItem.ContentItemId, containedAspect, context.PublishingItem.Content as JObject, part.Path, true); } _entries.AddEntries(entriesToAdd); } if (!String.IsNullOrWhiteSpace(part.Path) && !part.Disabled && part.SetHomepage) { await SetHomeRoute(part, homeRoute => homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId); } // Evict any dependent item from cache await RemoveTagAsync(part); } private async Task SetHomeRoute(AutoroutePart part, Action<RouteValueDictionary> action) { var site = await _siteService.LoadSiteSettingsAsync(); if (site.HomeRoute == null) { site.HomeRoute = new RouteValueDictionary(); } var homeRoute = site.HomeRoute; foreach (var entry in _options.GlobalRouteValues) { homeRoute[entry.Key] = entry.Value; } action.Invoke(homeRoute); // Once we took the flag into account we can dismiss it. part.SetHomepage = false; part.Apply(); await _siteService.UpdateSiteSettingsAsync(site); } public override Task UnpublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override Task RemovedAsync(RemoveContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path) && context.NoActiveVersionLeft) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override async Task ValidatingAsync(ValidateContentContext context, AutoroutePart part) { // Only validate the path if it's not empty. if (String.IsNullOrWhiteSpace(part.Path)) { return; } if (part.Path == "/") { context.Fail(S["Your permalink can't be set to the homepage, please use the homepage option instead."]); } if (part.Path?.IndexOfAny(AutoroutePartDisplay.InvalidCharactersForPath) > -1 || part.Path?.IndexOf(' ') > -1 || part.Path?.IndexOf("//") > -1) { var invalidCharactersForMessage = string.Join(", ", AutoroutePartDisplay.InvalidCharactersForPath.Select(c => $"\"{c}\"")); context.Fail(S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage]); } if (part.Path?.Length > AutoroutePartDisplay.MaxPathLength) { context.Fail(S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePartDisplay.MaxPathLength]); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { context.Fail(S["Your permalink is already in use."]); } } public override async Task UpdatedAsync(UpdateContentContext context, AutoroutePart part) { await GenerateContainerPathFromPattern(part); await GenerateContainedPathsFromPattern(context.UpdatingItem, part); } public async override Task CloningAsync(CloneContentContext context, AutoroutePart part) { var clonedPart = context.CloneContentItem.As<AutoroutePart>(); clonedPart.Path = await GenerateUniqueAbsolutePathAsync(part.Path, context.CloneContentItem.ContentItemId); clonedPart.SetHomepage = false; clonedPart.Apply(); await GenerateContainedPathsFromPattern(context.CloneContentItem, part); } public override Task GetContentItemAspectAsync(ContentItemAspectContext context, AutoroutePart part) { return context.ForAsync<RouteHandlerAspect>(aspect => { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart")); var settings = contentTypePartDefinition.GetSettings<AutoroutePartSettings>(); if (settings.ManageContainedItemRoutes) { aspect.Path = part.Path; aspect.Absolute = part.Absolute; aspect.Disabled = part.Disabled; } return Task.CompletedTask; }); } private Task RemoveTagAsync(AutoroutePart part) { return _tagCache.RemoveTagAsync($"slug:{part.Path}"); } private async Task GenerateContainedPathsFromPattern(ContentItem contentItem, AutoroutePart part) { // Validate contained content item routes if container has valid path. if (!String.IsNullOrWhiteSpace(part.Path) || !part.RouteContainedItems) { return; } _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); // Build the entries for this content item to evaluate for duplicates. var entries = new List<AutorouteEntry>(); await PopulateContainedContentItemRoutes(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content as JObject, part.Path); await ValidateContainedContentItemRoutes(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content as JObject, part.Path); } private async Task PopulateContainedContentItemRoutes(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath, bool setHomepage = false) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var handlerAspect = await _contentManager.PopulateAspectAsync<RouteHandlerAspect>(contentItem); if (!handlerAspect.Disabled) { var path = handlerAspect.Path; if (!handlerAspect.Absolute) { path = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; } entries.Add(new AutorouteEntry(containerContentItemId, path, contentItem.ContentItemId, jItem.Path)); // Only an autoroute part, not a default handler aspect can set itself as the homepage. var autoroutePart = contentItem.As<AutoroutePart>(); if (setHomepage && autoroutePart != null && autoroutePart.SetHomepage) { await SetHomeRoute(autoroutePart, homeRoute => { homeRoute[_options.ContentItemIdKey] = containerContentItemId; homeRoute[_options.JsonPathKey] = jItem.Path; }); } } var itemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; var childrenAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await PopulateContainedContentItemRoutes(entries, containerContentItemId, childrenAspect, jItem, itemBasePath); } } } private async Task ValidateContainedContentItemRoutes(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var containedAutoroutePart = contentItem.As<AutoroutePart>(); // This is only relevant if the content items have an autoroute part as we adjust the part value as required to guarantee a unique route. // Content items routed only through the handler aspect already guarantee uniqueness. if (containedAutoroutePart != null && !containedAutoroutePart.Disabled) { var path = containedAutoroutePart.Path; if (containedAutoroutePart.Absolute && !await IsAbsolutePathUniqueAsync(path, contentItem.ContentItemId)) { path = await GenerateUniqueAbsolutePathAsync(path, contentItem.ContentItemId); containedAutoroutePart.Path = path; containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } else { var currentItemBasePath = basePath.EndsWith('/') ? basePath : basePath + '/'; path = currentItemBasePath + containedAutoroutePart.Path; if (!IsRelativePathUnique(entries, path, containedAutoroutePart)) { path = GenerateRelativeUniquePath(entries, path, containedAutoroutePart); // Remove base path and update part path. containedAutoroutePart.Path = path.Substring(currentItemBasePath.Length); containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } path = path.Substring(currentItemBasePath.Length); } var containedItemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + path; var childItemAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await ValidateContainedContentItemRoutes(entries, containerContentItemId, childItemAspect, jItem, containedItemBasePath); } } } } private bool IsRelativePathUnique(List<AutorouteEntry> entries, string path, AutoroutePart context) { var result = !entries.Any(e => context.ContentItem.ContentItemId != e.ContainedContentItemId && String.Equals(e.Path, path, StringComparison.OrdinalIgnoreCase)); return result; } private string GenerateRelativeUniquePath(List<AutorouteEntry> entries, string path, AutoroutePart context) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && int.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + separator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePartDisplay.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (IsRelativePathUnique(entries, versionedPath, context)) { var entry = entries.FirstOrDefault(e => e.ContainedContentItemId == context.ContentItem.ContentItemId); entry.Path = versionedPath; return versionedPath; } } } private async Task GenerateContainerPathFromPattern(AutoroutePart part) { // Compute the Path only if it's empty if (!String.IsNullOrWhiteSpace(part.Path)) { return; } var pattern = GetPattern(part); if (!String.IsNullOrEmpty(pattern)) { var model = new AutoroutePartViewModel() { Path = part.Path, AutoroutePart = part, ContentItem = part.ContentItem }; part.Path = await _liquidTemplateManager.RenderAsync(pattern, NullEncoder.Default, model, scope => scope.SetValue("ContentItem", model.ContentItem)); part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty); if (part.Path?.Length > AutoroutePartDisplay.MaxPathLength) { part.Path = part.Path.Substring(0, AutoroutePartDisplay.MaxPathLength); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { part.Path = await GenerateUniqueAbsolutePathAsync(part.Path, part.ContentItem.ContentItemId); } part.Apply(); } } /// <summary> /// Get the pattern from the AutoroutePartSettings property for its type /// </summary> private string GetPattern(AutoroutePart part) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart")); var pattern = contentTypePartDefinition.GetSettings<AutoroutePartSettings>().Pattern; return pattern; } private async Task<string> GenerateUniqueAbsolutePathAsync(string path, string contentItemId) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && int.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + seperator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePartDisplay.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (await IsAbsolutePathUniqueAsync(versionedPath, contentItemId)) { return versionedPath; } } } private async Task<bool> IsAbsolutePathUniqueAsync(string path, string contentItemId) { var isUnique = true; var possibleConflicts = await _session.QueryIndex<AutoroutePartIndex>(o => o.Path == path).ListAsync(); if (possibleConflicts.Any()) { if (possibleConflicts.Any(x => x.ContentItemId != contentItemId) || possibleConflicts.Any(x => !string.IsNullOrEmpty(x.ContainedContentItemId) && x.ContainedContentItemId != contentItemId)) { isUnique = false; } } return isUnique; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if false using System.Diagnostics.Contracts; class Problem2 { const int SIZE_T_MAX = 10000; const int RP_ECHO = 0x0001; const int RP_ALLOW_STDIN= 0x0002; const int RP_ALLOW_EOF = 0x0004; const int RP_USE_ASKPASS = 0x0008; const int EINVAL = 22; /* Invalid argument */ const int ENOTTY = 25; /* Not a typewriter */ const int SSH_PROTO_UNKNOWN = 0x00; const int SSH_PROTO_1 = 0x01; const int SSH_PROTO_1_PREFERRED = 0x02; const int SSH_PROTO_2 = 0x04; //typedef unsigned char u_char; //typedef unsigned short int u_short; //typedef unsigned int u_int; //typedef unsigned long int u_long; //typedef int pid_t; //typedef unsigned int socklen_t; /* Read NBYTES into BUF from FD. Return the number read, -1 for errors or 0 for EOF. This function is a cancellation point and therefore not marked with __THROW. */ //extern ssize_t read (int __fd, void *__buf, size_t __nbytes) __wur; const int EINPROGRESS = 115; /* Operation now in progress */ const int ETIMEDOUT = 110; /* Connection timed out */ const int EINTR = 4; /* Interrupted system call */ const int SOL_SOCKET = 1; const int SO_ERROR = 4; const int SO_KEEPALIVE = 9; const int RPP_ECHO_OFF = 0x00; /* Turn off echo (default). */ const int RPP_ECHO_ON = 0x01; /* Leave echo on. */ const int RPP_REQUIRE_TTY = 0x02; /* Fail if there is no tty. */ const int RPP_FORCELOWER = 0x04; /* Force input to lower case. */ const int RPP_FORCEUPPER = 0x08; /* Force input to upper case. */ const int RPP_SEVENBIT = 0x10; /* Strip the high bit from input. */ const int RPP_STDIN = 0x20; /* Read from stdin, not /dev/tty */ const string _PATH_TTY = "/dev/tty"; const string _PATH_SSH_ASKPASS_DEFAULT = "/usr/X11R6/bin/ssh-askpass"; /* Standard file descriptors. */ const int STDIN_FILENO =0; /* Standard input. */ const int STDOUT_FILENO =1; /* Standard output. */ const int STDERR_FILENO =2; /* Standard error output. */ /* * Maximum number of RSA authentication identity files that can be specified * in configuration files or on the command line. */ const int SSH_MAX_IDENTITY_FILES =100; /* Maximum number of TCP/IP ports forwarded per direction. */ const int SSH_MAX_FORWARDS_PER_DIRECTION =100; const int MAX_SEND_ENV =256; /* * Environment variable for overwriting the default location of askpass */ const string SSH_ASKPASS_ENV = "SSH_ASKPASS"; //static char * ssh_askpass(char *askpass, const char *msg); struct Key { int type; int flags; int[] rsa; int[] dsa; } // f: added struct termios { public int c_lflag; } const int ECHO =0000010; const int ECHOE =0000020; const int ECHOK =0000040; const int ECHONL =0000100; const int NOFLSH =0000200; const int TOSTOP =0000400; const int ECHOCTL =0001000; const int ECHOPRT =0002000; const int ECHOKE =0004000; const int FLUSHO =0010000; const int PENDIN =0040000; /* tcsetattr uses these */ const int TCSANOW =0; const int TCSADRAIN =1; const int TCSAFLUSH =2; const int _T_FLUSH = 12345; // (TCSAFLUSH) //---------------------------------------- /* Fatal messages. This function never returns. */ /* void fatal(const char *fmt,...) { exit(1); } */ /* Duplicates a character string. This function only returns NULL if s is passed as NULL. */ [ContractVerification(false)] // was extern string xstrdup (string s) { Contract.Ensures(s != null || Contract.Result<string>() == null); Contract.Ensures(s == null || Contract.Result<string>() != null); return s; } /* * Frees the memory pointed to by ptr. Aborts if ptr is NULL. */ [ContractVerification(false)] // was extern void xfree(object ptr) { Contract.Requires(ptr != null); } // defined in C library [ContractVerification(false)] // defined in C library int open(string name, int option) { Contract.Requires(name != null); return -1; } [ContractVerification(false)] private unsafe void memcpy(object p,object p_2,int p_3) { throw new System.NotImplementedException(); } [ContractVerification(false)] private int tcgetattr(int input, ref termios oterm) { throw new System.NotImplementedException(); } // f: Added by me private int O_RDWR; int errno; /* import */ extern string __progname; extern int original_real_uid; extern int original_effective_uid; extern int proxy_command_pid; static volatile int signo; //typedef unsigned char cc_t; //typedef unsigned int speed_t; //typedef unsigned int tcflag_t; unsafe string readpassphrase(string prompt, string buf, uint bufsiz, int flags) { //ssize_t nr; int input, output, save_errno; char ch; string p, end; /*struct */termios term, oterm; // f: where termios is defined??? /* I suppose we could alloc on demand in this case (XXX). */ if (bufsiz == 0) { errno = EINVAL; return null; } restart: signo = 0; /* * Read and write to /dev/tty if available. If not, read from * stdin and write to stderr unless a tty is required. */ if ((flags & RPP_STDIN) != 0|| (input = output = open(_PATH_TTY, O_RDWR)) == -1) { if ((flags & RPP_REQUIRE_TTY) != null) { errno = ENOTTY; return null; } input = STDIN_FILENO; output = STDERR_FILENO; } /* Turn off echo if possible. */ if (input != STDIN_FILENO && tcgetattr(input, ref oterm) == 0) { // F: commented // memcpy(term, oterm, term); if ((flags & RPP_ECHO_ON) == 0) term.c_lflag &= ~(ECHO | ECHONL); #if VSTATUS if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) term.c_cc[VSTATUS] = _POSIX_VDISABLE; #endif tcsetattr(input, _T_FLUSH, ref term); } else { memset(ref term, 0, sizeof(termios)); term.c_lflag |= ECHO; memset(ref oterm, 0, sizeof(termios)); oterm.c_lflag |= ECHO; } if ((flags & RPP_STDIN) == 0) write(output, prompt, prompt.Length); end = buf + bufsiz - 1; for (p = buf; p<end; ) { nr = read(input, &ch, 1); if ((flags & RPP_SEVENBIT)) ch &= 0x7f; if (isalpha(ch)) { if ((flags & RPP_FORCELOWER)) ch = tolower(ch); if ((flags & RPP_FORCEUPPER)) ch = toupper(ch); } *p++ = ch; } *p = '\0'; save_errno = errno; if (!(term.c_lflag & ECHO)) (void)write(output, "\n", 1); /* Restore old terminal settings and signals. */ if (memcmp(&term, &oterm, sizeof(term)) != 0) { while (tcsetattr(input, _T_FLUSH, &oterm) == -1 && errno == EINTR) continue; } /* * If we were interrupted by a signal, resend it to ourselves * now that we have restored the signal handlers. */ if (signo) { kill(getpid(), signo); switch (signo) { case SIGTSTP: case SIGTTIN: case SIGTTOU: goto restart; } } errno = save_errno; return(nr == -1 ? NULL : buf); } [ContractVerification(false)] private object write(int output,string prompt,int p) { throw new System.NotImplementedException(); } [ContractVerification(false)] private void memset(ref termios term,int p,int p_2) { throw new System.NotImplementedException(); } [ContractVerification(false)] private void tcsetattr(int input,int _T_FLUSH,ref termios term) { throw new System.NotImplementedException(); } /* * Reads a passphrase from /dev/tty with echo turned off/on. Returns the * passphrase (allocated with xmalloc). Exits if EOF is encountered. If * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no * tty is available */ char * read_passphrase(const char *prompt, int flags) { char *askpass = NULL, *ret, buf[1024]; int rppflags, use_askpass = 0, ttyfd; rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF; if (flags & RP_USE_ASKPASS) use_askpass = 1; else if (flags & RP_ALLOW_STDIN) { if (!isatty(STDIN_FILENO)) { debug("read_passphrase: stdin is not a tty"); use_askpass = 1; } } else { rppflags |= RPP_REQUIRE_TTY; ttyfd = open(_PATH_TTY, O_RDWR); if (ttyfd >= 0) close(ttyfd); else { debug("read_passphrase: can't open %s: %s", _PATH_TTY, strerror(errno)); use_askpass = 1; } } if ((flags & RP_USE_ASKPASS) && getenv("DISPLAY") == NULL) return (flags & RP_ALLOW_EOF) ? NULL : xstrdup(""); if (use_askpass && getenv("DISPLAY")) { if (getenv(SSH_ASKPASS_ENV)) askpass = getenv(SSH_ASKPASS_ENV); else askpass = _PATH_SSH_ASKPASS_DEFAULT; if ((ret = ssh_askpass(askpass, prompt)) == NULL) if (!(flags & RP_ALLOW_EOF)) return xstrdup(""); return ret; } if ((flags & RP_USE_ASKPASS) && readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) { return NULL; } ret = xstrdup(buf); memset(buf, 'x', sizeof buf); return ret; } static char * ssh_askpass(char *askpass, const char *msg) { pid_t pid, ret; size_t len; char *pass; int p[2], status; char buf[1024]; void (*osigchld)(int); if (fflush(stdout) != 0) error("ssh_askpass: fflush: %s", strerror(errno)); if (askpass == NULL) fatal("internal error: askpass undefined"); if (pipe(p) < 0) { error("ssh_askpass: pipe: %s", strerror(errno)); return NULL; } osigchld = signal(SIGCHLD, SIG_DFL); if ((pid = fork()) < 0) { error("ssh_askpass: fork: %s", strerror(errno)); signal(SIGCHLD, osigchld); return NULL; } if (pid == 0) { permanently_drop_suid(getuid()); close(p[0]); if (dup2(p[1], STDOUT_FILENO) < 0) fatal("ssh_askpass: dup2: %s", strerror(errno)); execlp(askpass, askpass, msg, (char *) 0); fatal("ssh_askpass: exec(%s): %s", askpass, strerror(errno)); } close(p[1]); len = 0; do { ssize_t r = read(p[0], buf + len, sizeof(buf) - 1 - len); if (r == -1 && errno == EINTR) continue; if (r <= 0) break; len += r; } while (sizeof(buf) - 1 - len > 0); buf[len] = '\0'; close(p[0]); while ((ret = waitpid(pid, &status, 0)) < 0) if (errno != EINTR) break; signal(SIGCHLD, osigchld); if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { memset(buf, 0, sizeof(buf)); return NULL; } buf[strcspn(buf, "\r\n")] = '\0'; pass = xstrdup(buf); memset(buf, 0, sizeof(buf)); return pass; } static int confirm(const char *prompt) { char *p; int ret = -1; const char* msg = prompt; if(!msg) return 0; p = read_passphrase(msg, RP_ECHO); static_assert(p!=NULL); if (p&& (p[0] == '\0') || (p[0] == '\n') || strncasecmp(p, "no", 2) == 0) ret = 0; if (p && strncasecmp(p, "yes", 3) == 0) ret = 1; if(p) xfree(p); return ret; } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Build.Collections; using Microsoft.Build.Execution; using Microsoft.Build.Shared; using Microsoft.Build.Construction; using Xunit; namespace Microsoft.Build.UnitTests.OM.Collections { /// <summary> /// Tests for the CopyOnWriteDictionary /// </summary> public class CopyOnWriteDictionary_Tests { /// <summary> /// Find with the same key inserted using the indexer /// </summary> [Fact] public void Indexer_ReferenceFound() { object k1 = new Object(); object v1 = new Object(); var dictionary = new CopyOnWriteDictionary<object, object>(); dictionary[k1] = v1; // Now look for the same key we inserted object v2 = dictionary[k1]; Assert.True(Object.ReferenceEquals(v1, v2)); Assert.True(dictionary.ContainsKey(k1)); } /// <summary> /// Find something not present with the indexer /// </summary> [Fact] public void Indexer_NotFound() { Assert.Throws<KeyNotFoundException>(() => { var dictionary = new CopyOnWriteDictionary<object, object>(); object value = dictionary[new Object()]; } ); } /// <summary> /// Find with the same key inserted using TryGetValue /// </summary> [Fact] public void TryGetValue_ReferenceFound() { object k1 = new Object(); object v1 = new Object(); var dictionary = new CopyOnWriteDictionary<object, object>(); dictionary[k1] = v1; // Now look for the same key we inserted object v2; bool result = dictionary.TryGetValue(k1, out v2); Assert.True(result); Assert.True(Object.ReferenceEquals(v1, v2)); } /// <summary> /// Find something not present with TryGetValue /// </summary> [Fact] public void TryGetValue_ReferenceNotFound() { var dictionary = new CopyOnWriteDictionary<object, object>(); object v; bool result = dictionary.TryGetValue(new Object(), out v); Assert.False(result); Assert.Null(v); Assert.False(dictionary.ContainsKey(new Object())); } /// <summary> /// Find a key that wasn't inserted but is equal /// </summary> [Fact] public void EqualityComparer() { string k1 = String.Concat("ke", "y"); object v1 = new Object(); var dictionary = new CopyOnWriteDictionary<string, object>(); dictionary[k1] = v1; // Now look for a different but equatable key // Don't create it with a literal or the compiler will intern it! string k2 = String.Concat("k", "ey"); Assert.False(Object.ReferenceEquals(k1, k2)); object v2 = dictionary[k2]; Assert.True(Object.ReferenceEquals(v1, v2)); } /// <summary> /// Cloning sees the same values /// </summary> [Fact] public void CloneVisibility() { var dictionary = new CopyOnWriteDictionary<string, string>(); dictionary["test"] = "1"; Assert.Equal("1", dictionary["test"]); var clone = dictionary.Clone(); Assert.Equal("1", clone["test"]); Assert.Equal(clone.Count, dictionary.Count); } /// <summary> /// Clone uses same comparer /// </summary> [Fact] public void CloneComparer() { var dictionary = new CopyOnWriteDictionary<string, string>(StringComparer.OrdinalIgnoreCase); dictionary["test"] = "1"; Assert.Equal("1", dictionary["test"]); var clone = dictionary.Clone(); Assert.Equal("1", clone["TEST"]); } /// <summary> /// Writes to original not visible to clone /// </summary> [Fact] public void OriginalWritesNotVisibleToClones() { var dictionary = new CopyOnWriteDictionary<string, string>(); dictionary["test"] = "1"; Assert.Equal("1", dictionary["test"]); var clone = dictionary.Clone(); var clone2 = dictionary.Clone(); Assert.True(dictionary.HasSameBacking(clone)); Assert.True(dictionary.HasSameBacking(clone2)); dictionary["test"] = "2"; Assert.False(dictionary.HasSameBacking(clone)); Assert.False(dictionary.HasSameBacking(clone2)); Assert.True(clone.HasSameBacking(clone2)); Assert.Equal("1", clone["test"]); Assert.Equal("1", clone2["test"]); } /// <summary> /// Writes to clone not visible to original /// </summary> [Fact] public void CloneWritesNotVisibleToOriginal() { var dictionary = new CopyOnWriteDictionary<string, string>(); dictionary["test"] = "1"; Assert.Equal("1", dictionary["test"]); var clone = dictionary.Clone(); var clone2 = dictionary.Clone(); Assert.True(dictionary.HasSameBacking(clone)); Assert.True(dictionary.HasSameBacking(clone2)); clone["test"] = "2"; Assert.False(dictionary.HasSameBacking(clone)); Assert.False(clone2.HasSameBacking(clone)); Assert.True(dictionary.HasSameBacking(clone2)); clone2["test"] = "3"; Assert.False(dictionary.HasSameBacking(clone2)); Assert.Equal("1", dictionary["test"]); Assert.Equal("2", clone["test"]); } /// <summary> /// Serialize basic case /// </summary> [Fact] public void SerializeDeserialize() { CopyOnWriteDictionary<int, string> dictionary = new CopyOnWriteDictionary<int, string>(); dictionary.Add(1, "1"); using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, dictionary); stream.Position = 0; var dictionary2 = (CopyOnWriteDictionary<int, string>)formatter.Deserialize(stream); Assert.Equal(dictionary.Count, dictionary2.Count); Assert.Equal(dictionary.Comparer, dictionary2.Comparer); Assert.Equal("1", dictionary2[1]); dictionary2.Add(2, "2"); } } /// <summary> /// Serialize custom comparer /// </summary> [Fact] public void SerializeDeserialize2() { CopyOnWriteDictionary<string, string> dictionary = new CopyOnWriteDictionary<string, string>(MSBuildNameIgnoreCaseComparer.Default); using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, dictionary); stream.Position = 0; CopyOnWriteDictionary<string, string> dictionary2 = (CopyOnWriteDictionary<string, string>)formatter.Deserialize(stream); Assert.Equal(dictionary.Count, dictionary2.Count); Assert.IsType<MSBuildNameIgnoreCaseComparer>(dictionary2.Comparer); } } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.Win32.SafeHandles; namespace Microsoft.VisualStudioTools.Project { internal static class NativeMethods { // IIDS public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); public const int ERROR_FILE_NOT_FOUND = 2; public const int CLSCTX_INPROC_SERVER = 0x1; public const int S_FALSE = 0x00000001, S_OK = 0x00000000, IDOK = 1, IDCANCEL = 2, IDABORT = 3, IDRETRY = 4, IDIGNORE = 5, IDYES = 6, IDNO = 7, IDCLOSE = 8, IDHELP = 9, IDTRYAGAIN = 10, IDCONTINUE = 11, OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100), OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104), UNDO_E_CLIENTABORT = unchecked((int)0x80044001), E_OUTOFMEMORY = unchecked((int)0x8007000E), E_INVALIDARG = unchecked((int)0x80070057), E_FAIL = unchecked((int)0x80004005), E_NOINTERFACE = unchecked((int)0x80004002), E_POINTER = unchecked((int)0x80004003), E_NOTIMPL = unchecked((int)0x80004001), E_UNEXPECTED = unchecked((int)0x8000FFFF), E_HANDLE = unchecked((int)0x80070006), E_ABORT = unchecked((int)0x80004004), E_ACCESSDENIED = unchecked((int)0x80070005), E_PENDING = unchecked((int)0x8000000A); public const int OLECLOSE_SAVEIFDIRTY = 0, OLECLOSE_NOSAVE = 1, OLECLOSE_PROMPTSAVE = 2; public const int OLEIVERB_PRIMARY = 0, OLEIVERB_SHOW = -1, OLEIVERB_OPEN = -2, OLEIVERB_HIDE = -3, OLEIVERB_UIACTIVATE = -4, OLEIVERB_INPLACEACTIVATE = -5, OLEIVERB_DISCARDUNDOSTATE = -6, OLEIVERB_PROPERTIES = -7; public const int OFN_READONLY = unchecked((int)0x00000001), OFN_OVERWRITEPROMPT = unchecked((int)0x00000002), OFN_HIDEREADONLY = unchecked((int)0x00000004), OFN_NOCHANGEDIR = unchecked((int)0x00000008), OFN_SHOWHELP = unchecked((int)0x00000010), OFN_ENABLEHOOK = unchecked((int)0x00000020), OFN_ENABLETEMPLATE = unchecked((int)0x00000040), OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080), OFN_NOVALIDATE = unchecked((int)0x00000100), OFN_ALLOWMULTISELECT = unchecked((int)0x00000200), OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400), OFN_PATHMUSTEXIST = unchecked((int)0x00000800), OFN_FILEMUSTEXIST = unchecked((int)0x00001000), OFN_CREATEPROMPT = unchecked((int)0x00002000), OFN_SHAREAWARE = unchecked((int)0x00004000), OFN_NOREADONLYRETURN = unchecked((int)0x00008000), OFN_NOTESTFILECREATE = unchecked((int)0x00010000), OFN_NONETWORKBUTTON = unchecked((int)0x00020000), OFN_NOLONGNAMES = unchecked((int)0x00040000), OFN_EXPLORER = unchecked((int)0x00080000), OFN_NODEREFERENCELINKS = unchecked((int)0x00100000), OFN_LONGNAMES = unchecked((int)0x00200000), OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000), OFN_ENABLESIZING = unchecked((int)0x00800000), OFN_USESHELLITEM = unchecked((int)0x01000000), OFN_DONTADDTORECENT = unchecked((int)0x02000000), OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000); // for READONLYSTATUS public const int ROSTATUS_NotReadOnly = 0x0, ROSTATUS_ReadOnly = 0x1, ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF); public const int IEI_DoNotLoadDocData = 0x10000000; public const int CB_SETDROPPEDWIDTH = 0x0160, GWL_STYLE = (-16), GWL_EXSTYLE = (-20), DWL_MSGRESULT = 0, SW_SHOWNORMAL = 1, HTMENU = 5, WS_POPUP = unchecked((int)0x80000000), WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_LAYERED = 0x00080000, WS_EX_TOPMOST = 0x00000008, WS_EX_NOPARENTNOTIFY = 0x00000004, LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54), LVS_EX_LABELTIP = 0x00004000, // winuser.h WH_JOURNALPLAYBACK = 1, WH_GETMESSAGE = 3, WH_MOUSE = 7, WSF_VISIBLE = 0x0001, WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DELETEITEM = 0x002D, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_NCXBUTTONDOWN = 0x00AB, WM_NCXBUTTONUP = 0x00AC, WM_NCXBUTTONDBLCLK = 0x00AD, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_CTLCOLOR = 0x0019, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, WM_XBUTTONDBLCLK = 0x020D, WM_MOUSEWHEEL = 0x020A, WM_MOUSELAST = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_POWERBROADCAST = 0x0218, WM_DEVICECHANGE = 0x0219, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = unchecked((int)0x8000), WM_USER = 0x0400, WM_REFLECT = WM_USER + 0x1C00, WS_OVERLAPPED = 0x00000000, WPF_SETMINPOSITION = 0x0001, WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1), WHEEL_DELTA = 120, DWLP_MSGRESULT = 0, PSNRET_NOERROR = 0, PSNRET_INVALID = 1, PSNRET_INVALID_NOCHANGEPAGE = 2, EM_SETCUEBANNER = 0x1501; public const int VK_LBUTTON = 0x01; public const int VK_RBUTTON = 0x02; public const int VK_MBUTTON = 0x04; public const int VK_XBUTTON1 = 0x05; public const int VK_XBUTTON2 = 0x06; public const int VK_TAB = 0x09; public const int VK_SHIFT = 0x10; public const int VK_CONTROL = 0x11; public const int VK_MENU = 0x12; public const int VK_SPACE = 0x20; public const int VK_LSHIFT = 0xA0; public const int VK_RSHIFT = 0xA1; public const int VK_LCONTROL = 0xA2; public const int VK_RCONTROL = 0xA3; public const int VK_LMENU = 0xA4; public const int VK_RMENU = 0xA5; public const int VK_LWIN = 0x5B; public const int VK_RWIN = 0x5C; public const int VK_F1 = 0x70; public const int VK_F2 = 0x71; public const int VK_F3 = 0x72; public const int VK_F4 = 0x73; public const int VK_ESC = 0x1B; public const int VK_RETURN = 0x0D; public const int VK_ESCAPE = 0x1B; public const int VK_DELETE = 0x2E; public const int VK_DOWN = 0x28; public const int PSN_APPLY = ((0 - 200) - 2), PSN_KILLACTIVE = ((0 - 200) - 1), PSN_RESET = ((0 - 200) - 3), PSN_SETACTIVE = ((0 - 200) - 0); public const int GMEM_MOVEABLE = 0x0002, GMEM_ZEROINIT = 0x0040, GMEM_DDESHARE = 0x2000; public const int SWP_NOACTIVATE = 0x0010, SWP_NOZORDER = 0x0004, SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_FRAMECHANGED = 0x0020; public const int TVM_SETINSERTMARK = (0x1100 + 26), TVM_GETEDITCONTROL = (0x1100 + 15); public const int FILE_ATTRIBUTE_READONLY = 0x00000001, FILE_ATTRIBUTE_DIRECTORY = 0x00000010; public const int PSP_DEFAULT = 0x00000000, PSP_DLGINDIRECT = 0x00000001, PSP_USEHICON = 0x00000002, PSP_USEICONID = 0x00000004, PSP_USETITLE = 0x00000008, PSP_RTLREADING = 0x00000010, PSP_HASHELP = 0x00000020, PSP_USEREFPARENT = 0x00000040, PSP_USECALLBACK = 0x00000080, PSP_PREMATURE = 0x00000400, PSP_HIDEHEADER = 0x00000800, PSP_USEHEADERTITLE = 0x00001000, PSP_USEHEADERSUBTITLE = 0x00002000; public const int PSH_DEFAULT = 0x00000000, PSH_PROPTITLE = 0x00000001, PSH_USEHICON = 0x00000002, PSH_USEICONID = 0x00000004, PSH_PROPSHEETPAGE = 0x00000008, PSH_WIZARDHASFINISH = 0x00000010, PSH_WIZARD = 0x00000020, PSH_USEPSTARTPAGE = 0x00000040, PSH_NOAPPLYNOW = 0x00000080, PSH_USECALLBACK = 0x00000100, PSH_HASHELP = 0x00000200, PSH_MODELESS = 0x00000400, PSH_RTLREADING = 0x00000800, PSH_WIZARDCONTEXTHELP = 0x00001000, PSH_WATERMARK = 0x00008000, PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark PSH_USEHPLWATERMARK = 0x00020000, // PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header PSH_HEADER = 0x00080000, PSH_USEHBMHEADER = 0x00100000, PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page PSH_WIZARD_LITE = 0x00400000, PSH_NOCONTEXTHELP = 0x02000000; public const int PSBTN_BACK = 0, PSBTN_NEXT = 1, PSBTN_FINISH = 2, PSBTN_OK = 3, PSBTN_APPLYNOW = 4, PSBTN_CANCEL = 5, PSBTN_HELP = 6, PSBTN_MAX = 6; public const int TRANSPARENT = 1, OPAQUE = 2, FW_BOLD = 700; [StructLayout(LayoutKind.Sequential)] public struct NMHDR { public IntPtr hwndFrom; public int idFrom; public int code; } /// <devdoc> /// Helper class for setting the text parameters to OLECMDTEXT structures. /// </devdoc> public static class OLECMDTEXT { public static void SetText(IntPtr pCmdTextInt, string text) { Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)); char[] menuText = text.ToCharArray(); // Get the offset to the rgsz param. This is where we will stuff our text // IntPtr offset = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "rgwz"); IntPtr offsetToCwActual = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "cwActual"); // The max chars we copy is our string, or one less than the buffer size, // since we need a null at the end. // int maxChars = Math.Min((int)pCmdText.cwBuf - 1, menuText.Length); Marshal.Copy(menuText, 0, (IntPtr)((long)pCmdTextInt + (long)offset), maxChars); // append a null character Marshal.WriteInt16((IntPtr)((long)pCmdTextInt + (long)offset + maxChars * 2), 0); // write out the length // +1 for the null char Marshal.WriteInt32((IntPtr)((long)pCmdTextInt + (long)offsetToCwActual), maxChars + 1); } /// <summary> /// Gets the flags of the OLECMDTEXT structure /// </summary> /// <param name="pCmdTextInt">The structure to read.</param> /// <returns>The value of the flags.</returns> public static OLECMDTEXTF GetFlags(IntPtr pCmdTextInt) { Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)); if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_NAME) != 0) return OLECMDTEXTF.OLECMDTEXTF_NAME; if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_STATUS) != 0) return OLECMDTEXTF.OLECMDTEXTF_STATUS; return OLECMDTEXTF.OLECMDTEXTF_NONE; } /// <summary> /// Flags for the OLE command text /// </summary> public enum OLECMDTEXTF { /// <summary>No flag</summary> OLECMDTEXTF_NONE = 0, /// <summary>The name of the command is required.</summary> OLECMDTEXTF_NAME = 1, /// <summary>A description of the status is required.</summary> OLECMDTEXTF_STATUS = 2 } } /// <devdoc> /// OLECMDF enums for IOleCommandTarget /// </devdoc> public enum tagOLECMDF { OLECMDF_SUPPORTED = 1, OLECMDF_ENABLED = 2, OLECMDF_LATCHED = 4, OLECMDF_NINCHED = 8, OLECMDF_INVISIBLE = 16 } [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern bool GetClientRect(IntPtr hWnd, out User32RECT lpRect); [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageW(IntPtr hWnd, uint msg, IntPtr wParam, string lParam); [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); public static void SetErrorDescription(string description, params object[] args) { ICreateErrorInfo errInfo; ErrorHandler.ThrowOnFailure(CreateErrorInfo(out errInfo)); errInfo.SetDescription(String.Format(description, args)); var guidNull = Guid.Empty; errInfo.SetGUID(ref guidNull); errInfo.SetHelpFile(null); errInfo.SetHelpContext(0); errInfo.SetSource(""); IErrorInfo errorInfo = errInfo as IErrorInfo; SetErrorInfo(0, errorInfo); } [DllImport("oleaut32")] static extern int CreateErrorInfo(out ICreateErrorInfo errInfo); [DllImport("oleaut32")] static extern int SetErrorInfo(uint dwReserved, IErrorInfo perrinfo); [ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IEventHandler { // converts the underlying codefunction into an event handler for the given event // if the given event is NULL, then the function will handle no events [PreserveSig] int AddHandler(string bstrEventName); [PreserveSig] int RemoveHandler(string bstrEventName); IVsEnumBSTR GetHandledEvents(); bool HandlesEvent(string bstrEventName); } [ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IParameterKind { void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode); void SetParameterArrayDimensions(int uDimensions); int GetParameterArrayCount(); int GetParameterArrayDimensions(int uIndex); int GetParameterPassingMode(); } public enum PARAMETER_PASSING_MODE { cmParameterTypeIn = 1, cmParameterTypeOut = 2, cmParameterTypeInOut = 3 } [ ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] public interface IMethodXML { // Generate XML describing the contents of this function's body. void GetXML(ref string pbstrXML); // Parse the incoming XML with respect to the CodeModel XML schema and // use the result to regenerate the body of the function. /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' /> [PreserveSig] int SetXML(string pszXML); // This is really a textpoint [PreserveSig] int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint); } [ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IVBFileCodeModelEvents { [PreserveSig] int StartEdit(); [PreserveSig] int EndEdit(); } ///-------------------------------------------------------------------------- /// ICodeClassBase: ///-------------------------------------------------------------------------- [GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport()] public interface ICodeClassBase { [PreserveSig()] int GetBaseName(out string pBaseName); } public const ushort CF_HDROP = 15; // winuser.h public const uint MK_CONTROL = 0x0008; //winuser.h public const uint MK_SHIFT = 0x0004; public const int MAX_PATH = 260; // windef.h public const int MAX_FOLDER_PATH = MAX_PATH - 12; // folders need to allow 8.3 filenames, so MAX_PATH - 12 /// <summary> /// Specifies options for a bitmap image associated with a task item. /// </summary> public enum VSTASKBITMAP { BMP_COMPILE = -1, BMP_SQUIGGLE = -2, BMP_COMMENT = -3, BMP_SHORTCUT = -4, BMP_USER = -5 }; public const int ILD_NORMAL = 0x0000, ILD_TRANSPARENT = 0x0001, ILD_MASK = 0x0010, ILD_ROP = 0x0040; /// <summary> /// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration /// </summary> [ComVisible(true)] public enum ExtendedSpecialFolder { /// <summary> /// Identical to CSIDL_COMMON_STARTUP /// </summary> CommonStartup = 0x0018, /// <summary> /// Identical to CSIDL_WINDOWS /// </summary> Windows = 0x0024, } // APIS /// <summary> /// Changes the parent window of the specified child window. /// </summary> /// <param name="hWnd">Handle to the child window.</param> /// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param> /// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns> [DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool DestroyIcon(IntPtr handle); [DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg); [DllImport("kernel32", EntryPoint = "GetBinaryTypeW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] private static extern bool _GetBinaryType(string lpApplicationName, out GetBinaryTypeResult lpBinaryType); private enum GetBinaryTypeResult : uint { SCS_32BIT_BINARY = 0, SCS_DOS_BINARY = 1, SCS_WOW_BINARY = 2, SCS_PIF_BINARY = 3, SCS_POSIX_BINARY = 4, SCS_OS216_BINARY = 5, SCS_64BIT_BINARY = 6 } public static ProcessorArchitecture GetBinaryType(string path) { GetBinaryTypeResult result; if (_GetBinaryType(path, out result)) { switch (result) { case GetBinaryTypeResult.SCS_32BIT_BINARY: return ProcessorArchitecture.X86; case GetBinaryTypeResult.SCS_64BIT_BINARY: return ProcessorArchitecture.Amd64; case GetBinaryTypeResult.SCS_DOS_BINARY: case GetBinaryTypeResult.SCS_WOW_BINARY: case GetBinaryTypeResult.SCS_PIF_BINARY: case GetBinaryTypeResult.SCS_POSIX_BINARY: case GetBinaryTypeResult.SCS_OS216_BINARY: default: break; } } return ProcessorArchitecture.None; } [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); [DllImport("ADVAPI32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool LogonUser( [In] string lpszUsername, [In] string lpszDomain, [In] string lpszPassword, [In] LogonType dwLogonType, [In] LogonProvider dwLogonProvider, [In, Out] ref IntPtr hToken ); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint GetFinalPathNameByHandle( SafeHandle hFile, [Out]StringBuilder lpszFilePath, uint cchFilePath, uint dwFlags ); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern SafeFileHandle CreateFile( string lpFileName, FileDesiredAccess dwDesiredAccess, FileShareFlags dwShareMode, IntPtr lpSecurityAttributes, FileCreationDisposition dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile ); [Flags] public enum FileDesiredAccess : uint { FILE_LIST_DIRECTORY = 1 } [Flags] public enum FileShareFlags : uint { FILE_SHARE_READ = 0x00000001, FILE_SHARE_WRITE = 0x00000002, FILE_SHARE_DELETE = 0x00000004 } [Flags] public enum FileCreationDisposition : uint { OPEN_EXISTING = 3 } [Flags] public enum FileFlagsAndAttributes : uint { FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 } public static IntPtr INVALID_FILE_HANDLE = new IntPtr(-1); public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); public enum LogonType { LOGON32_LOGON_INTERACTIVE = 2, LOGON32_LOGON_NETWORK, LOGON32_LOGON_BATCH, LOGON32_LOGON_SERVICE = 5, LOGON32_LOGON_UNLOCK = 7, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NEW_CREDENTIALS } public enum LogonProvider { LOGON32_PROVIDER_DEFAULT = 0, LOGON32_PROVIDER_WINNT35, LOGON32_PROVIDER_WINNT40, LOGON32_PROVIDER_WINNT50 } [DllImport("user32", CallingConvention = CallingConvention.Winapi)] public static extern bool AllowSetForegroundWindow(int dwProcessId); [DllImport("mpr", CharSet = CharSet.Unicode)] public static extern uint WNetAddConnection3(IntPtr handle, ref _NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags); public const int CONNECT_INTERACTIVE = 0x08; public const int CONNECT_PROMPT = 0x10; public const int RESOURCETYPE_DISK = 1; public struct _NETRESOURCE { public uint dwScope; public uint dwType; public uint dwDisplayType; public uint dwUsage; public string lpLocalName; public string lpRemoteName; public string lpComment; public string lpProvider; } [DllImport(ExternDll.Kernel32, EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int GetFinalPathNameByHandle(SafeFileHandle handle, [In, Out] StringBuilder path, int bufLen, int flags); [DllImport(ExternDll.Kernel32, EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeFileHandle CreateFile( string lpFileName, int dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, IntPtr SecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); /// <summary> /// Given a directory, actual or symbolic, return the actual directory path. /// </summary> /// <param name="symlink">DirectoryInfo object for the suspected symlink.</param> /// <returns>A string of the actual path.</returns> internal static string GetAbsolutePathToDirectory(string symlink) { const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; const int DEVICE_QUERY_ACCESS = 0; using (SafeFileHandle directoryHandle = CreateFile( symlink, DEVICE_QUERY_ACCESS, FileShare.Write, System.IntPtr.Zero, FileMode.Open, FILE_FLAG_BACKUP_SEMANTICS, System.IntPtr.Zero)) { if (directoryHandle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } StringBuilder path = new StringBuilder(512); int pathSize = GetFinalPathNameByHandle(directoryHandle, path, path.Capacity, 0); if (pathSize < 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } // UNC Paths will start with \\?\. Remove this if present as this isn't really expected on a path. var pathString = path.ToString(); return pathString.StartsWith(@"\\?\", StringComparison.Ordinal) ? pathString.Substring(4) : pathString; } } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool FindClose(IntPtr hFindFile); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool DeleteFile(string lpFileName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool RemoveDirectory(string lpPathName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool MoveFile(String src, String dst); } internal class CredUI { private const string advapi32Dll = "advapi32.dll"; private const string credUIDll = "credui.dll"; public const int ERROR_INVALID_FLAGS = 1004, // Invalid flags. ERROR_NOT_FOUND = 1168, // Element not found. ERROR_NO_SUCH_LOGON_SESSION = 1312, // A specified logon session does not exist. It may already have been terminated. ERROR_LOGON_FAILURE = 1326; // Logon failure: unknown user name or bad password. [Flags] public enum CREDUI_FLAGS : uint { INCORRECT_PASSWORD = 0x1, DO_NOT_PERSIST = 0x2, REQUEST_ADMINISTRATOR = 0x4, EXCLUDE_CERTIFICATES = 0x8, REQUIRE_CERTIFICATE = 0x10, SHOW_SAVE_CHECK_BOX = 0x40, ALWAYS_SHOW_UI = 0x80, REQUIRE_SMARTCARD = 0x100, PASSWORD_ONLY_OK = 0x200, VALIDATE_USERNAME = 0x400, COMPLETE_USERNAME = 0x800, PERSIST = 0x1000, SERVER_CREDENTIAL = 0x4000, EXPECT_CONFIRMATION = 0x20000, GENERIC_CREDENTIALS = 0x40000, USERNAME_TARGET_CREDENTIALS = 0x80000, KEEP_USERNAME = 0x100000, } [StructLayout(LayoutKind.Sequential)] public class CREDUI_INFO { public int cbSize; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr hwndParentCERParent; [MarshalAs(UnmanagedType.LPWStr)] public string pszMessageText; [MarshalAs(UnmanagedType.LPWStr)] public string pszCaptionText; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr hbmBannerCERHandle; } public enum CredUIReturnCodes : uint { NO_ERROR = 0, ERROR_CANCELLED = 1223, ERROR_NO_SUCH_LOGON_SESSION = 1312, ERROR_NOT_FOUND = 1168, ERROR_INVALID_ACCOUNT_NAME = 1315, ERROR_INSUFFICIENT_BUFFER = 122, ERROR_INVALID_PARAMETER = 87, ERROR_INVALID_FLAGS = 1004, } // Copied from wincred.h public const uint // Values of the Credential Type field. CRED_TYPE_GENERIC = 1, CRED_TYPE_DOMAIN_PASSWORD = 2, CRED_TYPE_DOMAIN_CERTIFICATE = 3, CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 4, CRED_TYPE_MAXIMUM = 5, // Maximum supported cred type CRED_TYPE_MAXIMUM_EX = (CRED_TYPE_MAXIMUM + 1000), // Allow new applications to run on old OSes // String limits CRED_MAX_CREDENTIAL_BLOB_SIZE = 512, // Maximum size of the CredBlob field (in bytes) CRED_MAX_STRING_LENGTH = 256, // Maximum length of the various credential string fields (in characters) CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256), // Maximum length of the UserName field. The worst case is <User>@<DnsDomain> CRED_MAX_GENERIC_TARGET_NAME_LENGTH = 32767, // Maximum length of the TargetName field for CRED_TYPE_GENERIC (in characters) CRED_MAX_DOMAIN_TARGET_NAME_LENGTH = (256 + 1 + 80), // Maximum length of the TargetName field for CRED_TYPE_DOMAIN_* (in characters). Largest one is <DfsRoot>\<DfsShare> CRED_MAX_VALUE_SIZE = 256, // Maximum size of the Credential Attribute Value field (in bytes) CRED_MAX_ATTRIBUTES = 64, // Maximum number of attributes per credential CREDUI_MAX_MESSAGE_LENGTH = 32767, CREDUI_MAX_CAPTION_LENGTH = 128, CREDUI_MAX_GENERIC_TARGET_LENGTH = CRED_MAX_GENERIC_TARGET_NAME_LENGTH, CREDUI_MAX_DOMAIN_TARGET_LENGTH = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH, CREDUI_MAX_USERNAME_LENGTH = CRED_MAX_USERNAME_LENGTH, CREDUI_MAX_PASSWORD_LENGTH = (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2); internal enum CRED_PERSIST : uint { NONE = 0, SESSION = 1, LOCAL_MACHINE = 2, ENTERPRISE = 3, } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct NativeCredential { public uint flags; public uint type; public string targetName; public string comment; public int lastWritten_lowDateTime; public int lastWritten_highDateTime; public uint credentialBlobSize; public IntPtr credentialBlob; public uint persist; public uint attributeCount; public IntPtr attributes; public string targetAlias; public string userName; }; [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredReadW")] public static extern bool CredRead( [MarshalAs(UnmanagedType.LPWStr)] string targetName, [MarshalAs(UnmanagedType.U4)] uint type, [MarshalAs(UnmanagedType.U4)] uint flags, out IntPtr credential ); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredWriteW")] public static extern bool CredWrite( ref NativeCredential Credential, [MarshalAs(UnmanagedType.U4)] uint flags ); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport(advapi32Dll, SetLastError = true)] public static extern bool CredFree( IntPtr buffer ); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport(credUIDll, EntryPoint = "CredUIPromptForCredentialsW", CharSet = CharSet.Unicode)] public static extern CredUIReturnCodes CredUIPromptForCredentials( CREDUI_INFO pUiInfo, // Optional (one can pass null here) [MarshalAs(UnmanagedType.LPWStr)] string targetName, IntPtr Reserved, // Must be 0 (IntPtr.Zero) int iError, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszUserName, [MarshalAs(UnmanagedType.U4)] uint ulUserNameMaxChars, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPassword, [MarshalAs(UnmanagedType.U4)] uint ulPasswordMaxChars, ref int pfSave, CREDUI_FLAGS dwFlags); /// <returns> /// Win32 system errors: /// NO_ERROR /// ERROR_INVALID_ACCOUNT_NAME /// ERROR_INSUFFICIENT_BUFFER /// ERROR_INVALID_PARAMETER /// </returns> [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport(credUIDll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredUIParseUserNameW")] public static extern CredUIReturnCodes CredUIParseUserName( [MarshalAs(UnmanagedType.LPWStr)] string strUserName, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder strUser, [MarshalAs(UnmanagedType.U4)] uint iUserMaxChars, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder strDomain, [MarshalAs(UnmanagedType.U4)] uint iDomainMaxChars ); } struct User32RECT { public int left; public int top; public int right; public int bottom; public int Width { get { return right - left; } } public int Height { get { return bottom - top; } } } [Guid("22F03340-547D-101B-8E65-08002B2BD119")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface ICreateErrorInfo { int SetGUID( ref Guid rguid ); int SetSource(string szSource); int SetDescription(string szDescription); int SetHelpFile(string szHelpFile); int SetHelpContext(uint dwHelpContext); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct WIN32_FIND_DATA { public uint dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HeatMap { using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using System.Diagnostics; public class HeatMap { public List<PointWithValue> Points { get; set; } public List<RGB> Colors; public HeatMapLimits Limits; public int Width; public int Height; public double ColorLimit = 0.35; public int NumberOfLevels = 20; public int MinValue = -100; public int MaxValue = 100; public bool LevelsEnabled = false; protected bool useDefaultColors = true; public bool UseDefaultColors { get { return useDefaultColors; } set { useDefaultColors = value; if (value) SetDefaultColors(); else Colors = null; } } public HeatMap() { Points = new List<PointWithValue>(); Limits = new HeatMapLimits { xMin = 0, xMax = 0, yMin = 0, yMax = 0 }; SetDefaultColors(); } protected void SetDefaultColors() { Colors = new List<RGB>(); Colors.Add(new RGB(85, 78, 177)); Colors.Add(new RGB(67, 105, 196)); Colors.Add(new RGB(64, 160, 180)); Colors.Add(new RGB(78, 194, 98)); Colors.Add(new RGB(108, 209, 80)); Colors.Add(new RGB(190, 228, 61)); Colors.Add(new RGB(235, 224, 53)); Colors.Add(new RGB(234, 185, 57)); Colors.Add(new RGB(233, 143, 67)); Colors.Add(new RGB(225, 94, 93)); Colors.Add(new RGB(147, 23, 78)); Colors.Add(new RGB(114, 22, 56)); Colors.Add(new RGB(84, 16, 41)); Colors.Add(new RGB(43, 0, 1)); } int CrossProduct(HeatMapPoint o, HeatMapPoint a, HeatMapPoint b) { return (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X); } long SquareDistance(HeatMapPoint p0, HeatMapPoint p1) { long x = p0.X - p1.X, y = p0.Y - p1.Y; return x * x + y * y; } double HUE2RGB(double p, double q, double t) { if (t < 0) { t += 1; } else if (t > 1) { t -= 1; } if (t >= 0.66) { return p; } else if (t >= 0.5) { return p + (q - p) * (0.66 - t) * 6; } else if (t >= 0.33) { return q; } else { return p + (q - p) * 6 * t; } } RGB HSL2RGB(double h, double s, double l, double a = 1) { double r, g, b; if (s == 0) { r = g = b = l; } else { double q = l < 0.5 ? l * (1 + s) : l + s - l * s; double p = 2 * l - q; r = HUE2RGB(p, q, h + 0.333); g = HUE2RGB(p, q, h); b = HUE2RGB(p, q, h - 0.333); } var Result = new RGB((int)(r * 255) | 0, (int)(g * 255) | 0, (int)(b * 255) | 0, (int)(a * 255)); if (Result.R > 255) Result.R = 255; if (Result.G > 255) Result.G = 255; if (Result.B > 255) Result.B = 255; if (Result.A > 255) Result.A = 255; return Result; } public HSL GetHSLColor(double value) { double temperature = 0, diff = MaxValue - MinValue; if (value < MinValue) { value = MinValue; } if (value > MaxValue) { value = MaxValue; } temperature = 1 - (1 - ColorLimit) - (((value - MinValue) * ColorLimit) / diff); if (LevelsEnabled) { temperature = Math.Round(temperature * NumberOfLevels) / NumberOfLevels; } double l = 0.5; double s = 1; double a = 1; return new HSL() { H = temperature, S = s, L = l, A = a }; } public RGB GetRGBColor(double value) { if (Colors == null) { var hsl = GetHSLColor(value); return HSL2RGB(hsl.H, hsl.S, hsl.L, hsl.A); } else { int index = 0; if (MinValue < 0) { var v = value < 0 ? Math.Abs(MinValue) - Math.Abs(value) : value + Math.Abs(MaxValue); var maxV = Math.Abs(MaxValue) + Math.Abs(MinValue); index = (int)(v * (Colors.Count) / maxV); } else { index = (int)(value * Colors.Count / MaxValue); } if (index == Colors.Count) index--; return Colors[index]; } } double GetPointValue(int limit, PointWithValue point, List<PointWithDistance> pointsWithDistance) { long distance = 0; double inv = 0.0, t = 0.0, b = 0.0; for (int i = 0; i < this.Points.Count; i++) { var p = Points[i]; long x = point.X - p.X, y = point.Y - p.Y; distance = x * x + y * y; if (distance == 0) { return p.Value; } var pwd = pointsWithDistance[i]; pwd.Distance = distance; pwd.Point = p; } for (int i = 0; i < limit; i++) { var P = pointsWithDistance[i]; inv = 1.0 / (P.Distance * P.Distance); t = t + inv * P.Point.Value; b = b + inv; } return t / b; } public Bitmap Draw() { Bitmap result = new Bitmap(Width, Height); if (Limits.xMax == 0 && Limits.xMin == 0 && Limits.yMax == 0 && Limits.yMin == 0) { this.Limits = new HeatMapLimits { xMin = 0, xMax = Width, yMin = 0, yMax = Height }; } var pointsWithDistance = new List<PointWithDistance>(Points.Count); for (var i = 0; i < Points.Count; i++) { pointsWithDistance.Add(new PointWithDistance()); } int x = Limits.xMin; int y = Limits.yMin; int w = Width; int wy = w * y; int pointsLimit = Points.Count; int xStart = Limits.xMin; int xEnd = Limits.xMax; int yEnd = Limits.yMax; bool isEmpty = true; while (y < yEnd) { var val = GetPointValue(pointsLimit, new PointWithValue() { X = x, Y = y }, pointsWithDistance); if (val != -255) { isEmpty = false; int imgX = x - Limits.xMin; int imgY = y - Limits.yMin; if (imgX < Width && imgY < Height && imgX >= 0 && imgY >= 0) { var col = GetRGBColor(val); var imgCol = Color.FromArgb(col.A, col.R, col.G, col.B); result.SetPixel(imgX, imgY, imgCol); } } x = x + 1; if (x > xEnd) { x = xStart; y = y + 1; wy = w * y; } } if (isEmpty) return null; return result; } } public class HeatMapPoint { public int X; public int Y; } public class PointWithValue : HeatMapPoint { public double Value; } public class PointWithDistance { public long Distance { get; set; } public PointWithValue Point { get; set; } } public class HeatMapLimits { public int xMin; public int xMax; public int yMin; public int yMax; } public class RGB { public RGB(int r, int g, int b, int a = 255) { R = r; G = g; B = b; A = a; } public int R; public int G; public int B; public int A; } public class HSL { public double H; public double S; public double L; public double A; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; using System.Threading; using log4net; using SharpRemote.CodeGeneration; // ReSharper disable CheckNamespace namespace SharpRemote.Hosting // ReSharper restore CheckNamespace { /// <summary> /// Used in conjunction with a <see cref="OutOfProcessSilo" /> to host objects in a remote process. /// </summary> /// <example> /// public static void main(string[] arguments) /// { /// try /// { /// // Put any additional/required initialization here. /// using (var silo = new OutOfProcessSiloServer(arguments)) /// { /// // This is the place to register any additional interfaces with this silo /// // silo.CreateServant(id, (IMyCustomInterface)new MyCustomImplementation()); /// silo.Run(); /// } /// } /// catch(Exception e) /// { /// // This will marshall the exception back to the parent process so you can /// // actually know and programmatically react to the failure. /// OutOfProcessSiloServer.ReportException(e); /// } /// } /// </example> public sealed class OutOfProcessSiloServer : IRemotingEndPoint { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly ITypeResolver _customTypeResolver; private readonly ISocketEndPoint _endPoint; internal ISocketEndPoint EndPoint => _endPoint; private readonly Process _parentProcess; private readonly int? _parentProcessId; private readonly DefaultImplementationRegistry _registry; private readonly ManualResetEvent _waitHandle; /// <summary> /// Initializes a new silo server. /// </summary> /// <param name="args">The command line arguments given to the Main() method</param> /// <param name="customTypeResolver">The type resolver, if any, responsible for resolving Type objects by their assembly qualified name</param> /// <param name="codeGenerator">The code generator to create proxy and servant types</param> /// <param name="heartbeatSettings">The settings for heartbeat mechanism, if none are specified, then default settings are used</param> /// <param name="latencySettings">The settings for latency measurements, if none are specified, then default settings are used</param> /// <param name="endPointSettings">The settings for the endpoint itself (max. number of concurrent calls, etc...)</param> /// <param name="endPointName">The name of this silo, used for debugging (and logging)</param> public OutOfProcessSiloServer(string[] args, ITypeResolver customTypeResolver = null, ICodeGenerator codeGenerator = null, HeartbeatSettings heartbeatSettings = null, LatencySettings latencySettings = null, EndPointSettings endPointSettings = null, string endPointName = null) { Log.InfoFormat("Silo Server starting, args ({0}): \"{1}\", {2} custom type resolver", args.Length, string.Join(" ", args), customTypeResolver != null ? "with" : "without" ); int pid; if (args.Length >= 1 && int.TryParse(args[0], out pid)) { _parentProcessId = pid; _parentProcess = Process.GetProcessById(pid); _parentProcess.EnableRaisingEvents = true; _parentProcess.Exited += ParentProcessOnExited; } if (Log.IsDebugEnabled) { Log.DebugFormat("Args.Length: {0}", args.Length); } _registry = new DefaultImplementationRegistry(); _waitHandle = new ManualResetEvent(false); _customTypeResolver = customTypeResolver; _endPoint = new SocketEndPoint(EndPointType.Server, endPointName, codeGenerator: codeGenerator, heartbeatSettings: heartbeatSettings, latencySettings: latencySettings, endPointSettings: endPointSettings ); _endPoint.OnConnected += EndPointOnOnConnected; _endPoint.OnDisconnected += EndPointOnOnDisconnected; _endPoint.OnFailure += EndPointOnOnFailure; } private void EndPointOnOnFailure(EndPointDisconnectReason endPointDisconnectReason, ConnectionId id) { OnFailure?.Invoke(endPointDisconnectReason, id); } private void EndPointOnOnDisconnected(EndPoint remoteEndPoint, ConnectionId connectionId) { OnDisconnected?.Invoke(remoteEndPoint, connectionId); } private void EndPointOnOnConnected(EndPoint remoteEndPoint, ConnectionId connectionId) { OnConnected?.Invoke(remoteEndPoint, connectionId); } /// <summary> /// The process id of the parent process, as specified in the command line arguments or null /// when no id was specified. /// </summary> public int? ParentProcessId => _parentProcessId; /// <inheritdoc /> public void Dispose() { _waitHandle.Dispose(); _endPoint.Dispose(); } /// <inheritdoc /> public string Name => _endPoint.Name; /// <inheritdoc /> public bool IsConnected => _endPoint.IsConnected; /// <inheritdoc /> public long NumProxiesCollected => _endPoint.NumProxiesCollected; /// <inheritdoc /> public long NumServantsCollected => _endPoint.NumServantsCollected; /// <inheritdoc /> public long NumBytesSent => _endPoint.NumBytesSent; /// <inheritdoc /> public long NumBytesReceived => _endPoint.NumBytesReceived; /// <inheritdoc /> public long NumMessagesSent => _endPoint.NumMessagesSent; /// <inheritdoc /> public long NumMessagesReceived => _endPoint.NumMessagesReceived; /// <inheritdoc /> public long NumCallsInvoked => _endPoint.NumCallsInvoked; /// <inheritdoc /> public long NumCallsAnswered => _endPoint.NumCallsAnswered; /// <inheritdoc /> public long NumPendingMethodCalls => _endPoint.NumPendingMethodCalls; /// <inheritdoc /> public long NumPendingMethodInvocations => _endPoint.NumPendingMethodInvocations; /// <inheritdoc /> public TimeSpan? AverageRoundTripTime => _endPoint.AverageRoundTripTime; /// <inheritdoc /> public TimeSpan TotalGarbageCollectionTime => _endPoint.TotalGarbageCollectionTime; /// <inheritdoc /> public EndPointSettings EndPointSettings => _endPoint.EndPointSettings; /// <inheritdoc /> public LatencySettings LatencySettings => _endPoint.LatencySettings; /// <inheritdoc /> public HeartbeatSettings HeartbeatSettings => _endPoint.HeartbeatSettings; /// <inheritdoc /> public ConnectionId CurrentConnectionId => _endPoint.CurrentConnectionId; /// <inheritdoc /> public EndPoint LocalEndPoint => _endPoint.LocalEndPoint; /// <inheritdoc /> public EndPoint RemoteEndPoint => _endPoint.RemoteEndPoint; /// <inheritdoc /> public IEnumerable<IProxy> Proxies => _endPoint.Proxies; /// <summary> /// /// </summary> public event Action<EndPoint, ConnectionId> OnConnected; /// <summary> /// /// </summary> public event Action<EndPoint, ConnectionId> OnDisconnected; /// <summary> /// /// </summary> public event Action<EndPointDisconnectReason, ConnectionId> OnFailure; /// <inheritdoc /> public void Disconnect() { _endPoint.Disconnect(); } /// <inheritdoc /> public T CreateProxy<T>(ulong objectId) where T : class { return _endPoint.CreateProxy<T>(objectId); } /// <inheritdoc /> public T GetProxy<T>(ulong objectId) where T : class { return _endPoint.GetProxy<T>(objectId); } /// <inheritdoc /> public IServant CreateServant<T>(ulong objectId, T subject) where T : class { return _endPoint.CreateServant(objectId, subject); } /// <inheritdoc /> public T RetrieveSubject<T>(ulong objectId) where T : class { return _endPoint.RetrieveSubject<T>(objectId); } /// <inheritdoc /> public T GetExistingOrCreateNewProxy<T>(ulong objectId) where T : class { return _endPoint.GetExistingOrCreateNewProxy<T>(objectId); } /// <inheritdoc /> public IServant GetExistingOrCreateNewServant<T>(T subject) where T : class { return _endPoint.GetExistingOrCreateNewServant(subject); } /// <summary> /// Registers a default implementation for the given interface so that /// <see cref="ISilo.CreateGrain{T}(object[])" /> can be used to create grains. /// </summary> /// <typeparam name="TInterface"></typeparam> /// <typeparam name="TImplementation"></typeparam> public void RegisterDefaultImplementation<TInterface, TImplementation>() where TImplementation : TInterface where TInterface : class { _registry.RegisterDefaultImplementation(typeof (TImplementation), typeof (TInterface)); } /// <summary> /// Runs the server and blocks until a shutdown command is received because the /// <see cref="OutOfProcessSilo" /> is being disposed of or because the parent process /// quits unexpectedly. /// </summary> /// <remarks> /// Binds the endpoint to <see cref="IPAddress.Any"/>. /// </remarks> public void Run() { Run(IPAddress.Any); } /// <summary> /// Runs the server and blocks until a shutdown command is received because the /// <see cref="OutOfProcessSilo" /> is being disposed of or because the parent process /// quits unexpectedly. /// </summary> /// <param name="address">The ip-address this endpoint shall bind itself to</param> public void Run(IPAddress address) { Run(address, SocketEndPoint.Constants.MinDefaultPort, SocketEndPoint.Constants.MaxDefaultPort); } /// <summary> /// Runs the server and blocks until a shutdown command is received because the /// <see cref="OutOfProcessSilo" /> is being disposed of or because the parent process /// quits unexpectedly. /// </summary> /// <param name="address">The ip-address this endpoint shall bind itself to</param> /// <param name="minPort">The minimum port number to which this endpoint may be bound to</param> /// <param name="maxPort">The maximum port number to which this endpoint may be bound to</param> public void Run(IPAddress address, ushort minPort, ushort maxPort) { Console.WriteLine(ProcessWatchdog.Constants.BootingMessage); try { using (_endPoint) using (var host = new SubjectHost(_endPoint, _registry, OnSubjectHostDisposed, _customTypeResolver)) { _endPoint.CreateServant(OutOfProcessSilo.Constants.SubjectHostId, (ISubjectHost) host); _endPoint.Bind(address, minPort, maxPort); Console.WriteLine(_endPoint.LocalEndPoint.Port); Log.InfoFormat("Port sent to host process"); Console.WriteLine(ProcessWatchdog.Constants.ReadyMessage); _waitHandle.WaitOne(); Console.WriteLine(ProcessWatchdog.Constants.ShutdownMessage); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.Message); } } private void ParentProcessOnExited(object sender, EventArgs eventArgs) { Log.InfoFormat("Parent process terminated unexpectedly (exit code: {0}), shutting down...", _parentProcess.ExitCode ); Shutdown(); } private void Shutdown() { OnSubjectHostDisposed(); } private void OnSubjectHostDisposed() { Log.Info("Parent process orders shutdown..."); _waitHandle.Set(); } /// <summary> /// Shall be called by user code when an exception occurred during startup of the server /// and shall be reported back to the <see cref="OutOfProcessSilo"/>. /// </summary> /// <param name="exception"></param> public static void ReportException(Exception exception) { var encodedException = EncodeException(exception); Console.WriteLine("{0}{1}", ProcessWatchdog.Constants.ExceptionMessage, encodedException); } internal static string EncodeException(Exception exception) { using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { AbstractEndPoint.WriteException(writer, exception); var length = (int)stream.Length; var data = stream.GetBuffer(); var encodedException = Convert.ToBase64String(data, 0, length); return encodedException; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XSSF.Model { using System.Collections.Generic; using OpenXmlFormats.Spreadsheet; using System; using System.IO; using NPOI.OpenXml4Net.OPC; using System.Xml; using System.Security; using System.Text.RegularExpressions; using System.Text; /** * Table of strings shared across all sheets in a workbook. * <p> * A workbook may contain thousands of cells Containing string (non-numeric) data. Furthermore this data is very * likely to be repeated across many rows or columns. The goal of implementing a single string table that is shared * across the workbook is to improve performance in opening and saving the file by only Reading and writing the * repetitive information once. * </p> * <p> * Consider for example a workbook summarizing information for cities within various countries. There may be a * column for the name of the country, a column for the name of each city in that country, and a column * Containing the data for each city. In this case the country name is repetitive, being duplicated in many cells. * In many cases the repetition is extensive, and a tremendous savings is realized by making use of a shared string * table when saving the workbook. When displaying text in the spreadsheet, the cell table will just contain an * index into the string table as the value of a cell, instead of the full string. * </p> * <p> * The shared string table Contains all the necessary information for displaying the string: the text, formatting * properties, and phonetic properties (for East Asian languages). * </p> * * @author Nick Birch * @author Yegor Kozlov */ public class SharedStringsTable : POIXMLDocumentPart { /** * Array of individual string items in the Shared String table. */ private List<CT_Rst> strings = new List<CT_Rst>(); /** * Maps strings and their indexes in the <code>strings</code> arrays */ private Dictionary<String, int> stmap = new Dictionary<String, int>(); /** * An integer representing the total count of strings in the workbook. This count does not * include any numbers, it counts only the total of text strings in the workbook. */ private int count; /** * An integer representing the total count of unique strings in the Shared String Table. * A string is unique even if it is a copy of another string, but has different formatting applied * at the character level. */ private int uniqueCount; private SstDocument _sstDoc; public SharedStringsTable() : base() { _sstDoc = new SstDocument(); _sstDoc.AddNewSst(); } public SharedStringsTable(PackagePart part) : base(part) { ReadFrom(part.GetInputStream()); } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] public SharedStringsTable(PackagePart part, PackageRelationship rel) : this(part) { } public void ReadFrom(Stream is1) { try { int cnt = 0; XmlDocument xml = ConvertStreamToXml(is1); _sstDoc = SstDocument.Parse(xml, NamespaceManager); CT_Sst sst = _sstDoc.GetSst(); count = (int)sst.count; uniqueCount = (int)sst.uniqueCount; foreach (CT_Rst st in sst.si) { string key = GetKey(st); if (key != null && !stmap.ContainsKey(key)) stmap.Add(key, cnt); strings.Add(st); cnt++; } } catch (XmlException e) { throw new IOException("unable to parse shared strings table", e); } } private String GetKey(CT_Rst st) { return st.XmlText; } /** * Return a string item by index * * @param idx index of item to return. * @return the item at the specified position in this Shared String table. */ public CT_Rst GetEntryAt(int idx) { return strings[idx]; } /** * Return an integer representing the total count of strings in the workbook. This count does not * include any numbers, it counts only the total of text strings in the workbook. * * @return the total count of strings in the workbook */ public int Count { get { return count; } } /** * Returns an integer representing the total count of unique strings in the Shared String Table. * A string is unique even if it is a copy of another string, but has different formatting applied * at the character level. * * @return the total count of unique strings in the workbook */ public int UniqueCount { get { return uniqueCount; } } /** * Add an entry to this Shared String table (a new value is appened to the end). * * <p> * If the Shared String table already Contains this <code>CT_Rst</code> bean, its index is returned. * Otherwise a new entry is aded. * </p> * * @param st the entry to add * @return index the index of Added entry */ public int AddEntry(CT_Rst st) { String s = GetKey(st); count++; if (stmap.ContainsKey(s)) { return stmap[s]; } uniqueCount++; //create a CT_Rst bean attached to this SstDocument and copy the argument CT_Rst into it CT_Rst newSt = new CT_Rst(); _sstDoc.GetSst().si.Add(newSt); newSt.Set(st); int idx = strings.Count; stmap[s] = idx; strings.Add(newSt); return idx; } /** * Provide low-level access to the underlying array of CT_Rst beans * * @return array of CT_Rst beans */ public IList<CT_Rst> Items { get { return strings.AsReadOnly(); } } /** * * this table out as XML. * * @param out The stream to write to. * @throws IOException if an error occurs while writing. */ public void WriteTo(Stream out1) { // the following two lines turn off writing CDATA // see Bugzilla 48936 //options.SetSaveCDataLengthThreshold(1000000); //options.SetSaveCDataEntityCountThreshold(-1); CT_Sst sst = _sstDoc.GetSst(); sst.count = count; sst.uniqueCount = uniqueCount; //re-create the sst table every time saving a workbook _sstDoc.Save(out1); } protected internal override void Commit() { PackagePart part = GetPackagePart(); //Stream out1 = part.GetInputStream(); Stream out1 = part.GetOutputStream(); WriteTo(out1); out1.Close(); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// Pipeline /// </summary> [DataContract(Name = "Pipeline")] public partial class Pipeline : IEquatable<Pipeline>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Pipeline" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="organization">organization.</param> /// <param name="name">name.</param> /// <param name="displayName">displayName.</param> /// <param name="fullName">fullName.</param> /// <param name="weatherScore">weatherScore.</param> /// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param> /// <param name="latestRun">latestRun.</param> public Pipeline(string _class = default(string), string organization = default(string), string name = default(string), string displayName = default(string), string fullName = default(string), int weatherScore = default(int), int estimatedDurationInMillis = default(int), PipelinelatestRun latestRun = default(PipelinelatestRun)) { this.Class = _class; this.Organization = organization; this.Name = name; this.DisplayName = displayName; this.FullName = fullName; this.WeatherScore = weatherScore; this.EstimatedDurationInMillis = estimatedDurationInMillis; this.LatestRun = latestRun; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name = "organization", EmitDefaultValue = false)] public string Organization { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name = "fullName", EmitDefaultValue = false)] public string FullName { get; set; } /// <summary> /// Gets or Sets WeatherScore /// </summary> [DataMember(Name = "weatherScore", EmitDefaultValue = false)] public int WeatherScore { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name = "estimatedDurationInMillis", EmitDefaultValue = false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets LatestRun /// </summary> [DataMember(Name = "latestRun", EmitDefaultValue = false)] public PipelinelatestRun LatestRun { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Pipeline {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" LatestRun: ").Append(LatestRun).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Pipeline); } /// <summary> /// Returns true if Pipeline instances are equal /// </summary> /// <param name="input">Instance of Pipeline to be compared</param> /// <returns>Boolean</returns> public bool Equals(Pipeline input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.WeatherScore == input.WeatherScore || this.WeatherScore.Equals(input.WeatherScore) ) && ( this.EstimatedDurationInMillis == input.EstimatedDurationInMillis || this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis) ) && ( this.LatestRun == input.LatestRun || (this.LatestRun != null && this.LatestRun.Equals(input.LatestRun)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.Organization != null) { hashCode = (hashCode * 59) + this.Organization.GetHashCode(); } if (this.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } if (this.DisplayName != null) { hashCode = (hashCode * 59) + this.DisplayName.GetHashCode(); } if (this.FullName != null) { hashCode = (hashCode * 59) + this.FullName.GetHashCode(); } hashCode = (hashCode * 59) + this.WeatherScore.GetHashCode(); hashCode = (hashCode * 59) + this.EstimatedDurationInMillis.GetHashCode(); if (this.LatestRun != null) { hashCode = (hashCode * 59) + this.LatestRun.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; /// <summary> /// Sends log messages to the remote instance of NLog Viewer. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/NLogViewer-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/NLogViewer/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/NLogViewer/Simple/Example.cs" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will crawl. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// </example> [Target("NLogViewer")] public class NLogViewerTarget : NetworkTarget, IIncludeContext { private readonly Log4JXmlEventLayout _layout = new Log4JXmlEventLayout(); /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NLogViewerTarget() { this.Parameters = new List<NLogViewerParameterInfo>(); this.Renderer.Parameters = this.Parameters; NewLine = false; } /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NLogViewerTarget(string name) : this() { this.Name = name; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNLogData { get { return this.Renderer.IncludeNLogData; } set { this.Renderer.IncludeNLogData = value; } } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get { return this.Renderer.AppInfo; } set { this.Renderer.AppInfo = value; } } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get { return this.Renderer.IncludeCallSite; } set { this.Renderer.IncludeCallSite = value; } } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get { return this.Renderer.IncludeSourceInfo; } set { this.Renderer.IncludeSourceInfo = value; } } #endif /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext"/> dictionary contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get { return this.Renderer.IncludeMdc; } set { this.Renderer.IncludeMdc = value; } } /// <summary> /// Gets or sets a value indicating whether to include <see cref="NestedDiagnosticsContext"/> stack contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get { return this.Renderer.IncludeNdc; } set { this.Renderer.IncludeNdc = value; } } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsLogicalContext"/> dictionary contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdlc { get { return this.Renderer.IncludeMdlc; } set { this.Renderer.IncludeMdlc = value; } } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdlc { get { return this.Renderer.IncludeNdlc; } set { this.Renderer.IncludeNdlc = value; } } #endif /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeAllProperties { get { return this.Renderer.IncludeAllProperties; } set { this.Renderer.IncludeAllProperties = value; } } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> public string NdcItemSeparator { get { return this.Renderer.NdcItemSeparator; } set { this.Renderer.NdcItemSeparator = value; } } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a named parameter. /// </summary> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")] public IList<NLogViewerParameterInfo> Parameters { get; private set; } /// <summary> /// Gets the layout renderer which produces Log4j-compatible XML events. /// </summary> public Log4JXmlEventLayoutRenderer Renderer { get { return this._layout.Renderer; } } /// <summary> /// Gets or sets the instance of <see cref="Log4JXmlEventLayout"/> that is used to format log messages. /// </summary> /// <docgen category='Layout Options' order='10' /> public override Layout Layout { get { return this._layout; } set { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Transactions; using Abp.Auditing; using Abp.Dependency; using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Extensions; using Abp.Json; using Abp.Runtime.Session; using Abp.Timing; using Castle.Core.Logging; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace Abp.EntityHistory { public class EntityHistoryHelper : IEntityHistoryHelper, ITransientDependency { public ILogger Logger { get; set; } public IAbpSession AbpSession { get; set; } public IClientInfoProvider ClientInfoProvider { get; set; } public IEntityHistoryStore EntityHistoryStore { get; set; } private readonly IEntityHistoryConfiguration _configuration; private readonly IUnitOfWorkManager _unitOfWorkManager; private bool IsEntityHistoryEnabled { get { if (!_configuration.IsEnabled) { return false; } if (!_configuration.IsEnabledForAnonymousUsers && (AbpSession?.UserId == null)) { return false; } return true; } } public EntityHistoryHelper( IEntityHistoryConfiguration configuration, IUnitOfWorkManager unitOfWorkManager) { _configuration = configuration; _unitOfWorkManager = unitOfWorkManager; AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; ClientInfoProvider = NullClientInfoProvider.Instance; EntityHistoryStore = NullEntityHistoryStore.Instance; } public virtual EntityChangeSet CreateEntityChangeSet(ICollection<EntityEntry> entityEntries) { var changeSet = new EntityChangeSet { // Fill "who did this change" BrowserInfo = ClientInfoProvider.BrowserInfo.TruncateWithPostfix(EntityChangeSet.MaxBrowserInfoLength), ClientIpAddress = ClientInfoProvider.ClientIpAddress.TruncateWithPostfix(EntityChangeSet.MaxClientIpAddressLength), ClientName = ClientInfoProvider.ComputerName.TruncateWithPostfix(EntityChangeSet.MaxClientNameLength), ImpersonatorTenantId = AbpSession.ImpersonatorTenantId, ImpersonatorUserId = AbpSession.ImpersonatorUserId, TenantId = AbpSession.TenantId, UserId = AbpSession.UserId }; if (!IsEntityHistoryEnabled) { return changeSet; } foreach (var entry in entityEntries) { if (!ShouldSaveEntityHistory(entry)) { continue; } var entityChangeInfo = CreateEntityChangeInfo(entry); if (entityChangeInfo == null) { continue; } changeSet.EntityChanges.Add(entityChangeInfo); } return changeSet; } public virtual async Task SaveAsync(EntityChangeSet changeSet) { if (!IsEntityHistoryEnabled) { return; } if (changeSet.EntityChanges.Count == 0) { return; } UpdateChangeSet(changeSet); using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { await EntityHistoryStore.SaveAsync(changeSet); await uow.CompleteAsync(); } } [CanBeNull] private EntityChange CreateEntityChangeInfo(EntityEntry entityEntry) { var entity = entityEntry.Entity; EntityChangeType changeType; switch (entityEntry.State) { case EntityState.Added: changeType = EntityChangeType.Created; break; case EntityState.Deleted: changeType = EntityChangeType.Deleted; break; case EntityState.Modified: changeType = IsDeleted(entityEntry) ? EntityChangeType.Deleted : EntityChangeType.Updated; break; case EntityState.Detached: case EntityState.Unchanged: default: Logger.Error("Unexpected EntityState!"); return null; } var entityId = GetEntityId(entity); if (entityId == null && changeType != EntityChangeType.Created) { Logger.Error("Unexpected null value for entityId!"); return null; } var entityType = entity.GetType(); var entityChangeInfo = new EntityChange { ChangeType = changeType, EntityEntry = entityEntry, // [NotMapped] EntityId = entityId, EntityTypeAssemblyQualifiedName = entityType.AssemblyQualifiedName, PropertyChanges = GetPropertyChanges(entityEntry) }; return entityChangeInfo; } private DateTime GetChangeTime(EntityChange entityChange) { var entity = entityChange.EntityEntry.As<EntityEntry>().Entity; switch (entityChange.ChangeType) { case EntityChangeType.Created: return (entity as IHasCreationTime)?.CreationTime ?? Clock.Now; case EntityChangeType.Deleted: return (entity as IHasDeletionTime)?.DeletionTime ?? Clock.Now; case EntityChangeType.Updated: return (entity as IHasModificationTime)?.LastModificationTime ?? Clock.Now; default: Logger.Error("Unexpected EntityState!"); return Clock.Now; } } private string GetEntityId(object entityAsObj) { return entityAsObj .GetType().GetProperty("Id")? .GetValue(entityAsObj)? .ToJsonString(); } /// <summary> /// Gets the property changes for this entry. /// </summary> private ICollection<EntityPropertyChange> GetPropertyChanges(EntityEntry entityEntry) { var propertyChanges = new List<EntityPropertyChange>(); var properties = entityEntry.Metadata.GetProperties(); var isCreatedOrDeleted = IsCreated(entityEntry) || IsDeleted(entityEntry); foreach (var property in properties) { var propertyEntry = entityEntry.Property(property.Name); if (ShouldSavePropertyHistory(propertyEntry, isCreatedOrDeleted)) { propertyChanges.Add(new EntityPropertyChange { NewValue = propertyEntry.CurrentValue.ToJsonString(), OriginalValue = propertyEntry.OriginalValue.ToJsonString(), PropertyName = property.Name, PropertyTypeName = property.ClrType.AssemblyQualifiedName }); } } return propertyChanges; } private bool IsCreated(EntityEntry entityEntry) { return entityEntry.State == EntityState.Added; } private bool IsDeleted(EntityEntry entityEntry) { if (entityEntry.State == EntityState.Deleted) { return true; } var entity = entityEntry.Entity; return entity is ISoftDelete && entity.As<ISoftDelete>().IsDeleted; } private bool ShouldSaveEntityHistory(EntityEntry entityEntry, bool defaultValue = false) { if (entityEntry.State == EntityState.Detached || entityEntry.State == EntityState.Unchanged) { return false; } if (_configuration.IgnoredTypes.Any(t => t.IsInstanceOfType(entityEntry.Entity))) { return false; } var entityType = entityEntry.Entity.GetType(); if (!EntityHelper.IsEntity(entityType)) { return false; } if (!entityType.IsPublic) { return false; } if (entityType.GetTypeInfo().IsDefined(typeof(AuditedAttribute), true)) { return true; } if (entityType.GetTypeInfo().IsDefined(typeof(DisableAuditingAttribute), true)) { return false; } if (_configuration.Selectors.Any(selector => selector.Predicate(entityType))) { return true; } var properties = entityEntry.Metadata.GetProperties(); if (properties.Any(p => p.PropertyInfo?.IsDefined(typeof(AuditedAttribute)) ?? false)) { return true; } return defaultValue; } private bool ShouldSavePropertyHistory(PropertyEntry propertyEntry, bool defaultValue) { var propertyInfo = propertyEntry.Metadata.PropertyInfo; if (propertyInfo.IsDefined(typeof(DisableAuditingAttribute), true)) { return false; } var classType = propertyInfo.DeclaringType; if (classType != null) { if (classType.GetTypeInfo().IsDefined(typeof(DisableAuditingAttribute), true) && !propertyInfo.IsDefined(typeof(AuditedAttribute), true)) { return false; } } var isModified = !(propertyEntry.OriginalValue?.Equals(propertyEntry.CurrentValue) ?? propertyEntry.CurrentValue == null); if (isModified) { return true; } return defaultValue; } /// <summary> /// Updates change time, entity id and foreign keys after SaveChanges is called. /// </summary> private void UpdateChangeSet(EntityChangeSet changeSet) { foreach (var entityChangeInfo in changeSet.EntityChanges) { /* Update change time */ entityChangeInfo.ChangeTime = GetChangeTime(entityChangeInfo); /* Update entity id */ var entityEntry = entityChangeInfo.EntityEntry.As<EntityEntry>(); entityChangeInfo.EntityId = GetEntityId(entityEntry.Entity); /* Update foreign keys */ var foreignKeys = entityEntry.Metadata.GetForeignKeys(); foreach (var foreignKey in foreignKeys) { foreach (var property in foreignKey.Properties) { var propertyEntry = entityEntry.Property(property.Name); var propertyChange = entityChangeInfo.PropertyChanges.FirstOrDefault(pc => pc.PropertyName == property.Name); if (propertyChange == null) { if (!(propertyEntry.OriginalValue?.Equals(propertyEntry.CurrentValue) ?? propertyEntry.CurrentValue == null)) { // Add foreign key entityChangeInfo.PropertyChanges.Add(new EntityPropertyChange { NewValue = propertyEntry.CurrentValue.ToJsonString(), OriginalValue = propertyEntry.OriginalValue.ToJsonString(), PropertyName = property.Name, PropertyTypeName = property.ClrType.AssemblyQualifiedName }); } continue; } if (propertyChange.OriginalValue == propertyChange.NewValue) { var newValue = propertyEntry.CurrentValue.ToJsonString(); if (newValue == propertyChange.NewValue) { // No change entityChangeInfo.PropertyChanges.Remove(propertyChange); } else { // Update foreign key propertyChange.NewValue = newValue; } } } } } } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Data.SqlServerCe; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.Tools; namespace MLifter.DAL.DB.MsSqlCe { /// <summary> /// MsSqlCeQueryTypesConnector /// </summary> /// <remarks>Documented by Dev08, 2009-01-13</remarks> class MsSqlCeQueryTypesConnector : IDbQueryTypesConnector { private static Dictionary<ConnectionStringStruct, MsSqlCeQueryTypesConnector> instances = new Dictionary<ConnectionStringStruct, MsSqlCeQueryTypesConnector>(); public static MsSqlCeQueryTypesConnector GetInstance(ParentClass ParentClass) { lock (instances) { ConnectionStringStruct connection = ParentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new MsSqlCeQueryTypesConnector(ParentClass)); return instances[connection]; } } private ParentClass Parent; private MsSqlCeQueryTypesConnector(ParentClass ParentClass) { Parent = ParentClass; Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed); } void Parent_DictionaryClosed(object sender, EventArgs e) { IParent Parent = sender as IParent; instances.Remove(Parent.Parent.CurrentUser.ConnectionString); } /// <summary> /// Gets the settings value. /// </summary> /// <param name="queryTypeId">The query type id.</param> /// <param name="cacheObjectType">Type of the cache object.</param> /// <param name="cacheValue">The cache value.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> private void GetSettingsValue(int queryTypeId, CacheObject cacheObjectType, out object cacheValue) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT * FROM \"QueryTypes\" WHERE id=@id"; cmd.Parameters.Add("@id", queryTypeId); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); reader.Read(); int? qid = DbValueConverter.Convert<int>(reader["id"]); bool? imageRecognition = DbValueConverter.Convert<bool>(reader["image_recognition"]); bool? listeningComprehension = DbValueConverter.Convert<bool>(reader["listening_comprehension"]); bool? multipleChoice = DbValueConverter.Convert<bool>(reader["multiple_choice"]); bool? sentenceMode = DbValueConverter.Convert<bool>(reader["sentence"]); bool? wordMode = DbValueConverter.Convert<bool>(reader["word"]); reader.Close(); //cache values DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime); Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesImageRecognition, queryTypeId, expires)] = imageRecognition; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesListeningComprehension, queryTypeId, expires)] = listeningComprehension; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesMultipleChoice, queryTypeId, expires)] = multipleChoice; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesSentence, queryTypeId, expires)] = sentenceMode; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesWord, queryTypeId, expires)] = wordMode; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesId, queryTypeId, expires)] = qid; //set output value switch (cacheObjectType) { case CacheObject.SettingsQueryTypesImageRecognition: cacheValue = imageRecognition; break; case CacheObject.SettingsQueryTypesListeningComprehension: cacheValue = listeningComprehension; break; case CacheObject.SettingsQueryTypesMultipleChoice: cacheValue = multipleChoice; break; case CacheObject.SettingsQueryTypesSentence: cacheValue = sentenceMode; break; case CacheObject.SettingsQueryTypesWord: cacheValue = wordMode; break; case CacheObject.SettingsQueryTypesId: cacheValue = qid; break; default: cacheValue = null; break; } } /// <summary> /// Settingses the cached. /// </summary> /// <param name="queryTypeId">The query type id.</param> /// <param name="cacheObjectType">Type of the cache object.</param> /// <param name="cacheValue">The cache value.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> private bool SettingsCached(int queryTypeId, CacheObject cacheObjectType, out object cacheValue) { int? queryTypeIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsQueryTypesId, queryTypeId)] as int?; cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, queryTypeId)]; return queryTypeIdCached.HasValue;// && (cacheValue != null); } #region IDbQueryTypesConnector Members /// <summary> /// Checks the id. /// </summary> /// <param name="id">The id.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public void CheckId(int id) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT count(*) FROM \"QueryTypes\" WHERE id=@id"; cmd.Parameters.Add("@id", id); if (Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)) < 1) throw new IdAccessException(id); } /// <summary> /// Gets the image recognition. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public bool? GetImageRecognition(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsQueryTypesImageRecognition, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsQueryTypesImageRecognition, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; } /// <summary> /// Sets the image recognition. /// </summary> /// <param name="id">The id.</param> /// <param name="imageRecognition">The image recognition.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public void SetImageRecognition(int id, bool? imageRecognition) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE \"QueryTypes\" SET image_recognition=" + (imageRecognition.HasValue ? "@value" : "null") + " WHERE id=@id"; cmd.Parameters.Add("@id", id); if (imageRecognition.HasValue) cmd.Parameters.Add("@value", imageRecognition); MSSQLCEConn.ExecuteNonQuery(cmd); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesImageRecognition, id, Cache.DefaultSettingsValidationTime)] = imageRecognition; } /// <summary> /// Gets the listening comprehension. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public bool? GetListeningComprehension(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsQueryTypesListeningComprehension, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsQueryTypesListeningComprehension, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; } /// <summary> /// Sets the listening comprehension. /// </summary> /// <param name="id">The id.</param> /// <param name="listeningComprehension">The listening comprehension.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public void SetListeningComprehension(int id, bool? listeningComprehension) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE \"QueryTypes\" SET listening_comprehension=" + (listeningComprehension.HasValue ? "@value" : "null") + " WHERE id=@id"; cmd.Parameters.Add("@id", id); if (listeningComprehension.HasValue) cmd.Parameters.Add("@value", listeningComprehension); MSSQLCEConn.ExecuteNonQuery(cmd); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesListeningComprehension, id, Cache.DefaultSettingsValidationTime)] = listeningComprehension; } /// <summary> /// Gets the multiple choice. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public bool? GetMultipleChoice(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsQueryTypesMultipleChoice, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsQueryTypesMultipleChoice, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; } /// <summary> /// Sets the multiple choice. /// </summary> /// <param name="id">The id.</param> /// <param name="multipleChoice">The multiple choice.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public void SetMultipleChoice(int id, bool? multipleChoice) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE \"QueryTypes\" SET multiple_choice=" + (multipleChoice.HasValue ? "@value" : "null") + " WHERE id=@id"; cmd.Parameters.Add("@id", id); if (multipleChoice.HasValue) cmd.Parameters.Add("@value", multipleChoice); MSSQLCEConn.ExecuteNonQuery(cmd); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesMultipleChoice, id, Cache.DefaultSettingsValidationTime)] = multipleChoice; } /// <summary> /// Gets the sentence. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public bool? GetSentence(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsQueryTypesSentence, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsQueryTypesSentence, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; } /// <summary> /// Sets the sentence. /// </summary> /// <param name="id">The id.</param> /// <param name="sentence">The sentence.</param> /// <remarks> /// Documented by FabThe, 13.1.2009 /// </remarks> public void SetSentence(int id, bool? sentence) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE \"QueryTypes\" SET sentence=" + (sentence.HasValue ? "@value" : "null") + " WHERE id=@id"; cmd.Parameters.Add("@id", id); if (sentence.HasValue) cmd.Parameters.Add("@value", sentence); MSSQLCEConn.ExecuteNonQuery(cmd); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesSentence, id, Cache.DefaultSettingsValidationTime)] = sentence; } /// <summary> /// Gets the word. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public bool? GetWord(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsQueryTypesWord, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsQueryTypesWord, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; } /// <summary> /// Sets the word. /// </summary> /// <param name="id">The id.</param> /// <param name="word">The word.</param> /// <remarks>Documented by Dev08, 2009-01-13</remarks> public void SetWord(int id, bool? word) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE \"QueryTypes\" SET word=" + (word.HasValue ? "@value" : "null") + " WHERE id=@id"; cmd.Parameters.Add("@id", id); if (word.HasValue) cmd.Parameters.Add("@value", word); MSSQLCEConn.ExecuteNonQuery(cmd); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesWord, id, Cache.DefaultSettingsValidationTime)] = word; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.IO { using System; using System.Runtime.CompilerServices; /// <summary> /// Helper methods for encoding and decoding integer values. /// </summary> internal static class IntegerHelper { public const int MaxBytesVarInt16 = 3; public const int MaxBytesVarInt32 = 5; public const int MaxBytesVarInt64 = 10; public static int GetVarUInt16Length(ushort value) { if (value < (1 << 7)) { return 1; } else if (value < (1 << 14)) { return 2; } else { return 3; } } public static int EncodeVarUInt16(byte[] data, ushort value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } // byte 2 data[index++] = (byte)value; return index; } public static int GetVarUInt32Length(uint value) { if (value < (1 << 7)) { return 1; } else if (value < (1 << 14)) { return 2; } else if (value < (1 << 21)) { return 3; } else if (value < (1 << 28)) { return 4; } else { return 5; } } public static int EncodeVarUInt32(byte[] data, uint value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } // last byte data[index++] = (byte)value; return index; } public static int GetVarUInt64Length(ulong value) { if (value < (1UL << 7)) { return 1; } else if (value < (1UL << 14)) { return 2; } else if (value < (1UL << 21)) { return 3; } else if (value < (1UL << 28)) { return 4; } else if (value < (1UL << 35)) { return 5; } else if (value < (1UL << 42)) { return 6; } else if (value < (1UL << 49)) { return 7; } else if (value < (1UL << 56)) { return 8; } else if (value < (1UL << 63)) { return 9; } else { return 10; } } public static int EncodeVarUInt64(byte[] data, ulong value, int index) { // byte 0 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 1 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 2 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 3 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 4 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 5 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 6 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 7 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; // byte 8 if (value >= 0x80) { data[index++] = (byte)(value | 0x80); value >>= 7; } } } } } } } } } // last byte data[index++] = (byte)value; return index; } public static ushort DecodeVarUInt16(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= raw << 14; } } index = i; return (ushort) result; } public static uint DecodeVarUInt32(byte[] data, ref int index) { var i = index; // byte 0 uint result = data[i++]; if (0x80u <= result) { // byte 1 uint raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= raw << 28; } } } } index = i; return result; } public static ulong DecodeVarUInt64(byte[] data, ref int index) { var i = index; // byte 0 ulong result = data[i++]; if (0x80u <= result) { // byte 1 ulong raw = data[i++]; result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7); if (0x80u <= raw) { // byte 2 raw = data[i++]; result |= (raw & 0x7Fu) << 14; if (0x80u <= raw) { // byte 3 raw = data[i++]; result |= (raw & 0x7Fu) << 21; if (0x80u <= raw) { // byte 4 raw = data[i++]; result |= (raw & 0x7Fu) << 28; if (0x80u <= raw) { // byte 5 raw = data[i++]; result |= (raw & 0x7Fu) << 35; if (0x80u <= raw) { // byte 6 raw = data[i++]; result |= (raw & 0x7Fu) << 42; if (0x80u <= raw) { // byte 7 raw = data[i++]; result |= (raw & 0x7Fu) << 49; if (0x80u <= raw) { // byte 8 raw = data[i++]; result |= raw << 56; if (0x80u <= raw) { // byte 9 i++; } } } } } } } } } index = i; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static UInt16 EncodeZigzag16(Int16 value) { return (UInt16)((value << 1) ^ (value >> (sizeof(Int16) * 8 - 1))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static UInt32 EncodeZigzag32(Int32 value) { return (UInt32)((value << 1) ^ (value >> (sizeof(Int32) * 8 - 1))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static UInt64 EncodeZigzag64(Int64 value) { return (UInt64)((value << 1) ^ (value >> (sizeof(Int64) * 8 - 1))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int16 DecodeZigzag16(UInt16 value) { return (Int16)((value >> 1) ^ (-(value & 1))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int32 DecodeZigzag32(UInt32 value) { return (Int32)((value >> 1) ^ (-(value & 1))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Int64 DecodeZigzag64(UInt64 value) { return (Int64)((value >> 1) ^ (UInt64)(-(Int64)(value & 1))); } } }
// // BoxFactory.cs: Provides support for reading boxes from a file. // // Author: // Brian Nickel ([email protected]) // // Copyright (C) 2006-2007 Brian Nickel // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // 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 // using System; namespace TagLib.Mpeg4 { /// <summary> /// This static class provides support for reading boxes from a file. /// </summary> public static class BoxFactory { /// <summary> /// Creates a box by reading it from a file given its header, /// parent header, handler, and index in its parent. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <param name="parent"> /// A <see cref="BoxHeader" /> object containing the header /// of the parent box. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <param name="index"> /// A <see cref="int" /> value containing the index of the /// new box in its parent. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> private static Box CreateBox (TagLib.File file, BoxHeader header, BoxHeader parent, IsoHandlerBox handler, int index) { // The first few children of an "stsd" are sample // entries. if (parent.BoxType == BoxType.Stsd && parent.Box is IsoSampleDescriptionBox && index < (parent.Box as IsoSampleDescriptionBox).EntryCount) { if (handler != null && handler.HandlerType == BoxType.Soun) return new IsoAudioSampleEntry (header, file, handler); else if (handler != null && handler.HandlerType == BoxType.Vide) return new IsoVisualSampleEntry (header, file, handler); else if (handler != null && handler.HandlerType == BoxType.Alis) { if (header.BoxType == BoxType.Text) return new TextBox (header, file, handler); else if (header.BoxType == BoxType.Url) return new UrlBox (header, file, handler); // This could be anything, so just parse it return new UnknownBox (header, file, handler); } else return new IsoSampleEntry (header, file, handler); } // Standard items... ByteVector type = header.BoxType; if (type == BoxType.Mvhd) return new IsoMovieHeaderBox (header, file, handler); else if (type == BoxType.Stbl) return new IsoSampleTableBox (header, file, handler); else if (type == BoxType.Stsd) return new IsoSampleDescriptionBox (header, file, handler); else if (type == BoxType.Stco) return new IsoChunkOffsetBox (header, file, handler); else if (type == BoxType.Co64) return new IsoChunkLargeOffsetBox (header, file, handler); else if (type == BoxType.Hdlr) return new IsoHandlerBox (header, file, handler); else if (type == BoxType.Udta) return new IsoUserDataBox (header, file, handler); else if (type == BoxType.Meta) return new IsoMetaBox (header, file, handler); else if (type == BoxType.Ilst) return new AppleItemListBox (header, file, handler); else if (type == BoxType.Data) return new AppleDataBox (header, file, handler); else if (type == BoxType.Esds) return new AppleElementaryStreamDescriptor ( header, file, handler); else if (type == BoxType.Free || type == BoxType.Skip) return new IsoFreeSpaceBox (header, file, handler); else if (type == BoxType.Mean || type == BoxType.Name) return new AppleAdditionalInfoBox (header, file, handler); // If we still don't have a tag, and we're inside an // ItemListBox, load the box as an AnnotationBox // (Apple tag item). if (parent.BoxType == BoxType.Ilst) return new AppleAnnotationBox (header, file, handler); // Nothing good. Go generic. return new UnknownBox (header, file, handler); } /// <summary> /// Creates a box by reading it from a file given its /// position in the file, parent header, handler, and index /// in its parent. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying at what seek /// position in <paramref name="file" /> to start reading. /// </param> /// <param name="parent"> /// A <see cref="BoxHeader" /> object containing the header /// of the parent box. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <param name="index"> /// A <see cref="int" /> value containing the index of the /// new box in its parent. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> internal static Box CreateBox (TagLib.File file, long position, BoxHeader parent, IsoHandlerBox handler, int index) { BoxHeader header = new BoxHeader (file, position); return CreateBox (file, header, parent, handler, index); } /// <summary> /// Creates a box by reading it from a file given its /// position in the file and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying at what seek /// position in <paramref name="file" /> to start reading. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox (TagLib.File file, long position, IsoHandlerBox handler) { return CreateBox (file, position, BoxHeader.Empty, handler, -1); } /// <summary> /// Creates a box by reading it from a file given its /// position in the file. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying at what seek /// position in <paramref name="file" /> to start reading. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox (TagLib.File file, long position) { return CreateBox (file, position, null); } /// <summary> /// Creates a box by reading it from a file given its header /// and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object containing the /// handler that applies to the new box. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox (TagLib.File file, BoxHeader header, IsoHandlerBox handler) { return CreateBox (file, header, BoxHeader.Empty, handler, -1); } /// <summary> /// Creates a box by reading it from a file given its header /// and handler. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object containing the file /// to read from. /// </param> /// <param name="header"> /// A <see cref="BoxHeader" /> object containing the header /// of the box to create. /// </param> /// <returns> /// A newly created <see cref="Box" /> object. /// </returns> public static Box CreateBox (TagLib.File file, BoxHeader header) { return CreateBox (file, header, null); } } }
// Copyright 2010 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Demo { internal class ZonedDateTimeDemo { [Test] public void Construction() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; ZonedDateTime dt = Snippet.For(dublin.AtStrictly(new LocalDateTime(2010, 6, 9, 15, 15, 0))); Assert.AreEqual(15, dt.Hour); Assert.AreEqual(2010, dt.Year); Instant instant = Instant.FromUtc(2010, 6, 9, 14, 15, 0); Assert.AreEqual(instant, dt.ToInstant()); } // TODO: Work out how to have multiple snippets for a single member. [Test] public void AmbiguousLocalDateTime() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; Assert.Throws<AmbiguousTimeException>(() => dublin.AtStrictly(new LocalDateTime(2010, 10, 31, 1, 15, 0))); } [Test] public void SkippedLocalDateTime() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; Assert.Throws<SkippedTimeException>(() => dublin.AtStrictly(new LocalDateTime(2010, 3, 28, 1, 15, 0))); } [Test] public void TickOfDay() { // This is a 25-hour day at the end of daylight saving time var dt = new LocalDate(2017, 10, 29); var time = new LocalTime(23, 59, 59); var dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var startOfDay = dublin.AtStartOfDay(dt); ZonedDateTime nearEndOfDay = dublin.AtStrictly(dt + time); Assert.AreEqual(time.TickOfDay, Snippet.For(nearEndOfDay.TickOfDay)); Duration duration = nearEndOfDay - startOfDay; Assert.AreEqual(Duration.FromHours(25) - Duration.FromSeconds(1), duration); } [Test] public void IsDaylightSavingTime() { // Europe/Dublin transitions from UTC+1 to UTC+0 at 2am (local) on 2017-10-29 // However, Euopre/Dublin is also odd in terms of having its standard time as *summer* time, // and its winter time as "daylight saving time". The saving offset in winter is -1 hour, // as opposed to the more common "+1 hour in summer". var dt = new LocalDateTime(2017, 10, 29, 1, 45, 0); DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; ZonedDateTime beforeTransition = new ZonedDateTime(dt, dublin, Offset.FromHours(1)); Assert.AreEqual(false, Snippet.For(beforeTransition.IsDaylightSavingTime())); // Same local time, different offset - so a different instant, after the transition. ZonedDateTime afterTransition = new ZonedDateTime(dt, dublin, Offset.FromHours(0)); Assert.AreEqual(true, Snippet.For(afterTransition.IsDaylightSavingTime())); } [Test] public void AddDuration() { // Europe/Dublin transitions from UTC+1 to UTC+0 at 2am (local) on 2017-10-29 var dt = new LocalDateTime(2017, 10, 29, 1, 45, 0); DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; ZonedDateTime beforeTransition = new ZonedDateTime(dt, dublin, Offset.FromHours(1)); var result = Snippet.For(ZonedDateTime.Add(beforeTransition, Duration.FromHours(1))); Assert.AreEqual(new LocalDate(2017, 10, 29), result.Date); // Adding an hour of elapsed time takes us across the DST transition, so we have // the same local time (shown on a clock) but a different offset. Assert.AreEqual(new ZonedDateTime(dt, dublin, Offset.FromHours(0)), result); // The + operator and Plus instance method are equivalent to the Add static method. var result2 = Snippet.For(beforeTransition + Duration.FromHours(1)); var result3 = Snippet.For(beforeTransition.Plus(Duration.FromHours(1))); Assert.AreEqual(result, result2); Assert.AreEqual(result, result3); } [Test] public void PlusHours() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T07:30:00 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusHours(1)))); } [Test] public void PlusMinutes() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T06:31:00 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusMinutes(1)))); } [Test] public void PlusSeconds() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T06:30:01 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusSeconds(1)))); } [Test] public void PlusMilliseconds() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T06:30:00.001 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusMilliseconds(1)))); } [Test] public void PlusTicks() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T06:30:00.0000001 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusTicks(1)))); } [Test] public void PlusNanoseconds() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var start = Instant.FromUtc(2017, 7, 20, 5, 30); // Dublin is at UTC+1 in July 2017, so this is 6:30am. ZonedDateTime zoned = new ZonedDateTime(start, dublin); var pattern = ZonedDateTimePattern.ExtendedFormatOnlyIso; Assert.AreEqual("2017-07-20T06:30:00.000000001 Europe/Dublin (+01)", pattern.Format(Snippet.For(zoned.PlusNanoseconds(1)))); } [Test] public void SubtractDuration() { // Europe/Dublin transitions from UTC+1 to UTC+0 at 2am (local) on 2017-10-29 var dt = new LocalDateTime(2017, 10, 29, 1, 45, 0); DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; ZonedDateTime afterTransition = new ZonedDateTime(dt, dublin, Offset.FromHours(0)); var result = Snippet.For(ZonedDateTime.Subtract(afterTransition, Duration.FromHours(1))); Assert.AreEqual(new LocalDate(2017, 10, 29), result.Date); // Adding an hour of elapsed time takes us across the DST transition, so we have // the same local time (shown on a clock) but a different offset. Assert.AreEqual(new ZonedDateTime(dt, dublin, Offset.FromHours(1)), result); // The + operator and Plus instance method are equivalent to the Add static method. var result2 = Snippet.For(afterTransition - Duration.FromHours(1)); var result3 = Snippet.For(afterTransition.Minus(Duration.FromHours(1))); Assert.AreEqual(result, result2); Assert.AreEqual(result, result3); } [Test] public void SubtractZonedDateTime() { var zone = DateTimeZone.ForOffset(Offset.FromHours(-5)); ZonedDateTime subject = new ZonedDateTime(Instant.FromUtc(2017, 7, 17, 7, 17), zone); ZonedDateTime other = new ZonedDateTime(Instant.FromUtc(2017, 7, 17, 9, 17), zone); var difference = Snippet.For(ZonedDateTime.Subtract(other, subject)); Assert.AreEqual(Duration.FromHours(2), difference); } [Test] public void MinusZonedDateTime() { var zone = DateTimeZone.ForOffset(Offset.FromHours(-5)); ZonedDateTime subject = new ZonedDateTime(Instant.FromUtc(2017, 7, 17, 7, 17), zone); ZonedDateTime other = new ZonedDateTime(Instant.FromUtc(2017, 7, 17, 9, 17), zone); var difference = Snippet.For(other.Minus(subject)); Assert.AreEqual(Duration.FromHours(2), difference); } [Test] public void NanosecondOfDay() { // This is a 25-hour day at the end of daylight saving time var dt = new LocalDate(2017, 10, 29); var time = new LocalTime(23, 59, 59); var dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; var startOfDay = dublin.AtStartOfDay(dt); ZonedDateTime nearEndOfDay = dublin.AtStrictly(dt + time); Assert.AreEqual(time.NanosecondOfDay, Snippet.For(nearEndOfDay.NanosecondOfDay)); Duration duration = nearEndOfDay - startOfDay; Assert.AreEqual(Duration.FromHours(25) - Duration.FromSeconds(1), duration); } } }
/* * 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 Moq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Brokerages; using QuantConnect.Brokerages.GDAX; using QuantConnect.Interfaces; using QuantConnect.Orders; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; namespace QuantConnect.Tests.Brokerages.GDAX { [TestFixture] public class GDAXBrokerageTests { #region Declarations GDAXBrokerage _unit; Mock<IWebSocket> _wss = new Mock<IWebSocket>(); Mock<IRestClient> _rest = new Mock<IRestClient>(); Mock<IAlgorithm> _algo = new Mock<IAlgorithm>(); string _orderData; string _orderByIdData; string _openOrderData; string _matchData; string _accountsData; string _holdingData; string _tickerData; Symbol _symbol; const string _brokerId = "d0c5340b-6d6c-49d9-b567-48c4bfca13d2"; const string _matchBrokerId = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; AccountType _accountType = AccountType.Margin; #endregion [SetUp] public void Setup() { var priceProvider = new Mock<IPriceProvider>(); priceProvider.Setup(x => x.GetLastPrice(It.IsAny<Symbol>())).Returns(1.234m); _unit = new GDAXBrokerage("wss://localhost", _wss.Object, _rest.Object, "abc", "MTIz", "pass", _algo.Object, priceProvider.Object); _orderData = File.ReadAllText("TestData//gdax_order.txt"); _matchData = File.ReadAllText("TestData//gdax_match.txt"); _openOrderData = File.ReadAllText("TestData//gdax_openOrders.txt"); _accountsData = File.ReadAllText("TestData//gdax_accounts.txt"); _holdingData = File.ReadAllText("TestData//gdax_holding.txt"); _orderByIdData = File.ReadAllText("TestData//gdax_orderById.txt"); _tickerData = File.ReadAllText("TestData//gdax_ticker.txt"); _symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/products/")))).Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_tick.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/orders/" + _brokerId) || r.Resource.StartsWith("/orders/" + _matchBrokerId)))) .Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_orderById.txt"), StatusCode = HttpStatusCode.OK }); _algo.Setup(a => a.BrokerageModel.AccountType).Returns(_accountType); } private void SetupResponse(string body, HttpStatusCode httpStatus = HttpStatusCode.OK) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.StartsWith("/products/") && !r.Resource.StartsWith("/orders/" + _brokerId)))) .Returns(new RestSharp.RestResponse { Content = body, StatusCode = httpStatus }); } [Test] public void IsConnectedTest() { _wss.Setup(w => w.IsOpen).Returns(true); Assert.IsTrue(_unit.IsConnected); _wss.Setup(w => w.IsOpen).Returns(false); Assert.IsFalse(_unit.IsConnected); } [Test] public void ConnectTest() { _wss.Setup(m => m.Connect()).Callback(() => { _wss.Setup(m => m.IsOpen).Returns(true); }).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(false); _unit.Connect(); _wss.Verify(); } [Test] public void DisconnectTest() { _wss.Setup(m => m.Close()).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(true); _unit.Disconnect(); _wss.Verify(); } [TestCase(5.23512)] [TestCase(99)] public void OnMessageFillTest(decimal expectedQuantity) { string json = _matchData; string id = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; //not our order if (expectedQuantity == 99) { json = json.Replace(id, Guid.NewGuid().ToString()); } decimal orderQuantity = 6.1m; GDAXTestsHelpers.AddOrder(_unit, 1, id, orderQuantity); ManualResetEvent raised = new ManualResetEvent(false); decimal actualFee = 0; decimal actualQuantity = 0; _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual("BTCUSD", e.Symbol.Value); actualFee += e.OrderFee; actualQuantity += e.AbsoluteFillQuantity; Assert.IsTrue(actualQuantity != orderQuantity); Assert.AreEqual(OrderStatus.Filled, e.Status); Assert.AreEqual(expectedQuantity, e.FillQuantity); // fill quantity = 5.23512 // fill price = 400.23 // partial order fee = (400.23 * 5.23512 * 0.003) = 6.2857562328 Assert.AreEqual(6.2857562328m, actualFee); raised.Set(); }; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); // not our order, market order is completed even if not totally filled json = json.Replace(id, Guid.NewGuid().ToString()); _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); //if not our order should get no event Assert.AreEqual(raised.WaitOne(1000), expectedQuantity != 99); } [Test] public void GetAuthenticationTokenTest() { var actual = _unit.GetAuthenticationToken("", "POST", "http://localhost"); Assert.IsFalse(string.IsNullOrEmpty(actual.Signature)); Assert.IsFalse(string.IsNullOrEmpty(actual.Timestamp)); Assert.AreEqual("pass", actual.Passphrase); Assert.AreEqual("abc", actual.Key); } [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.StopMarket)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.StopMarket)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Market)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Limit)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.StopMarket)] public void PlaceOrderTest(string orderId, HttpStatusCode httpStatus, Orders.OrderStatus status, decimal quantity, decimal price, OrderType orderType) { var response = new { id = _brokerId, fill_fees = "0.11" }; SetupResponse(JsonConvert.SerializeObject(response), httpStatus); _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual(status, e.Status); if (orderId != null) { Assert.AreEqual("BTCUSD", e.Symbol.Value); Assert.That((quantity > 0 && e.Direction == Orders.OrderDirection.Buy) || (quantity < 0 && e.Direction == Orders.OrderDirection.Sell)); Assert.IsTrue(orderId == null || _unit.CachedOrderIDs.SelectMany(c => c.Value.BrokerId.Where(b => b == _brokerId)).Any()); } }; Order order = null; if (orderType == OrderType.Limit) { order = new Orders.LimitOrder(_symbol, quantity, price, DateTime.UtcNow); } else if (orderType == OrderType.Market) { order = new Orders.MarketOrder(_symbol, quantity, DateTime.UtcNow); } else { order = new Orders.StopMarketOrder(_symbol, quantity, price, DateTime.UtcNow); } bool actual = _unit.PlaceOrder(order); Assert.IsTrue(actual || (orderId == null && !actual)); } [Test] public void GetOpenOrdersTest() { SetupResponse(_openOrderData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetOpenOrders(); Assert.AreEqual(2, actual.Count()); Assert.AreEqual(0.01, actual.First().Quantity); Assert.AreEqual(OrderDirection.Buy, actual.First().Direction); Assert.AreEqual(0.1, actual.First().Price); Assert.AreEqual(-1, actual.Last().Quantity); Assert.AreEqual(OrderDirection.Sell, actual.Last().Direction); Assert.AreEqual(1, actual.Last().Price); } [Test] public void GetTickTest() { var actual = _unit.GetTick(_symbol); Assert.AreEqual(333.98m, actual.BidPrice); Assert.AreEqual(333.99m, actual.AskPrice); Assert.AreEqual(5957.11914015, actual.Quantity); } [Test] public void GetCashBalanceTest() { SetupResponse(_accountsData); var actual = _unit.GetCashBalance(); Assert.AreEqual(2, actual.Count()); var usd = actual.Single(a => a.Symbol == "USD"); var btc = actual.Single(a => a.Symbol == "BTC"); Assert.AreEqual(80.2301373066930000m, usd.Amount); Assert.AreEqual(1, usd.ConversionRate); Assert.AreEqual(1.1, btc.Amount); Assert.AreEqual(333.985m, btc.ConversionRate); } [Test, Ignore("Holdings are now set to 0 swaps at the start of each launch. Not meaningful.")] public void GetAccountHoldingsTest() { SetupResponse(_holdingData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetAccountHoldings(); Assert.AreEqual(0, actual.Count()); } [TestCase(HttpStatusCode.OK, HttpStatusCode.NotFound, false)] [TestCase(HttpStatusCode.OK, HttpStatusCode.OK, true)] public void CancelOrderTest(HttpStatusCode code, HttpStatusCode code2, bool expected) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("1")))).Returns(new RestSharp.RestResponse { StatusCode = code }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("2")))).Returns(new RestSharp.RestResponse { StatusCode = code2 }); var actual = _unit.CancelOrder(new Orders.LimitOrder { BrokerId = new List<string> { "1", "2" } }); Assert.AreEqual(expected, actual); } [Test] public void UpdateOrderTest() { Assert.Throws<NotSupportedException>(() => _unit.UpdateOrder(new LimitOrder())); } [Test] public void SubscribeTest() { string actual = null; string expected = "[\"BTC-USD\",\"BTC-ETH\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Ticks.Clear(); _unit.Subscribe(new[] { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("GBPUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("BTCETH", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); // spin for a few seconds, waiting for the GBPUSD tick var start = DateTime.UtcNow; var timeout = start.AddSeconds(5); while (_unit.Ticks.Count == 0 && DateTime.UtcNow < timeout) { Thread.Sleep(1); } // only rate conversion ticks are received during subscribe Assert.AreEqual(1, _unit.Ticks.Count); Assert.AreEqual("GBPUSD", _unit.Ticks[0].Symbol.Value); } [Test] public void UnsubscribeTest() { string actual = null; _wss.Setup(w => w.IsOpen).Returns(true); _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Unsubscribe(new List<Symbol> { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX) }); StringAssert.Contains("user", actual); StringAssert.Contains("heartbeat", actual); StringAssert.Contains("matches", actual); } [Test, Ignore("This test is obsolete, the 'ticker' channel is no longer used.")] public void OnMessageTickerTest() { string json = _tickerData; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); var actual = _unit.Ticks.First(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.005m, actual.Price); Assert.AreEqual(4388m, actual.BidPrice); Assert.AreEqual(4388.01m, actual.AskPrice); actual = _unit.Ticks.Last(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.01m, actual.Price); Assert.AreEqual(0.03m, actual.Quantity); } [Test] public void PollTickTest() { _unit.PollTick(Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM)); Thread.Sleep(1000); // conversion rate is the price returned by the QC pricing API Assert.AreEqual(1.234m, _unit.Ticks.First().Price); } [Test] public void ErrorTest() { string actual = null; // subscribe to invalid symbol const string expected = "[\"BTC-LTC\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Subscribe(new[] { Symbol.Create("BTCLTC", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); BrokerageMessageType messageType = 0; _unit.Message += (sender, e) => { messageType = e.Type; }; const string json = "{\"type\":\"error\",\"message\":\"Failed to subscribe\",\"reason\":\"Invalid product ID provided\"}"; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); Assert.AreEqual(BrokerageMessageType.Warning, messageType); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Tester.UnitTests { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.DeviceModels.Chipset.PXA27x.Drivers; /// <summary> /// Unit Tests for the I2C subsystem /// </summary> public class I2CBusTests : ITest { #region Scan Bus test /// <summary> /// scan bus test /// </summary> public void TestCase1() { int found = 0; ushort startFrom = 0; int clockRateKHz = 400; I2CDevice.Configuration config = new I2CDevice.Configuration(startFrom, clockRateKHz); using (I2CDevice i2cDevice = new I2CDevice(config)) { bool found34, found49, found4a; found34 = found49 = found4a = false; //keep out 0 and 127) for (int i = 1; i < 126; i++) { i2cDevice.Config = new I2CDevice.Configuration((ushort)(1 + ((i + startFrom) % 126)), 400); I2CDevice.I2CTransaction unit1 = i2cDevice.CreateReadTransaction(new byte[] { 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); if (len > 0) { ASSERT(len == 1, true, "not all data sent"); found34 |= (i2cDevice.Config.Address == 0x34); found49 |= (i2cDevice.Config.Address == 0x49); found4a |= (i2cDevice.Config.Address == 0x4a); found++; } else { ASSERT(len < 0, false, "illegal return value for execute"); } } ASSERT(found == 3, true, "more devices than expected"); ASSERT(found34, true, "device 0x34 not found"); ASSERT(found49, true, "device 0x49 not found"); ASSERT(found4a, true, "device 0x4a not found"); } } #endregion #region Write config data to AD converter /// <summary> /// scan bus test /// </summary> public void TestCase2() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { I2CDevice.I2CTransaction unit1 = i2cDevice.CreateWriteTransaction(new byte[] { 0, 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); ASSERT(len > 0, true, "not all data sent"); ASSERT(len == 2, true, "illegal return value for execute"); } } #endregion #region Read channel data from AD converter /// <summary> /// scan bus test /// </summary> public void TestCase3() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { I2CDevice.I2CTransaction unit1 = i2cDevice.CreateReadTransaction(new byte[] { 0, 0, 0, 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); ASSERT(len > 0, true, "not all data sent"); ASSERT(len == 4, true, "illegal return value for execute"); bool dataOk = false; for (int i = 0; i < unit1.Buffer.Length; i++) { dataOk |= (unit1.Buffer[i] != 0); } ASSERT(dataOk, true, "no data from converter"); } } #endregion #region check for illegal data /// <summary> /// scan bus test /// </summary> public void TestCase4() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { try { i2cDevice.CreateReadTransaction(null); ASSERT(true, false, "illegal data"); } catch { //expected } try { i2cDevice.CreateWriteTransaction(null); ASSERT(true, false, "illegal data"); } catch { //expected } try { int len = i2cDevice.Execute(null, 200); ASSERT(true, false, "illegal data"); } catch { //expected } try { int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[0], 200); ASSERT(len == 0, true, "illegal data"); } catch { ASSERT(true, false, "illegal data"); } } } #endregion #region ITest Members private bool m_success = true; private int assertionId = 0; /// <summary> /// if true, test completed with no error /// </summary> public bool Success { get { return m_success; } } /// <summary> /// checks that an object is not null /// </summary> /// <param name="o"></param> /// <param name="failureMessage"></param> public void ASSERT_NOT_NULL(object o, String failureMessage) { assertionId++; if (null == o) { Result += "\r\n# " + assertionId + " Object <null>: " + failureMessage; m_success = false; } } /// <summary> /// checks that a condition is met /// </summary> /// <param name="current"></param> /// <param name="expected"></param> /// <param name="failureMessage"></param> public void ASSERT(bool current, bool expected, String failureMessage) { assertionId++; if (current != expected) { Result += "\r\n#" + assertionId + " " + current + "!=" + expected + "(expected): " + failureMessage; m_success = false; } } /// <summary> /// Prepares the output port test case /// </summary> public void Prepare() { Result = ""; } /// <summary> /// Executes the output port test case /// </summary> public void Run() { try { TestCase1(); } catch { ASSERT_NOT_NULL(null, "test case 1 - "); } try { TestCase2(); } catch { ASSERT_NOT_NULL(null, "test case 2 - "); } try { TestCase3(); } catch { ASSERT_NOT_NULL(null, "test case 3 - "); } try { TestCase4(); } catch { ASSERT_NOT_NULL(null, "test case 4 - "); } } /// <summary> /// Retrieves the results of the output port test case /// </summary> public string Result { get; private set; } #endregion } #region Test helper classes public class I2CDevice : IDisposable { #region Constructor/Destructor public I2CDevice(I2CDevice.Configuration config) { this.Config = config; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool fDisposing) { } #endregion #region Public API public Configuration Config; public int Execute(I2CDevice.I2CTransaction[] xActions, int timeout) { if (Config.Address == Microsoft.DeviceModels.Chipset.PXA27x.I2C.Instance.ISAR) return -1;// throw new ArgumentOutOfRangeException("Config.Address"); if (null == xActions) throw new ArgumentNullException("xActions"); if (0 == xActions.Length) return 0; I2CBus_Transaction action = new I2CBus_Transaction(Config.Address, Config.ClockRateKhz, xActions); I2C.Instance.StartTransactionAsMaster(action); if (!action.WaitForCompletion(timeout)) { I2C.Instance.StopTransactionAsMaster(); return 0; } return action.BytesTransacted; } public I2CDevice.I2CReadTransaction CreateReadTransaction(byte[] buffer) { return new I2CReadTransaction(buffer); } public I2CDevice.I2CWriteTransaction CreateWriteTransaction(byte[] buffer) { return new I2CWriteTransaction(buffer); } #endregion #region Nested classes public sealed class I2CReadTransaction : I2CTransaction { internal I2CReadTransaction(byte[] buffer) : base(true, buffer) { } } public sealed class I2CWriteTransaction : I2CTransaction { internal I2CWriteTransaction(byte[] buffer) : base(false, buffer) { } } public class I2CTransaction : I2CBus_TransactionUnit { internal I2CTransaction(bool isReadTransaction, byte[] buffer) : base(isReadTransaction, buffer) { } } public class Configuration { public readonly ushort Address; public readonly int ClockRateKhz; public Configuration(ushort address, int clockRateKhz) { this.Address = address; this.ClockRateKhz = clockRateKhz; } } #endregion } #endregion }
using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Windows.Input; using BudgetAnalyser.Annotations; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Services; using BudgetAnalyser.ShellDialog; using GalaSoft.MvvmLight.CommandWpf; using Rees.UserInteraction.Contracts; using Rees.Wpf; namespace BudgetAnalyser.Budget { [AutoRegisterWithIoC(SingleInstance = true)] public class BudgetController : ControllerBase, IShowableController { private const string CloseBudgetMenuName = "Close _Budget"; private const string EditBudgetMenuName = "Edit Current _Budget"; private readonly IApplicationDatabaseService applicationDatabaseService; private readonly IUserInputBox inputBox; private readonly IBudgetMaintenanceService maintenanceService; private readonly IUserMessageBox messageBox; private readonly IUserQuestionBoxYesNo questionBox; private string budgetMenuItemName; private Guid dialogCorrelationId; private bool doNotUseDirty; private BudgetCurrencyContext doNotUseModel; private bool doNotUseShownBudget; private decimal expenseTotal; private decimal incomeTotal; private bool isLoadingBudgetModel; private decimal surplus; [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OnPropertyChange is ok to call here")] public BudgetController( [NotNull] UiContext uiContext, [NotNull] IBudgetMaintenanceService maintenanceService, [NotNull] IApplicationDatabaseService applicationDatabaseService) { if (uiContext == null) { throw new ArgumentNullException(nameof(uiContext)); } if (maintenanceService == null) { throw new ArgumentNullException(nameof(maintenanceService)); } if (applicationDatabaseService == null) { throw new ArgumentNullException(nameof(applicationDatabaseService)); } this.maintenanceService = maintenanceService; this.applicationDatabaseService = applicationDatabaseService; this.questionBox = uiContext.UserPrompts.YesNoBox; this.messageBox = uiContext.UserPrompts.MessageBox; this.inputBox = uiContext.UserPrompts.InputBox; BudgetPieController = uiContext.BudgetPieController; NewBudgetController = uiContext.NewBudgetModelController; NewBudgetController.Ready += OnAddNewBudgetReady; Shown = false; MessengerInstance = uiContext.Messenger; MessengerInstance.Register<ShellDialogResponseMessage>(this, OnPopUpResponseReceived); this.maintenanceService.Closed += OnClosedNotificationReceived; this.maintenanceService.NewDataSourceAvailable += OnNewDataSourceAvailableNotificationReceived; this.maintenanceService.Saving += OnSavingNotificationReceived; this.maintenanceService.Validating += OnValidatingNotificationReceived; this.maintenanceService.Saved += OnSavedNotificationReceived; CurrentBudget = new BudgetCurrencyContext(this.maintenanceService.Budgets, this.maintenanceService.Budgets.CurrentActiveBudget); } public ICommand AddNewExpenseCommand => new RelayCommand<ExpenseBucket>(OnAddNewExpenseExecute); public ICommand AddNewIncomeCommand => new RelayCommand(OnAddNewIncomeExecute); [UsedImplicitly] public string BudgetMenuItemName { [UsedImplicitly] get { return this.budgetMenuItemName; } set { this.budgetMenuItemName = value; RaisePropertyChanged(); } } public BudgetPieController BudgetPieController { get; } public BudgetCollection Budgets { get; private set; } public BudgetCurrencyContext CurrentBudget { get { return this.doNotUseModel; } private set { try { this.isLoadingBudgetModel = true; this.doNotUseModel = value; ReleaseListBindingEvents(); if (this.doNotUseModel == null) { Incomes = null; Expenses = null; } else { SubscribeListBindingEvents(); } RaisePropertyChanged(() => Incomes); RaisePropertyChanged(() => Expenses); OnExpenseAmountPropertyChanged(null, EventArgs.Empty); OnIncomeAmountPropertyChanged(null, EventArgs.Empty); RaisePropertyChanged(() => CurrentBudget); } finally { this.isLoadingBudgetModel = false; } } } [UsedImplicitly] public ICommand DeleteBudgetItemCommand => new RelayCommand<object>(OnDeleteBudgetItemCommandExecute); [UsedImplicitly] public ICommand DetailsCommand => new RelayCommand(OnDetailsCommandExecute); public bool Dirty { get { return this.doNotUseDirty; } private set { this.doNotUseDirty = value; RaisePropertyChanged(); if (Dirty) { CurrentBudget.Model.LastModified = DateTime.Now; this.applicationDatabaseService.NotifyOfChange(ApplicationDataType.Budget); } } } public BindingList<Expense> Expenses { get; private set; } public decimal ExpenseTotal { get { return this.expenseTotal; } private set { this.expenseTotal = value; RaisePropertyChanged(); } } public BindingList<Income> Incomes { get; private set; } public decimal IncomeTotal { get { return this.incomeTotal; } private set { this.incomeTotal = value; RaisePropertyChanged(); } } [UsedImplicitly] public ICommand NewBudgetCommand => new RelayCommand(OnAddNewBudgetCommandExecuted, () => CurrentBudget != null); public NewBudgetModelController NewBudgetController { get; } [UsedImplicitly] public ICommand ShowAllCommand => new RelayCommand(OnShowAllCommandExecuted); public bool Shown { get { return this.doNotUseShownBudget; } set { if (value == this.doNotUseShownBudget) { return; } this.doNotUseShownBudget = value; RaisePropertyChanged(); BudgetMenuItemName = this.doNotUseShownBudget ? CloseBudgetMenuName : EditBudgetMenuName; } } [UsedImplicitly] public ICommand ShowPieCommand => new RelayCommand(OnShowPieCommandExecuted, CanExecuteShowPieCommand); public decimal Surplus { [UsedImplicitly] get { return this.surplus; } private set { this.surplus = value; RaisePropertyChanged(); } } public string TruncatedFileName => Budgets.StorageKey.TruncateLeft(100, true); protected virtual string PromptUserForLastModifiedComment() { var comment = this.inputBox.Show("Budget Maintenance", "Enter an optional comment to describe what you changed."); return comment ?? string.Empty; } private void BudgetModelOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { if (this.isLoadingBudgetModel) return; Dirty = true; } private bool CanExecuteShowPieCommand() { if (Expenses == null || Incomes == null || CurrentBudget == null) { return false; } return Expenses.Any() || Incomes.Any(); } private void OnAddNewBudgetCommandExecuted() { var proposedDate = CurrentBudget.Model.EffectiveFrom.AddMonths(1); while (proposedDate < DateTime.Today) { proposedDate = proposedDate.AddMonths(1); } NewBudgetController.ShowDialog(proposedDate); } private void OnAddNewBudgetReady(object sender, EventArgs e) { try { var budget = this.maintenanceService.CloneBudgetModel(CurrentBudget.Model, NewBudgetController.EffectiveFrom); ShowOtherBudget(budget); } catch (ArgumentException ex) { this.messageBox.Show(ex.Message, "Unable to create new budget"); } catch (ValidationWarningException ex) { this.messageBox.Show(ex.Message, "Unable to create new budget"); } } private void OnAddNewExpenseExecute(ExpenseBucket expense) { Dirty = true; var newExpense = Expenses.AddNew(); Debug.Assert(newExpense != null); newExpense.Amount = 0; // New buckets must be created because the one passed in, is a single command parameter instance to be used as a type indicator only. // If it was used, the same instance would overwritten each time an expense is created. if (expense is SpentMonthlyExpenseBucket) { newExpense.Bucket = new SpentMonthlyExpenseBucket(string.Empty, string.Empty); } else if (expense is SavedUpForExpenseBucket) { newExpense.Bucket = new SavedUpForExpenseBucket(string.Empty, string.Empty); } else if (expense is SavingsCommitmentBucket) { newExpense.Bucket = new SavingsCommitmentBucket(string.Empty, string.Empty); } else { throw new InvalidCastException("Invalid type passed to Add New Expense: " + expense); } Expenses.RaiseListChangedEvents = true; newExpense.PropertyChanged += OnExpenseAmountPropertyChanged; } private void OnAddNewIncomeExecute() { Dirty = true; var newIncome = new Income { Bucket = new IncomeBudgetBucket(string.Empty, string.Empty), Amount = 0 }; Incomes.Add(newIncome); newIncome.PropertyChanged += OnIncomeAmountPropertyChanged; } private void OnClosedNotificationReceived(object sender, EventArgs eventArgs) { CurrentBudget = new BudgetCurrencyContext(this.maintenanceService.Budgets, this.maintenanceService.Budgets.CurrentActiveBudget); Budgets = CurrentBudget.BudgetCollection; BudgetBucketBindingSource.BucketRepository = this.maintenanceService.BudgetBucketRepository; RaisePropertyChanged(() => TruncatedFileName); MessengerInstance.Send(new BudgetReadyMessage(CurrentBudget, Budgets)); } private void OnDeleteBudgetItemCommandExecute(object budgetItem) { bool? response = this.questionBox.Show( "Are you sure you want to delete this budget bucket?\nAnalysis may not work correctly if transactions are allocated to this bucket.", "Delete Budget Bucket"); if (response == null || response.Value == false) { return; } Dirty = true; var expenseItem = budgetItem as Expense; if (expenseItem != null) { expenseItem.PropertyChanged -= OnExpenseAmountPropertyChanged; expenseItem.Bucket.PropertyChanged -= OnExpenseAmountPropertyChanged; Expenses.Remove(expenseItem); return; } var incomeItem = budgetItem as Income; if (incomeItem != null) { incomeItem.PropertyChanged -= OnIncomeAmountPropertyChanged; incomeItem.Bucket.PropertyChanged -= OnIncomeAmountPropertyChanged; Incomes.Remove(incomeItem); } } private void OnDetailsCommandExecute() { var popUpRequest = new ShellDialogRequestMessage(BudgetAnalyserFeature.Budget, CurrentBudget, ShellDialogType.Ok); MessengerInstance.Send(popUpRequest); } private void OnExpenseAmountPropertyChanged(object sender, EventArgs propertyChangedEventArgs) { if (!this.isLoadingBudgetModel && ExpenseTotal != 0) { Dirty = true; } ExpenseTotal = Expenses.Sum(x => x.Amount); Surplus = IncomeTotal - ExpenseTotal; } private void OnIncomeAmountPropertyChanged(object sender, EventArgs propertyChangedEventArgs) { if (!this.isLoadingBudgetModel && IncomeTotal != 0) { Dirty = true; } IncomeTotal = Incomes.Sum(x => x.Amount); Surplus = IncomeTotal - ExpenseTotal; } private void OnNewDataSourceAvailableNotificationReceived(object sender, EventArgs eventArgs) { SyncDataFromBudgetService(); } private void OnPopUpResponseReceived(ShellDialogResponseMessage message) { if (!message.IsItForMe(this.dialogCorrelationId)) { return; } var viewModel = (BudgetSelectionViewModel) message.Content; if (viewModel.Selected == null || viewModel.Selected == CurrentBudget.Model) { return; } ShowOtherBudget(viewModel.Selected); } private void OnSavedNotificationReceived(object sender, EventArgs eventArgs) { RaisePropertyChanged(() => TruncatedFileName); Dirty = false; } private void OnSavingNotificationReceived(object sender, AdditionalInformationRequestedEventArgs args) { SyncDataToBudgetService(); args.Context = CurrentBudget.Model; } private void OnShowAllCommandExecuted() { SelectOtherBudget(); } private void OnShowPieCommandExecuted() { BudgetPieController.Load(CurrentBudget.Model); } private void OnValidatingNotificationReceived(object sender, ValidatingEventArgs eventArgs) { if (Dirty) SyncDataToBudgetService(); } private void ReleaseListBindingEvents() { CurrentBudget.Model.PropertyChanged -= BudgetModelOnPropertyChanged; if (Incomes != null) { foreach (var item in Incomes) { item.PropertyChanged -= OnIncomeAmountPropertyChanged; item.Bucket.PropertyChanged -= OnIncomeAmountPropertyChanged; } } if (Expenses != null) { foreach (var item in Expenses) { item.PropertyChanged -= OnExpenseAmountPropertyChanged; item.Bucket.PropertyChanged -= OnExpenseAmountPropertyChanged; } } } private void SelectOtherBudget() { this.dialogCorrelationId = Guid.NewGuid(); var popUpRequest = new ShellDialogRequestMessage(BudgetAnalyserFeature.Budget, new BudgetSelectionViewModel(Budgets), ShellDialogType.Ok) { CorrelationId = this.dialogCorrelationId }; MessengerInstance.Send(popUpRequest); } private void ShowOtherBudget(BudgetModel budgetToShow) { CurrentBudget = new BudgetCurrencyContext(Budgets, budgetToShow); Shown = true; Dirty = false; // Need to reset this because events fire needlessly (in this case) as a result of setting the CurrentBudget. } private void SubscribeListBindingEvents() { CurrentBudget.Model.PropertyChanged += BudgetModelOnPropertyChanged; Incomes = new BindingList<Income>(CurrentBudget.Model.Incomes.ToList()); Incomes.ToList().ForEach( i => { i.PropertyChanged += OnIncomeAmountPropertyChanged; i.Bucket.PropertyChanged += OnIncomeAmountPropertyChanged; }); Expenses = new BindingList<Expense>(CurrentBudget.Model.Expenses.ToList()); Expenses.ToList().ForEach( e => { e.PropertyChanged += OnExpenseAmountPropertyChanged; e.Bucket.PropertyChanged += OnExpenseAmountPropertyChanged; }); } private void SyncDataFromBudgetService() { Budgets = this.maintenanceService.Budgets; CurrentBudget = new BudgetCurrencyContext(Budgets, Budgets.CurrentActiveBudget); BudgetBucketBindingSource.BucketRepository = this.maintenanceService.BudgetBucketRepository; RaisePropertyChanged(() => TruncatedFileName); if (CurrentBudget != null) { MessengerInstance.Send(new BudgetReadyMessage(CurrentBudget, Budgets)); } } private void SyncDataToBudgetService() { this.maintenanceService.UpdateIncomesAndExpenses(CurrentBudget.Model, Incomes, Expenses); } } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Generator.Enums; namespace Generator.Tables { struct InstructionStringParser { readonly Dictionary<string, EnumValue> toRegister; readonly string instrStr; readonly string mnemonic; readonly string[] operands; ParsedInstructionFlags instrFlags; public InstructionStringParser(Dictionary<string, EnumValue> toRegister, string instrStr) { this.toRegister = toRegister; this.instrStr = instrStr; int index = instrStr.IndexOf(' ', StringComparison.Ordinal); if (index < 0) index = instrStr.Length; mnemonic = instrStr[0..index]; var opsStr = instrStr[index..].Trim(); operands = opsStr == string.Empty ? Array.Empty<string>() : opsStr.Split(',').Select(a => a.Trim()).ToArray(); instrFlags = ParsedInstructionFlags.None; } public bool TryParse(out ParsedInstructionResult result, [NotNullWhen(false)] out string? error) { result = default; // Check if it's INVALID, db, dw, dd, dq if (instrStr.StartsWith("<", StringComparison.Ordinal) && instrStr.EndsWith(">", StringComparison.Ordinal)) { result = new ParsedInstructionResult(instrStr, ParsedInstructionFlags.None, instrStr, Array.Empty<ParsedInstructionOperand>(), Array.Empty<InstrStrImpliedOp>()); error = null; return true; } var sb = new StringBuilder(); sb.Append(mnemonic); int opIndex; var parsedOps = new List<ParsedInstructionOperand>(); int realOps = 0; for (opIndex = 0; opIndex < operands.Length; opIndex++) { var op = operands[opIndex]; if (op.Length == 0) { error = "Empty instruction operand"; return false; } if (op[0] == '<') break; var opFlags = ParsedInstructionOperandFlags.None; if (op[0] == '[' && op[^1] == ']') { op = op[1..^1].Trim(); opFlags |= ParsedInstructionOperandFlags.HiddenOperand; } else { if (realOps == 0) sb.Append(' '); else sb.Append(", "); sb.Append(op); realOps++; } if (!TryParseDecorators(op, out var newOp, out error)) return false; op = newOp; var opParts = op.Split('/').Select(a => a.Trim()).ToArray(); var firstPart = opParts[0]; if (firstPart.EndsWith("+1", StringComparison.Ordinal)) { firstPart = firstPart[0..(firstPart.Length - "+1".Length)]; opFlags |= ParsedInstructionOperandFlags.RegPlus1; } else if (firstPart.EndsWith("+3", StringComparison.Ordinal)) { firstPart = firstPart[0..(firstPart.Length - "+3".Length)]; opFlags |= ParsedInstructionOperandFlags.RegPlus3; } if (firstPart == "r") { if (opParts.Length < 2) { error = "Missing GPR size (missing mXX)"; return false; } switch (opParts[1]) { case "m8": firstPart = "r8"; break; case "m16": firstPart = "r16"; break; case "m32": firstPart = "r32"; break; case "m64": firstPart = "r64"; break; default: error = $"Can't detect GPR size, memory op: `{opParts[1]}`"; return false; } } var register = Register.None; int sizeBits = 0; switch (firstPart) { case "bnd": case "bnd1": case "bnd2": register = Register.BND0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "cr": register = Register.CR0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "dr": register = Register.DR0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "k1": case "k2": case "k3": register = Register.K0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "mm": case "mm1": case "mm2": register = Register.MM0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "r8": register = Register.AL; opFlags |= ParsedInstructionOperandFlags.Register; break; case "r16": register = Register.AX; opFlags |= ParsedInstructionOperandFlags.Register; break; case "r32": case "r32a": case "r32b": register = Register.EAX; opFlags |= ParsedInstructionOperandFlags.Register; break; case "r64": case "r64a": case "r64b": register = Register.RAX; opFlags |= ParsedInstructionOperandFlags.Register; break; case "Sreg": register = Register.ES; opFlags |= ParsedInstructionOperandFlags.Register; break; case "ST(i)": register = Register.ST0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "tmm1": case "tmm2": case "tmm3": register = Register.TMM0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "tr": register = Register.TR0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "xmm": case "xmm1": case "xmm2": case "xmm3": case "xmm4": register = Register.XMM0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "ymm1": case "ymm2": case "ymm3": case "ymm4": register = Register.YMM0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "zmm1": case "zmm2": case "zmm3": register = Register.ZMM0; opFlags |= ParsedInstructionOperandFlags.Register; break; case "disp16": case "disp32": sizeBits = int.Parse(firstPart.AsSpan()["disp".Length..]); opFlags |= ParsedInstructionOperandFlags.DispBranch; break; case "ptr16:16": case "ptr16:32": sizeBits = int.Parse(firstPart.AsSpan()["ptr16:".Length..]); opFlags |= ParsedInstructionOperandFlags.FarBranch; break; case "rel8": case "rel16": case "rel32": sizeBits = int.Parse(firstPart.AsSpan()["rel".Length..]); opFlags |= ParsedInstructionOperandFlags.RelBranch; break; case "imm4": case "imm8": case "imm16": case "imm32": case "imm64": sizeBits = int.Parse(firstPart.AsSpan()["imm".Length..]); opFlags |= ParsedInstructionOperandFlags.Immediate; break; case "moffs8": case "moffs16": case "moffs32": case "moffs64": opFlags |= ParsedInstructionOperandFlags.MemoryOffset | ParsedInstructionOperandFlags.Memory; break; case "vm32x": case "vm32y": case "vm32z": case "vm64x": case "vm64y": case "vm64z": opFlags |= ParsedInstructionOperandFlags.Memory | ParsedInstructionOperandFlags.Vsib; sizeBits = int.Parse(firstPart.AsSpan()[2..4]); register = (firstPart[^1]) switch { 'x' => Register.XMM0, 'y' => Register.YMM0, 'z' => Register.ZMM0, _ => throw new InvalidOperationException(), }; break; case "m": case "mem": opFlags |= ParsedInstructionOperandFlags.Memory; break; case "mib": opFlags |= ParsedInstructionOperandFlags.Memory | ParsedInstructionOperandFlags.MIB; break; case "sibmem": opFlags |= ParsedInstructionOperandFlags.Memory | ParsedInstructionOperandFlags.Sibmem; break; default: if (int.TryParse(firstPart, out _)) { opFlags |= ParsedInstructionOperandFlags.ConstImmediate; break; } else if (firstPart.StartsWith("m", StringComparison.Ordinal) && firstPart.Length >= 2 && char.IsDigit(firstPart[1])) { opFlags |= ParsedInstructionOperandFlags.Memory; break; } else if (firstPart.ToUpperInvariant() == firstPart) { if (firstPart == "ST(0)" || firstPart == "ST") firstPart = "ST0"; if (toRegister.TryGetValue(firstPart, out var regEnum)) { register = (Register)regEnum.Value; opFlags |= ParsedInstructionOperandFlags.ImpliedRegister; break; } } error = $"Unknown value: `{firstPart}`"; return false; } if (opParts.Length >= 2) { var part = opParts[1]; if (part.StartsWith("m", StringComparison.Ordinal) && part.Length >= 2 && char.IsDigit(part[1])) opFlags |= ParsedInstructionOperandFlags.Memory; else { error = $"Unknown value: `{part}`"; return false; } } if (opParts.Length >= 3) { var part = opParts[2]; if (part.StartsWith("m", StringComparison.Ordinal) && part.Length >= 2 && char.IsDigit(part[1]) && part.EndsWith("bcst", StringComparison.Ordinal)) opFlags |= ParsedInstructionOperandFlags.Broadcast; else { error = $"Unknown value: `{part}`"; return false; } } if (opParts.Length >= 4) { error = "Too many reg/mem parts"; return false; } parsedOps.Add(new ParsedInstructionOperand(opFlags, register, sizeBits)); } var impliedOps = new List<InstrStrImpliedOp>(); for (; opIndex < operands.Length; opIndex++) { var op = operands[opIndex]; if (op.Length == 0) { error = "Empty instruction operand"; return false; } if (realOps == 0) sb.Append(' '); else sb.Append(", "); sb.Append(op); realOps++; if (op[0] == '<') { if (op[^1] != '>') { error = "Implied operands must be enclosed in < >"; return false; } if (op.ToUpperInvariant() != op && op.ToLowerInvariant() != op) { error = $"Implied operands must be lower case or upper case: `{op}`"; return false; } impliedOps.Add(new InstrStrImpliedOp(op)); } else { error = "All implied operands must be the last operands"; return false; } } result = new ParsedInstructionResult(sb.ToString(), instrFlags, mnemonic, parsedOps.ToArray(), impliedOps.ToArray()); error = null; return true; } bool TryParseDecorators(string op, [NotNullWhen(true)] out string? newOp, [NotNullWhen(false)] out string? error) { newOp = null; var parts = op.Split('{').Select(a => a.Trim()).ToArray(); for (int i = 1; i < parts.Length; i++) { var decorator = parts[i]; switch (decorator) { case "k1}": case "k2}": instrFlags |= ParsedInstructionFlags.OpMask; break; case "z}": instrFlags |= ParsedInstructionFlags.ZeroingMasking; break; case "sae}": instrFlags |= ParsedInstructionFlags.SuppressAllExceptions; break; case "er}": instrFlags |= ParsedInstructionFlags.RoundingControl; break; default: error = $"Unknown decorator: `{{{decorator}`"; return false; } } newOp = parts[0]; error = null; return true; } } }
using UnityEngine; using System; using System.Linq; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif namespace ForieroEngine.MIDIUnified.Plugins { public class MidiINPlugin { public static Queue<MidiMessage> midiMessages = new Queue<MidiMessage> (100); public static IMidiINDevice midiINDevice; public static IMidiEditorDevice midiEditorDevice; [RuntimeInitializeOnLoadMethod (RuntimeInitializeLoadType.BeforeSceneLoad)] public static void Init () { #if UNITY_EDITOR_OSX || UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX MidiINDeviceSTANDALONE device = new MidiINDeviceSTANDALONE (); #elif UNITY_IOS MidiINDeviceIOS device = new MidiINDeviceIOS(); #elif UNITY_WSA MidiINDeviceWSA device = new MidiINDeviceWSA(); #elif UNITY_WEBGL MidiINDeviceWEBGL device = new MidiINDeviceWEBGL(); #else MidiINDeviceNONE device = new MidiINDeviceNONE(); #endif midiDevice = device as IMidiDevice; midiINDevice = device as IMidiINDevice; midiEditorDevice = device as IMidiEditorDevice; Refresh (); initialized = true; } public static bool initialized = false; public static List<MidiDevice> connectedDevices = new List<MidiDevice> (); public static List<string> deviceNames = new List<string> (); static IMidiDevice midiDevice; public static List<MidiDevice> connectedEditorDevices = new List<MidiDevice> (); #if UNITY_EDITOR public static void StoreEditorConnections () { List<string> connectionNames = new List<string> (); foreach (MidiDevice device in connectedEditorDevices) { connectionNames.Add (device.name); } string s = string.Join (";", connectionNames.ToArray ()); EditorPrefs.SetString ("MIDI_IN_NAMES", s); } public static void RestoreEditorConnections () { string names = EditorPrefs.GetString ("MIDI_IN_NAMES", "").Trim (); string[] midiInNames = string.IsNullOrEmpty (names) ? new string[0] : names.Split (';'); foreach (string midiInName in midiInNames) { MidiDevice midiDevice = ConnectDeviceByName (midiInName, true); if (midiDevice == null) { Debug.LogError ("Could not conned midi in device : " + midiInName); } } } #endif public static void StoreConnections () { List<string> connectionNames = new List<string> (); foreach (MidiDevice device in connectedDevices) { connectionNames.Add (device.name); } string s = string.Join (";", connectionNames.ToArray ()); PlayerPrefs.SetString ("MIDI_IN_NAMES", s); } public static void RestoreConnections () { string names = PlayerPrefs.GetString ("MIDI_IN_NAMES", "").Trim (); string[] midiInNames = string.IsNullOrEmpty (names) ? new string[0] : names.Split (';'); foreach (string midiInName in midiInNames) { MidiDevice midiDevice = ConnectDeviceByName (midiInName); if (midiDevice == null) { Debug.LogError ("Could not conned midi in device : " + midiInName); } } } public static void Refresh () { if (midiDevice == null) return; deviceNames = new List<string> (); for (int i = 0; i < midiDevice.GetDeviceCount (); i++) { deviceNames.Add (midiDevice.GetDeviceName (i)); } if (midiEditorDevice != null) { connectedEditorDevices = new List<MidiDevice> (); for (int i = 0; i < midiEditorDevice.GetConnectedDeviceCount (); i++) { if (midiEditorDevice.GetConnectedDeviceIsEditor (i)) { MidiDevice md = new MidiDevice (); md.name = midiEditorDevice.GetConnectedDeviceName (i); md.deviceId = midiEditorDevice.GetConnectedDeviceId (i); md.isEditor = true; connectedEditorDevices.Add (md); } } } } public static bool Initialized () { if (midiDevice == null) return false; return midiDevice.Initialized (); } public static MidiDevice ConnectDevice (int deviceIndex, bool editor = false) { if (midiDevice == null) return null; foreach (MidiDevice md in MidiOUTPlugin.connectedDevices) { if (md.name == midiDevice.GetDeviceName (deviceIndex)) { Debug.LogError ("Preventing infinite loop. To have same device connected as IN and OUT is not allowed."); return null; } } int deviceId = midiDevice.ConnectDevice (deviceIndex, editor); if (editor) { foreach (MidiDevice cd in connectedEditorDevices) { if (deviceId == cd.deviceId) { Debug.LogError ("Editor device already connected"); return cd; } } } else { foreach (MidiDevice cd in connectedDevices) { if (deviceId == cd.deviceId) { Debug.LogError ("Device already connected"); return cd; } } } MidiDevice connectedDevice = new MidiDevice { deviceId = deviceId, name = GetDeviceName (deviceIndex), isEditor = editor }; if (editor) { connectedEditorDevices.Add (connectedDevice); } else { connectedDevices.Add (connectedDevice); } return connectedDevice; } public static MidiDevice ConnectDeviceByName (string deviceName, bool editor = false) { if (midiDevice == null) return null; foreach (MidiDevice md in MidiOUTPlugin.connectedDevices) { if (md.name == deviceName) { Debug.LogError ("Preventing infinite loop. To have same device connected as IN and OUT is not allowed."); return null; } } for (int i = 0; i < GetDeviceCount (); i++) { if (deviceName == GetDeviceName (i)) { return ConnectDevice (i, editor); } } return null; } public static void DisconnectDevice (MidiDevice connectedDevice) { if (midiDevice == null || connectedDevice == null) return; if (connectedDevice.isEditor) { for (int i = connectedEditorDevices.Count - 1; i >= 0; i--) { if (connectedDevice.deviceId == connectedEditorDevices [i].deviceId) { connectedEditorDevices.RemoveAt (i); break; } } } else { for (int i = connectedDevices.Count - 1; i >= 0; i--) { if (connectedDevice.deviceId == connectedDevices [i].deviceId) { connectedDevices.RemoveAt (i); break; } } } midiDevice.DisconnectDevice (connectedDevice.deviceId, connectedDevice.isEditor); } public static void DisconnectDevices (bool editor = false) { if (midiDevice == null) return; if (editor) { connectedEditorDevices = new List<MidiDevice> (); } else { connectedDevices = new List<MidiDevice> (); } midiDevice.DisconnectDevices (editor); } public static void DisconnectDeviceByName (string deviceName, bool editor = false) { if (midiDevice == null) return; MidiDevice disconnectDevice = null; if (editor) { for (int i = connectedEditorDevices.Count - 1; i >= 0; i--) { if (deviceName == connectedEditorDevices [i].name) { disconnectDevice = connectedEditorDevices [i]; break; } } } else { for (int i = connectedDevices.Count - 1; i >= 0; i--) { if (deviceName == connectedDevices [i].name) { disconnectDevice = connectedDevices [i]; break; } } } if (disconnectDevice != null) { DisconnectDevice (disconnectDevice); } } public static string GetDeviceName (int deviceIndex) { if (midiDevice == null) return ""; return midiDevice.GetDeviceName (deviceIndex); } public static int GetDeviceCount () { if (midiDevice == null) return 0; return midiDevice.GetDeviceCount (); } public static int PopMessage (out MidiMessage midiMessage, bool editor = false) { if (midiINDevice == null) { midiMessage = new MidiMessage (); return 0; } return midiINDevice.PopMessage (out midiMessage, editor); } public static int GetConnectedDeviceCount () { if (midiEditorDevice == null) return 0; return midiEditorDevice.GetConnectedDeviceCount (); } } }
using System; using System.Numerics; using System.Runtime.InteropServices; namespace VulkanCore.Samples.TexturedCube { [StructLayout(LayoutKind.Sequential)] internal struct WorldViewProjection { public Matrix4x4 World; public Matrix4x4 View; public Matrix4x4 Projection; } public class TexturedCubeApp : VulkanApp { private RenderPass _renderPass; private ImageView[] _imageViews; private Framebuffer[] _framebuffers; private PipelineLayout _pipelineLayout; private Pipeline _pipeline; private DescriptorSetLayout _descriptorSetLayout; private DescriptorPool _descriptorPool; private DescriptorSet _descriptorSet; private VulkanImage _depthStencilBuffer; private Sampler _sampler; private VulkanImage _cubeTexture; private VulkanBuffer _cubeVertices; private VulkanBuffer _cubeIndices; private VulkanBuffer _uniformBuffer; private WorldViewProjection _wvp; protected override void InitializePermanent() { var cube = GeometricPrimitive.Box(1.0f, 1.0f, 1.0f); _cubeTexture = Content.Load<VulkanImage>("IndustryForgedDark512.ktx"); _cubeVertices = ToDispose(VulkanBuffer.Vertex(Context, cube.Vertices)); _cubeIndices = ToDispose(VulkanBuffer.Index(Context, cube.Indices)); _sampler = ToDispose(CreateSampler()); _uniformBuffer = ToDispose(VulkanBuffer.DynamicUniform<WorldViewProjection>(Context, 1)); _descriptorSetLayout = ToDispose(CreateDescriptorSetLayout()); _pipelineLayout = ToDispose(CreatePipelineLayout()); _descriptorPool = ToDispose(CreateDescriptorPool()); _descriptorSet = CreateDescriptorSet(); // Will be freed when pool is destroyed. } protected override void InitializeFrame() { _depthStencilBuffer = ToDispose(VulkanImage.DepthStencil(Context, Host.Width, Host.Height)); _renderPass = ToDispose(CreateRenderPass()); _imageViews = ToDispose(CreateImageViews()); _framebuffers = ToDispose(CreateFramebuffers()); _pipeline = ToDispose(CreateGraphicsPipeline()); SetViewProjection(); } protected override void Update(Timer timer) { const float twoPi = (float)Math.PI * 2.0f; const float yawSpeed = twoPi / 4.0f; const float pitchSpeed = 0.0f; const float rollSpeed = twoPi / 4.0f; _wvp.World = Matrix4x4.CreateFromYawPitchRoll( timer.TotalTime * yawSpeed % twoPi, timer.TotalTime * pitchSpeed % twoPi, timer.TotalTime * rollSpeed % twoPi); UpdateUniformBuffers(); } protected override void RecordCommandBuffer(CommandBuffer cmdBuffer, int imageIndex) { var renderPassBeginInfo = new RenderPassBeginInfo( _framebuffers[imageIndex], new Rect2D(0, 0, Host.Width, Host.Height), new ClearColorValue(new ColorF4(0.39f, 0.58f, 0.93f, 1.0f)), new ClearDepthStencilValue(1.0f, 0)); cmdBuffer.CmdBeginRenderPass(renderPassBeginInfo); cmdBuffer.CmdBindDescriptorSet(PipelineBindPoint.Graphics, _pipelineLayout, _descriptorSet); cmdBuffer.CmdBindPipeline(PipelineBindPoint.Graphics, _pipeline); cmdBuffer.CmdBindVertexBuffer(_cubeVertices); cmdBuffer.CmdBindIndexBuffer(_cubeIndices); cmdBuffer.CmdDrawIndexed(_cubeIndices.Count); cmdBuffer.CmdEndRenderPass(); } private Sampler CreateSampler() { var createInfo = new SamplerCreateInfo { MagFilter = Filter.Linear, MinFilter = Filter.Linear, MipmapMode = SamplerMipmapMode.Linear }; // We also enable anisotropic filtering. Because that feature is optional, it must be // checked if it is supported by the device. if (Context.Features.SamplerAnisotropy) { createInfo.AnisotropyEnable = true; createInfo.MaxAnisotropy = Context.Properties.Limits.MaxSamplerAnisotropy; } else { createInfo.MaxAnisotropy = 1.0f; } return Context.Device.CreateSampler(createInfo); } private void SetViewProjection() { const float cameraDistance = 2.5f; _wvp.View = Matrix4x4.CreateLookAt(Vector3.UnitZ * cameraDistance, Vector3.Zero, Vector3.UnitY); _wvp.Projection = Matrix4x4.CreatePerspectiveFieldOfView( (float)Math.PI / 4, (float)Host.Width / Host.Height, 1.0f, 1000.0f); } private void UpdateUniformBuffers() { IntPtr ptr = _uniformBuffer.Memory.Map(0, Interop.SizeOf<WorldViewProjection>()); Interop.Write(ptr, ref _wvp); _uniformBuffer.Memory.Unmap(); } private DescriptorPool CreateDescriptorPool() { var descriptorPoolSizes = new[] { new DescriptorPoolSize(DescriptorType.UniformBuffer, 1), new DescriptorPoolSize(DescriptorType.CombinedImageSampler, 1) }; return Context.Device.CreateDescriptorPool( new DescriptorPoolCreateInfo(descriptorPoolSizes.Length, descriptorPoolSizes)); } private DescriptorSet CreateDescriptorSet() { DescriptorSet descriptorSet = _descriptorPool.AllocateSets(new DescriptorSetAllocateInfo(1, _descriptorSetLayout))[0]; // Update the descriptor set for the shader binding point. var writeDescriptorSets = new[] { new WriteDescriptorSet(descriptorSet, 0, 0, 1, DescriptorType.UniformBuffer, bufferInfo: new[] { new DescriptorBufferInfo(_uniformBuffer) }), new WriteDescriptorSet(descriptorSet, 1, 0, 1, DescriptorType.CombinedImageSampler, imageInfo: new[] { new DescriptorImageInfo(_sampler, _cubeTexture.View, ImageLayout.General) }) }; _descriptorPool.UpdateSets(writeDescriptorSets); return descriptorSet; } private DescriptorSetLayout CreateDescriptorSetLayout() { return Context.Device.CreateDescriptorSetLayout(new DescriptorSetLayoutCreateInfo( new DescriptorSetLayoutBinding(0, DescriptorType.UniformBuffer, 1, ShaderStages.Vertex), new DescriptorSetLayoutBinding(1, DescriptorType.CombinedImageSampler, 1, ShaderStages.Fragment))); } private PipelineLayout CreatePipelineLayout() { return Context.Device.CreatePipelineLayout(new PipelineLayoutCreateInfo( new[] { _descriptorSetLayout })); } private RenderPass CreateRenderPass() { var attachments = new[] { // Color attachment. new AttachmentDescription { Format = Swapchain.Format, Samples = SampleCounts.Count1, LoadOp = AttachmentLoadOp.Clear, StoreOp = AttachmentStoreOp.Store, StencilLoadOp = AttachmentLoadOp.DontCare, StencilStoreOp = AttachmentStoreOp.DontCare, InitialLayout = ImageLayout.Undefined, FinalLayout = ImageLayout.PresentSrcKhr }, // Depth attachment. new AttachmentDescription { Format = _depthStencilBuffer.Format, Samples = SampleCounts.Count1, LoadOp = AttachmentLoadOp.Clear, StoreOp = AttachmentStoreOp.DontCare, StencilLoadOp = AttachmentLoadOp.DontCare, StencilStoreOp = AttachmentStoreOp.DontCare, InitialLayout = ImageLayout.Undefined, FinalLayout = ImageLayout.DepthStencilAttachmentOptimal } }; var subpasses = new[] { new SubpassDescription( new[] { new AttachmentReference(0, ImageLayout.ColorAttachmentOptimal) }, new AttachmentReference(1, ImageLayout.DepthStencilAttachmentOptimal)) }; var dependencies = new[] { new SubpassDependency { SrcSubpass = Constant.SubpassExternal, DstSubpass = 0, SrcStageMask = PipelineStages.BottomOfPipe, DstStageMask = PipelineStages.ColorAttachmentOutput, SrcAccessMask = Accesses.MemoryRead, DstAccessMask = Accesses.ColorAttachmentRead | Accesses.ColorAttachmentWrite, DependencyFlags = Dependencies.ByRegion }, new SubpassDependency { SrcSubpass = 0, DstSubpass = Constant.SubpassExternal, SrcStageMask = PipelineStages.ColorAttachmentOutput, DstStageMask = PipelineStages.BottomOfPipe, SrcAccessMask = Accesses.ColorAttachmentRead | Accesses.ColorAttachmentWrite, DstAccessMask = Accesses.MemoryRead, DependencyFlags = Dependencies.ByRegion } }; var createInfo = new RenderPassCreateInfo(subpasses, attachments, dependencies); return Context.Device.CreateRenderPass(createInfo); } private ImageView[] CreateImageViews() { var imageViews = new ImageView[SwapchainImages.Length]; for (int i = 0; i < SwapchainImages.Length; i++) { imageViews[i] = SwapchainImages[i].CreateView(new ImageViewCreateInfo( Swapchain.Format, new ImageSubresourceRange(ImageAspects.Color, 0, 1, 0, 1))); } return imageViews; } private Framebuffer[] CreateFramebuffers() { var framebuffers = new Framebuffer[SwapchainImages.Length]; for (int i = 0; i < SwapchainImages.Length; i++) { framebuffers[i] = _renderPass.CreateFramebuffer(new FramebufferCreateInfo( new[] { _imageViews[i], _depthStencilBuffer.View }, Host.Width, Host.Height)); } return framebuffers; } private Pipeline CreateGraphicsPipeline() { // Create shader modules. Shader modules are one of the objects required to create the // graphics pipeline. But after the pipeline is created, we don't need these shader // modules anymore, so we dispose them. ShaderModule vertexShader = Content.Load<ShaderModule>("Shader.vert.spv"); ShaderModule fragmentShader = Content.Load<ShaderModule>("Shader.frag.spv"); var shaderStageCreateInfos = new[] { new PipelineShaderStageCreateInfo(ShaderStages.Vertex, vertexShader, "main"), new PipelineShaderStageCreateInfo(ShaderStages.Fragment, fragmentShader, "main") }; var vertexInputStateCreateInfo = new PipelineVertexInputStateCreateInfo( new[] { new VertexInputBindingDescription(0, Interop.SizeOf<Vertex>(), VertexInputRate.Vertex) }, new[] { new VertexInputAttributeDescription(0, 0, Format.R32G32B32SFloat, 0), // Position. new VertexInputAttributeDescription(1, 0, Format.R32G32B32SFloat, 12), // Normal. new VertexInputAttributeDescription(2, 0, Format.R32G32SFloat, 24) // TexCoord. } ); var inputAssemblyStateCreateInfo = new PipelineInputAssemblyStateCreateInfo(PrimitiveTopology.TriangleList); var viewportStateCreateInfo = new PipelineViewportStateCreateInfo( new Viewport(0, 0, Host.Width, Host.Height), new Rect2D(0, 0, Host.Width, Host.Height)); var rasterizationStateCreateInfo = new PipelineRasterizationStateCreateInfo { PolygonMode = PolygonMode.Fill, CullMode = CullModes.Back, FrontFace = FrontFace.CounterClockwise, LineWidth = 1.0f }; var multisampleStateCreateInfo = new PipelineMultisampleStateCreateInfo { RasterizationSamples = SampleCounts.Count1, MinSampleShading = 1.0f }; var depthStencilCreateInfo = new PipelineDepthStencilStateCreateInfo { DepthTestEnable = true, DepthWriteEnable = true, DepthCompareOp = CompareOp.LessOrEqual, Back = new StencilOpState { FailOp = StencilOp.Keep, PassOp = StencilOp.Keep, CompareOp = CompareOp.Always }, Front = new StencilOpState { FailOp = StencilOp.Keep, PassOp = StencilOp.Keep, CompareOp = CompareOp.Always } }; var colorBlendAttachmentState = new PipelineColorBlendAttachmentState { SrcColorBlendFactor = BlendFactor.One, DstColorBlendFactor = BlendFactor.Zero, ColorBlendOp = BlendOp.Add, SrcAlphaBlendFactor = BlendFactor.One, DstAlphaBlendFactor = BlendFactor.Zero, AlphaBlendOp = BlendOp.Add, ColorWriteMask = ColorComponents.All }; var colorBlendStateCreateInfo = new PipelineColorBlendStateCreateInfo( new[] { colorBlendAttachmentState }); var pipelineCreateInfo = new GraphicsPipelineCreateInfo( _pipelineLayout, _renderPass, 0, shaderStageCreateInfos, inputAssemblyStateCreateInfo, vertexInputStateCreateInfo, rasterizationStateCreateInfo, viewportState: viewportStateCreateInfo, multisampleState: multisampleStateCreateInfo, depthStencilState: depthStencilCreateInfo, colorBlendState: colorBlendStateCreateInfo); return Context.Device.CreateGraphicsPipeline(pipelineCreateInfo); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.ResponseStream // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Net.Sockets; using System.Text; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal partial class HttpResponseStream : Stream { private HttpListenerResponse _response; private bool _ignore_errors; private bool _trailer_sent; private Stream _stream; internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors) { _response = response; _ignore_errors = ignore_errors; _stream = stream; } private void DisposeCore() { byte[] bytes = null; MemoryStream ms = GetHeaders(true); bool chunked = _response.SendChunked; if (_stream.CanWrite) { try { if (ms != null) { long start = ms.Position; if (chunked && !_trailer_sent) { bytes = GetChunkSizeBytes(0, true); ms.Position = ms.Length; ms.Write(bytes, 0, bytes.Length); } InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start)); _trailer_sent = true; } else if (chunked && !_trailer_sent) { bytes = GetChunkSizeBytes(0, true); InternalWrite(bytes, 0, bytes.Length); _trailer_sent = true; } } catch (HttpListenerException) { // Ignore error due to connection reset by peer } } _response.Close(); } internal async Task WriteWebSocketHandshakeHeadersAsync() { if (_closed) throw new ObjectDisposedException(GetType().ToString()); if (_stream.CanWrite) { MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true); bool chunked = _response.SendChunked; long start = ms.Position; if (chunked) { byte[] bytes = GetChunkSizeBytes(0, true); ms.Position = ms.Length; ms.Write(bytes, 0, bytes.Length); } await InternalWriteAsync(ms.GetBuffer(), (int)start, (int)(ms.Length - start)).ConfigureAwait(false); await _stream.FlushAsync().ConfigureAwait(false); } } private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false) { // SendHeaders works on shared headers lock (_response._headersLock) { if (_response.SentHeaders) { return null; } MemoryStream ms = new MemoryStream(); _response.SendHeaders(closing, ms, isWebSocketHandshake); return ms; } } private static byte[] s_crlf = new byte[] { 13, 10 }; private static byte[] GetChunkSizeBytes(int size, bool final) { string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : ""); return Encoding.ASCII.GetBytes(str); } internal void InternalWrite(byte[] buffer, int offset, int count) { if (_ignore_errors) { try { _stream.Write(buffer, offset, count); } catch { } } else { try { _stream.Write(buffer, offset, count); } catch (IOException ex) { throw new HttpListenerException(ex.HResult, ex.Message); } } } internal Task InternalWriteAsync(byte[] buffer, int offset, int count) => _ignore_errors ? InternalWriteIgnoreErrorsAsync(buffer, offset, count) : _stream.WriteAsync(buffer, offset, count); private async Task InternalWriteIgnoreErrorsAsync(byte[] buffer, int offset, int count) { try { await _stream.WriteAsync(buffer, offset, count).ConfigureAwait(false); } catch { } } private void WriteCore(byte[] buffer, int offset, int size) { if (size == 0) return; byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { long start = ms.Position; // After the possible preamble for the encoding ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(size, false); ms.Write(bytes, 0, bytes.Length); } int new_count = Math.Min(size, 16384 - (int)ms.Position + (int)start); ms.Write(buffer, offset, new_count); size -= new_count; offset += new_count; InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start)); ms.SetLength(0); ms.Capacity = 0; // 'dispose' the buffer in ms. } else if (chunked) { bytes = GetChunkSizeBytes(size, false); InternalWrite(bytes, 0, bytes.Length); } if (size > 0) InternalWrite(buffer, offset, size); if (chunked) InternalWrite(s_crlf, 0, 2); } private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) { if (_closed) { HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this); ares._callback = cback; ares._state = state; ares.Complete(); return ares; } byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { long start = ms.Position; ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(size, false); ms.Write(bytes, 0, bytes.Length); } ms.Write(buffer, offset, size); buffer = ms.GetBuffer(); offset = (int)start; size = (int)(ms.Position - start); } else if (chunked) { bytes = GetChunkSizeBytes(size, false); InternalWrite(bytes, 0, bytes.Length); } try { return _stream.BeginWrite(buffer, offset, size, cback, state); } catch (IOException ex) { if (_ignore_errors) { HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this); ares._callback = cback; ares._state = state; ares.Complete(); return ares; } else { throw new HttpListenerException(ex.HResult, ex.Message); } } } private void EndWriteCore(IAsyncResult asyncResult) { if (_closed) return; if (_ignore_errors) { try { _stream.EndWrite(asyncResult); if (_response.SendChunked) _stream.Write(s_crlf, 0, 2); } catch { } } else { try { _stream.EndWrite(asyncResult); if (_response.SendChunked) _stream.Write(s_crlf, 0, 2); } catch (IOException ex) { // NetworkStream wraps exceptions in IOExceptions; if the underlying socket operation // failed because of invalid arguments or usage, propagate that error. Otherwise // wrap the whole thing in an HttpListenerException. This is all to match Windows behavior. if (ex.InnerException is ArgumentException || ex.InnerException is InvalidOperationException) { ExceptionDispatchInfo.Throw(ex.InnerException); } throw new HttpListenerException(ex.HResult, ex.Message); } } } } }
// // T4EditorExtension.cs // // Author: // Michael Hutchinson <[email protected]> // // Copyright (c) 2009 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoDevelop.Ide.CodeCompletion; using MonoDevelop.Projects.Dom; using MonoDevelop.Ide.Gui.Content; using MonoDevelop.DesignerSupport; using MonoDevelop.TextTemplating.Parser; using MonoDevelop.Ide; namespace MonoDevelop.TextTemplating.Gui { public class T4EditorExtension : CompletionTextEditorExtension, IOutlinedDocument { bool disposed; T4ParsedDocument parsedDoc; public T4EditorExtension () { } public override void Initialize () { base.Initialize (); MonoDevelop.Projects.Dom.Parser.ProjectDomService.ParsedDocumentUpdated += OnParseInformationChanged; parsedDoc = (T4ParsedDocument)Document.ParsedDocument; if (parsedDoc != null) { RefreshOutline (); } } public override void Dispose () { if (disposed) return; disposed = true; MonoDevelop.Projects.Dom.Parser.ProjectDomService.ParsedDocumentUpdated -= OnParseInformationChanged; base.Dispose (); } void OnParseInformationChanged (object sender, MonoDevelop.Projects.Dom.ParsedDocumentEventArgs args) { if (FileName == args.FileName && args.ParsedDocument != null) { parsedDoc = (T4ParsedDocument)args.ParsedDocument; RefreshOutline (); } } #region Convenience accessors, from BaseXmlEditorExtension protected T4ParsedDocument ParsedDoc { get { return parsedDoc; } } protected ITextBuffer Buffer { get { if (Document == null) throw new InvalidOperationException ("Editor extension not yet initialized"); return Document.GetContent<ITextBuffer> (); } } protected IEditableTextBuffer EditableBuffer { get { if (Document == null) throw new InvalidOperationException ("Editor extension not yet initialized"); return Document.GetContent<IEditableTextBuffer> (); } } protected string GetBufferText (DomRegion region) { MonoDevelop.Ide.Gui.Content.ITextBuffer buf = Buffer; int start = buf.GetPositionFromLineColumn (region.Start.Line, region.Start.Column); int end = buf.GetPositionFromLineColumn (region.End.Line, region.End.Column); if (end > start && start >= 0) return buf.GetText (start, end); else return null; } #endregion #region Code completion public override ICompletionDataList CodeCompletionCommand (CodeCompletionContext completionContext) { int pos = completionContext.TriggerOffset; string txt = Editor.GetText (pos - 1, pos); int triggerWordLength = 0; if (txt.Length > 0) { return HandleCodeCompletion ((CodeCompletionContext) completionContext, true, ref triggerWordLength); } return null; } public override ICompletionDataList HandleCodeCompletion ( CodeCompletionContext completionContext, char completionChar, ref int triggerWordLength) { int pos = completionContext.TriggerOffset; if (pos > 0 && Editor.GetCharAt (pos - 1) == completionChar) { return HandleCodeCompletion ((CodeCompletionContext) completionContext, false, ref triggerWordLength); } return null; } protected virtual ICompletionDataList HandleCodeCompletion ( CodeCompletionContext completionContext, bool forced, ref int triggerWordLength) { //IEditableTextBuffer buf = this.EditableBuffer; return null; } #endregion #region Outline bool refreshingOutline = false; MonoDevelop.Ide.Gui.Components.PadTreeView outlineTreeView; Gtk.TreeStore outlineTreeStore; Gtk.Widget IOutlinedDocument.GetOutlineWidget () { if (outlineTreeView != null) return outlineTreeView; outlineTreeStore = new Gtk.TreeStore (typeof(string), typeof (Gdk.Color), typeof (Mono.TextTemplating.ISegment)); outlineTreeView = new MonoDevelop.Ide.Gui.Components.PadTreeView (outlineTreeStore); outlineTreeView.Realized += delegate { RefillOutlineStore (); }; outlineTreeView.TextRenderer.Xpad = 0; outlineTreeView.TextRenderer.Ypad = 0; outlineTreeView.AppendColumn ("Node", outlineTreeView.TextRenderer, "text", 0, "foreground-gdk", 1); outlineTreeView.HeadersVisible = false; outlineTreeView.Selection.Changed += delegate { Gtk.TreeIter iter; if (!outlineTreeView.Selection.GetSelected (out iter)) return; SelectSegment ((Mono.TextTemplating.ISegment )outlineTreeStore.GetValue (iter, 2)); }; RefillOutlineStore (); var sw = new MonoDevelop.Components.CompactScrolledWindow ();; sw.Add (outlineTreeView); sw.ShowAll (); return sw; } void RefreshOutline () { if (refreshingOutline || outlineTreeView == null ) return; refreshingOutline = true; GLib.Timeout.Add (3000, refillOutlineStoreIdleHandler); } bool refillOutlineStoreIdleHandler () { refreshingOutline = false; RefillOutlineStore (); return false; } void RefillOutlineStore (T4ParsedDocument doc, Gtk.TreeStore store) { if (doc == null) return; Gdk.Color normal = new Gdk.Color (0x00, 0x00, 0x00); Gdk.Color blue = new Gdk.Color (0x10, 0x40, 0xE0); Gdk.Color green = new Gdk.Color (0x08, 0xC0, 0x30); Gdk.Color orange = new Gdk.Color (0xFF, 0xA0, 0x00); Gdk.Color red = new Gdk.Color (0xC0, 0x00, 0x20); Gtk.TreeIter parent = Gtk.TreeIter.Zero; foreach (Mono.TextTemplating.ISegment segment in doc.TemplateSegments) { Mono.TextTemplating.Directive dir = segment as Mono.TextTemplating.Directive; if (dir != null) { parent = Gtk.TreeIter.Zero; store.AppendValues ("<#@ " + dir.Name + " #>", red, segment); continue; } Mono.TextTemplating.TemplateSegment ts = segment as Mono.TextTemplating.TemplateSegment; if (ts != null) { string name; if (ts.Text.Length > 40) { name = ts.Text.Substring (0, 40) + "..."; } else { name = ts.Text; } name = name.Replace ('\n', ' ').Trim (); if (name.Length == 0) continue; if (ts.Type == Mono.TextTemplating.SegmentType.Expression) { store.AppendValues (parent, "<#= " + name + " #>", orange, segment); } else { if (ts.Type == Mono.TextTemplating.SegmentType.Block) { name = "<#" + name + " #>"; store.AppendValues (name, blue, segment); parent = Gtk.TreeIter.Zero; } else if (ts.Type == Mono.TextTemplating.SegmentType.Helper) { name = "<#+" + name + " #>"; store.AppendValues (name, green, segment); parent = Gtk.TreeIter.Zero; } else if (ts.Type == Mono.TextTemplating.SegmentType.Content) { parent = store.AppendValues (name, normal, segment); } } } } } void RefillOutlineStore () { DispatchService.AssertGuiThread (); Gdk.Threads.Enter (); refreshingOutline = false; if (outlineTreeStore == null || !outlineTreeView.IsRealized) return; outlineTreeStore.Clear (); if (ParsedDoc != null) { DateTime start = DateTime.Now; RefillOutlineStore (ParsedDoc, outlineTreeStore); outlineTreeView.ExpandAll (); outlineTreeView.ExpandAll (); MonoDevelop.Core.LoggingService.LogDebug ("Built outline in {0}ms", (DateTime.Now - start).Milliseconds); } Gdk.Threads.Leave (); } void IOutlinedDocument.ReleaseOutlineWidget () { if (outlineTreeView == null) return; Gtk.ScrolledWindow w = (Gtk.ScrolledWindow) outlineTreeView.Parent; w.Destroy (); outlineTreeView.Destroy (); outlineTreeStore.Dispose (); outlineTreeStore = null; outlineTreeView = null; } void SelectSegment (Mono.TextTemplating.ISegment seg) { int s = Editor.GetPositionFromLineColumn (seg.TagStartLocation.Line, seg.TagStartLocation.Column); if (s > -1) { Editor.CursorPosition = s; Editor.ShowPosition (s); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareGreaterThanInt32() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanInt32 testClass) { var result = Avx2.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareGreaterThanInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public SimpleBinaryOpTest__CompareGreaterThanInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.CompareGreaterThan( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.CompareGreaterThan( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.CompareGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareGreaterThanInt32(); var result = Avx2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareGreaterThanInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] > right[0]) ? unchecked((int)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? unchecked((int)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareGreaterThan)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI41; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI41 { /// <summary> /// Object attributes tests. /// </summary> [TestFixture()] public class _14_ObjectAttributeTest { /// <summary> /// Attribute with empty value test. /// </summary> [Test()] public void _01_EmptyAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); // Create attribute without the value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS); Assert.IsTrue(attr.type == (uint)CKA.CKA_CLASS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with uint value test. /// </summary> [Test()] public void _02_UintAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); uint originalValue = (uint)CKO.CKO_DATA; // Create attribute with uint value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_CLASS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == UnmanagedMemory.SizeOf(typeof(uint))); uint recoveredValue = 0; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_CLASS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with bool value test. /// </summary> [Test()] public void _03_BoolAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); bool originalValue = true; // Create attribute with bool value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_TOKEN); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == 1); bool recoveredValue = false; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_TOKEN); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with string value test. /// </summary> [Test()] public void _04_StringAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); string originalValue = "Hello world"; // Create attribute with string value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_LABEL); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == originalValue.Length); string recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_LABEL); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null string value attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, (string)null); Assert.IsTrue(attr.type == (uint)CKA.CKA_LABEL); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with byte array value test. /// </summary> [Test()] public void _05_ByteArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute with byte array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ID, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_ID); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == originalValue.Length); byte[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(Convert.ToBase64String(originalValue) == Convert.ToBase64String(recoveredValue)); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_ID); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null byte array value attr = CkaUtils.CreateAttribute(CKA.CKA_ID, (byte[])null); Assert.IsTrue(attr.type == (uint)CKA.CKA_ID); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with DateTime (CKA_DATE) value test. /// </summary> [Test()] public void _06_DateTimeAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); DateTime originalValue = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc); // Create attribute with DateTime value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_START_DATE, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_START_DATE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == 8); DateTime? recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_START_DATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with attribute array value test. /// </summary> [Test()] public void _07_AttributeArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CK_ATTRIBUTE[] originalValue = new CK_ATTRIBUTE[2]; originalValue[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); originalValue[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true); // Create attribute with attribute array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == (UnmanagedMemory.SizeOf(typeof(CK_ATTRIBUTE)) * originalValue.Length)); CK_ATTRIBUTE[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i].type == recoveredValue[i].type); Assert.IsTrue(originalValue[i].valueLen == recoveredValue[i].valueLen); bool originalBool = false; // Read the value of nested attribute CkaUtils.ConvertValue(ref originalValue[i], out originalBool); bool recoveredBool = true; // Read the value of nested attribute CkaUtils.ConvertValue(ref recoveredValue[i], out recoveredBool); Assert.IsTrue(originalBool == recoveredBool); // In this example there is the same pointer to unmanaged memory // in both originalValue and recoveredValue array therefore it // needs to be freed only once. Assert.IsTrue(originalValue[i].value == recoveredValue[i].value); // Free value of nested attributes UnmanagedMemory.Free(ref originalValue[i].value); originalValue[i].valueLen = 0; recoveredValue[i].value = IntPtr.Zero; recoveredValue[i].valueLen = 0; } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null attribute array value attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, (CK_ATTRIBUTE[])null); Assert.IsTrue(attr.type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty attribute array value attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, new CK_ATTRIBUTE[0]); Assert.IsTrue(attr.type == (uint)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with uint array value test. /// </summary> [Test()] public void _08_UintArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); uint[] originalValue = new uint[2]; originalValue[0] = 333333; originalValue[1] = 666666; // Create attribute with uint array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == (UnmanagedMemory.SizeOf(typeof(uint)) * originalValue.Length)); uint[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i] == recoveredValue[i]); } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null uint array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (uint[])null); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty uint array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new uint[0]); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with mechanism array value test. /// </summary> [Test()] public void _09_MechanismArrayAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKM[] originalValue = new CKM[2]; originalValue[0] = CKM.CKM_RSA_PKCS; originalValue[1] = CKM.CKM_AES_CBC; // Create attribute with mechanism array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == (UnmanagedMemory.SizeOf(typeof(uint)) * originalValue.Length)); CKM[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i] == recoveredValue[i]); } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null mechanism array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (CKM[])null); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty mechanism array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new CKM[0]); Assert.IsTrue(attr.type == (uint)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Custom attribute with manually set value test. /// </summary> [Test()] public void _10_CustomAttributeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute without the value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_VALUE); Assert.IsTrue(attr.type == (uint)CKA.CKA_VALUE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Allocate unmanaged memory for attribute value.. attr.value = UnmanagedMemory.Allocate(originalValue.Length); // ..then set the value of attribute.. UnmanagedMemory.Write(attr.value, originalValue); // ..and finally set the length of attribute value. attr.valueLen = (uint)originalValue.Length; Assert.IsTrue(attr.type == (uint)CKA.CKA_VALUE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == originalValue.Length); // Read the value of attribute byte[] recoveredValue = UnmanagedMemory.Read(attr.value, Convert.ToInt32(attr.valueLen)); Assert.IsTrue(Convert.ToBase64String(originalValue) == Convert.ToBase64String(recoveredValue)); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (uint)CKA.CKA_VALUE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } } }
// Keep this file CodeMaid organised and cleaned using ClosedXML.Excel; using ClosedXML.Excel.CalcEngine.Exceptions; using NUnit.Framework; using System; using System.Linq; namespace ClosedXML.Tests.Excel.CalcEngine { [TestFixture] public class LookupTests { private XLWorkbook workbook; #region Setup and teardown [OneTimeTearDown] public void Dispose() { workbook.Dispose(); } [SetUp] public void Init() { // Make sure tests run on a deterministic culture System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); workbook = SetupWorkbook(); } private XLWorkbook SetupWorkbook() { var wb = new XLWorkbook(); var ws = wb.AddWorksheet("Data"); var data = new object[] { new {Id=1, OrderDate = DateTime.Parse("2015-01-06"), Region = "East", Rep = "Jones", Item = "Pencil", Units = 95, UnitCost = 1.99, Total = 189.05 }, new {Id=2, OrderDate = DateTime.Parse("2015-01-23"), Region = "Central", Rep = "Kivell", Item = "Binder", Units = 50, UnitCost = 19.99, Total = 999.5}, new {Id=3, OrderDate = DateTime.Parse("2015-02-09"), Region = "Central", Rep = "Jardine", Item = "Pencil", Units = 36, UnitCost = 4.99, Total = 179.64}, new {Id=4, OrderDate = DateTime.Parse("2015-02-26"), Region = "Central", Rep = "Gill", Item = "Pen", Units = 27, UnitCost = 19.99, Total = 539.73}, new {Id=5, OrderDate = DateTime.Parse("2015-03-15"), Region = "West", Rep = "Sorvino", Item = "Pencil", Units = 56, UnitCost = 2.99, Total = 167.44}, new {Id=6, OrderDate = DateTime.Parse("2015-04-01"), Region = "East", Rep = "Jones", Item = "Binder", Units = 60, UnitCost = 4.99, Total = 299.4}, new {Id=7, OrderDate = DateTime.Parse("2015-04-18"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 75, UnitCost = 1.99, Total = 149.25}, new {Id=8, OrderDate = DateTime.Parse("2015-05-05"), Region = "Central", Rep = "Jardine", Item = "Pencil", Units = 90, UnitCost = 4.99, Total = 449.1}, new {Id=9, OrderDate = DateTime.Parse("2015-05-22"), Region = "West", Rep = "Thompson", Item = "Pencil", Units = 32, UnitCost = 1.99, Total = 63.68}, new {Id=10, OrderDate = DateTime.Parse("2015-06-08"), Region = "East", Rep = "Jones", Item = "Binder", Units = 60, UnitCost = 8.99, Total = 539.4}, new {Id=11, OrderDate = DateTime.Parse("2015-06-25"), Region = "Central", Rep = "Morgan", Item = "Pencil", Units = 90, UnitCost = 4.99, Total = 449.1}, new {Id=12, OrderDate = DateTime.Parse("2015-07-12"), Region = "East", Rep = "Howard", Item = "Binder", Units = 29, UnitCost = 1.99, Total = 57.71}, new {Id=13, OrderDate = DateTime.Parse("2015-07-29"), Region = "East", Rep = "Parent", Item = "Binder", Units = 81, UnitCost = 19.99, Total = 1619.19}, new {Id=14, OrderDate = DateTime.Parse("2015-08-15"), Region = "East", Rep = "Jones", Item = "Pencil", Units = 35, UnitCost = 4.99, Total = 174.65}, new {Id=15, OrderDate = DateTime.Parse("2015-09-01"), Region = "Central", Rep = "Smith", Item = "Desk", Units = 2, UnitCost = 125, Total = 250}, new {Id=16, OrderDate = DateTime.Parse("2015-09-18"), Region = "East", Rep = "Jones", Item = "Pen Set", Units = 16, UnitCost = 15.99, Total = 255.84}, new {Id=17, OrderDate = DateTime.Parse("2015-10-05"), Region = "Central", Rep = "Morgan", Item = "Binder", Units = 28, UnitCost = 8.99, Total = 251.72}, new {Id=18, OrderDate = DateTime.Parse("2015-10-22"), Region = "East", Rep = "Jones", Item = "Pen", Units = 64, UnitCost = 8.99, Total = 575.36}, new {Id=19, OrderDate = DateTime.Parse("2015-11-08"), Region = "East", Rep = "Parent", Item = "Pen", Units = 15, UnitCost = 19.99, Total = 299.85}, new {Id=20, OrderDate = DateTime.Parse("2015-11-25"), Region = "Central", Rep = "Kivell", Item = "Pen Set", Units = 96, UnitCost = 4.99, Total = 479.04}, new {Id=21, OrderDate = DateTime.Parse("2015-12-12"), Region = "Central", Rep = "Smith", Item = "Pencil", Units = 67, UnitCost = 1.29, Total = 86.43}, new {Id=22, OrderDate = DateTime.Parse("2015-12-29"), Region = "East", Rep = "Parent", Item = "Pen Set", Units = 74, UnitCost = 15.99, Total = 1183.26}, new {Id=23, OrderDate = DateTime.Parse("2016-01-15"), Region = "Central", Rep = "Gill", Item = "Binder", Units = 46, UnitCost = 8.99, Total = 413.54}, new {Id=24, OrderDate = DateTime.Parse("2016-02-01"), Region = "Central", Rep = "Smith", Item = "Binder", Units = 87, UnitCost = 15, Total = 1305}, new {Id=25, OrderDate = DateTime.Parse("2016-02-18"), Region = "East", Rep = "Jones", Item = "Binder", Units = 4, UnitCost = 4.99, Total = 19.96}, new {Id=26, OrderDate = DateTime.Parse("2016-03-07"), Region = "West", Rep = "Sorvino", Item = "Binder", Units = 7, UnitCost = 19.99, Total = 139.93}, new {Id=27, OrderDate = DateTime.Parse("2016-03-24"), Region = "Central", Rep = "Jardine", Item = "Pen Set", Units = 50, UnitCost = 4.99, Total = 249.5}, new {Id=28, OrderDate = DateTime.Parse("2016-04-10"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 66, UnitCost = 1.99, Total = 131.34}, new {Id=29, OrderDate = DateTime.Parse("2016-04-27"), Region = "East", Rep = "Howard", Item = "Pen", Units = 96, UnitCost = 4.99, Total = 479.04}, new {Id=30, OrderDate = DateTime.Parse("2016-05-14"), Region = "Central", Rep = "Gill", Item = "Pencil", Units = 53, UnitCost = 1.29, Total = 68.37}, new {Id=31, OrderDate = DateTime.Parse("2016-05-31"), Region = "Central", Rep = "Gill", Item = "Binder", Units = 80, UnitCost = 8.99, Total = 719.2}, new {Id=32, OrderDate = DateTime.Parse("2016-06-17"), Region = "Central", Rep = "Kivell", Item = "Desk", Units = 5, UnitCost = 125, Total = 625}, new {Id=33, OrderDate = DateTime.Parse("2016-07-04"), Region = "East", Rep = "Jones", Item = "Pen Set", Units = 62, UnitCost = 4.99, Total = 309.38}, new {Id=34, OrderDate = DateTime.Parse("2016-07-21"), Region = "Central", Rep = "Morgan", Item = "Pen Set", Units = 55, UnitCost = 12.49, Total = 686.95}, new {Id=35, OrderDate = DateTime.Parse("2016-08-07"), Region = "Central", Rep = "Kivell", Item = "Pen Set", Units = 42, UnitCost = 23.95, Total = 1005.9}, new {Id=36, OrderDate = DateTime.Parse("2016-08-24"), Region = "West", Rep = "Sorvino", Item = "Desk", Units = 3, UnitCost = 275, Total = 825}, new {Id=37, OrderDate = DateTime.Parse("2016-09-10"), Region = "Central", Rep = "Gill", Item = "Pencil", Units = 7, UnitCost = 1.29, Total = 9.03}, new {Id=38, OrderDate = DateTime.Parse("2016-09-27"), Region = "West", Rep = "Sorvino", Item = "Pen", Units = 76, UnitCost = 1.99, Total = 151.24}, new {Id=39, OrderDate = DateTime.Parse("2016-10-14"), Region = "West", Rep = "Thompson", Item = "Binder", Units = 57, UnitCost = 19.99, Total = 1139.43}, new {Id=40, OrderDate = DateTime.Parse("2016-10-31"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 14, UnitCost = 1.29, Total = 18.06}, new {Id=41, OrderDate = DateTime.Parse("2016-11-17"), Region = "Central", Rep = "Jardine", Item = "Binder", Units = 11, UnitCost = 4.99, Total = 54.89}, new {Id=42, OrderDate = DateTime.Parse("2016-12-04"), Region = "Central", Rep = "Jardine", Item = "Binder", Units = 94, UnitCost = 19.99, Total = 1879.06}, new {Id=43, OrderDate = DateTime.Parse("2016-12-21"), Region = "Central", Rep = "Andrews", Item = "Binder", Units = 28, UnitCost = 4.99, Total = 139.72} }; ws.FirstCell() .CellBelow() .CellRight() .InsertTable(data); return wb; } #endregion Setup and teardown [Test] public void Hlookup() { // Range lookup false var value = workbook.Evaluate(@"=HLOOKUP(""Total"",Data!$B$2:$I$71,4,FALSE)"); Assert.AreEqual(179.64, value); } [Test] public void Hyperlink() { XLHyperlink hl; hl = XLWorkbook.EvaluateExpr("HYPERLINK(\"http://github.com/ClosedXML/ClosedXML\")") as XLHyperlink; Assert.IsNotNull(hl); Assert.AreEqual("http://github.com/ClosedXML/ClosedXML", hl.ExternalAddress.ToString()); Assert.AreEqual(string.Empty, hl.Tooltip); hl = XLWorkbook.EvaluateExpr("HYPERLINK(\"mailto:[email protected]\", \"[email protected]\")") as XLHyperlink; Assert.IsNotNull(hl); Assert.AreEqual("mailto:[email protected]", hl.ExternalAddress.ToString()); Assert.AreEqual("[email protected]", hl.Tooltip); } [Test] public void Index() { var ws = workbook.Worksheets.First(); Assert.AreEqual("Kivell", ws.Evaluate(@"=INDEX(B2:J12, 3, 4)")); // We don't support optional parameter fully here yet. // Supposedly, if you omit e.g. the row number, then ROW() of the calling cell should be assumed // Assert.AreEqual("Gill", ws.Evaluate(@"=INDEX(B2:J12, , 4)")); Assert.AreEqual("Rep", ws.Evaluate(@"=INDEX(B2:I2, 4)")); Assert.AreEqual(3, ws.Evaluate(@"=INDEX(B2:B20, 4)")); Assert.AreEqual(3, ws.Evaluate(@"=INDEX(B2:B20, 4, 1)")); Assert.AreEqual(3, ws.Evaluate(@"=INDEX(B2:B20, 4, )")); Assert.AreEqual("Rep", ws.Evaluate(@"=INDEX(B2:J2, 1, 4)")); Assert.AreEqual("Rep", ws.Evaluate(@"=INDEX(B2:J2, , 4)")); } [Test] public void Index_Exceptions() { var ws = workbook.Worksheets.First(); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:I10, 20, 1)")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:I10, 1, 10)")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:I2, 10)")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:I2, 4, 1)")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:I2, 4, )")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:B10, 20)")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:B10, 20, )")); Assert.Throws<CellReferenceException>(() => ws.Evaluate(@"INDEX(B2:B10, , 4)")); } [Test] public void Match() { var ws = workbook.Worksheets.First(); Object value; value = ws.Evaluate(@"=MATCH(""Rep"", B2:I2, 0)"); Assert.AreEqual(4, value); value = ws.Evaluate(@"=MATCH(""Rep"", A2:Z2, 0)"); Assert.AreEqual(5, value); value = ws.Evaluate(@"=MATCH(""REP"", B2:I2, 0)"); Assert.AreEqual(4, value); value = ws.Evaluate(@"=MATCH(95, B3:I3, 0)"); Assert.AreEqual(6, value); value = ws.Evaluate(@"=MATCH(DATE(2015,1,6), B3:I3, 0)"); Assert.AreEqual(2, value); value = ws.Evaluate(@"=MATCH(1.99, 3:3, 0)"); Assert.AreEqual(8, value); value = ws.Evaluate(@"=MATCH(43, B:B, 0)"); Assert.AreEqual(45, value); value = ws.Evaluate(@"=MATCH(""cENtraL"", D3:D45, 0)"); Assert.AreEqual(2, value); value = ws.Evaluate(@"=MATCH(4.99, H:H, 0)"); Assert.AreEqual(5, value); value = ws.Evaluate(@"=MATCH(""Rapture"", B2:I2, 1)"); Assert.AreEqual(2, value); value = ws.Evaluate(@"=MATCH(22.5, B3:B45, 1)"); Assert.AreEqual(22, value); value = ws.Evaluate(@"=MATCH(""Rep"", B2:I2)"); Assert.AreEqual(4, value); value = ws.Evaluate(@"=MATCH(""Rep"", B2:I2, 1)"); Assert.AreEqual(4, value); value = ws.Evaluate(@"=MATCH(40, G3:G6, -1)"); Assert.AreEqual(2, value); } [Test] public void Match_Exceptions() { var ws = workbook.Worksheets.First(); Assert.Throws<CellValueException>(() => ws.Evaluate(@"=MATCH(""Rep"", B2:I5)")); Assert.Throws<NoValueAvailableException>(() => ws.Evaluate(@"=MATCH(""Dummy"", B2:I2, 0)")); Assert.Throws<NoValueAvailableException>(() => ws.Evaluate(@"=MATCH(4.5,B3:B45,-1)")); } [Test] public void Vlookup() { // Range lookup false var value = workbook.Evaluate("=VLOOKUP(3,Data!$B$2:$I$71,3,FALSE)"); Assert.AreEqual("Central", value); value = workbook.Evaluate("=VLOOKUP(DATE(2015,5,22),Data!C:I,7,FALSE)"); Assert.AreEqual(63.68, value); value = workbook.Evaluate(@"=VLOOKUP(""Central"",Data!D:E,2,FALSE)"); Assert.AreEqual("Kivell", value); // Case insensitive lookup value = workbook.Evaluate(@"=VLOOKUP(""central"",Data!D:E,2,FALSE)"); Assert.AreEqual("Kivell", value); // Range lookup true value = workbook.Evaluate("=VLOOKUP(3,Data!$B$2:$I$71,8,TRUE)"); Assert.AreEqual(179.64, value); value = workbook.Evaluate("=VLOOKUP(3,Data!$B$2:$I$71,8)"); Assert.AreEqual(179.64, value); value = workbook.Evaluate("=VLOOKUP(3,Data!$B$2:$I$71,8,)"); Assert.AreEqual(179.64, value); value = workbook.Evaluate("=VLOOKUP(14.5,Data!$B$2:$I$71,8,TRUE)"); Assert.AreEqual(174.65, value); value = workbook.Evaluate("=VLOOKUP(50,Data!$B$2:$I$71,8,TRUE)"); Assert.AreEqual(139.72, value); } [Test] public void Vlookup_Exceptions() { Assert.Throws<NoValueAvailableException>(() => workbook.Evaluate(@"=VLOOKUP("""",Data!$B$2:$I$71,3,FALSE)")); Assert.Throws<NoValueAvailableException>(() => workbook.Evaluate(@"=VLOOKUP(50,Data!$B$2:$I$71,3,FALSE)")); Assert.Throws<NoValueAvailableException>(() => workbook.Evaluate(@"=VLOOKUP(-1,Data!$B$2:$I$71,2,TRUE)")); Assert.Throws<CellReferenceException>(() => workbook.Evaluate(@"=VLOOKUP(20,Data!$B$2:$I$71,9,FALSE)")); } } }
/* * 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 NUnit.Framework; using KeywordAnalyzer = Lucene.Net.Analysis.KeywordAnalyzer; using Document = Lucene.Net.Documents.Document; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength; using Directory = Lucene.Net.Store.Directory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { [TestFixture] public class TestTopDocsCollector:LuceneTestCase { private sealed class MyTopsDocCollector : TopDocsCollector<ScoreDoc> { private int idx = 0; private int base_Renamed = 0; public MyTopsDocCollector(int size):base(new HitQueue(size, false)) { } public /*protected internal*/ override TopDocs NewTopDocs(ScoreDoc[] results, int start) { if (results == null) { return EMPTY_TOPDOCS; } float maxScore = System.Single.NaN; if (start == 0) { maxScore = results[0].Score; } else { for (int i = pq.Size(); i > 1; i--) { pq.Pop(); } maxScore = pq.Pop().Score; } return new TopDocs(internalTotalHits, results, maxScore); } public override void Collect(int doc) { ++internalTotalHits; pq.InsertWithOverflow(new ScoreDoc(doc + base_Renamed, Lucene.Net.Search.TestTopDocsCollector.scores[idx++])); } public override void SetNextReader(IndexReader reader, int docBase) { base_Renamed = docBase; } public override void SetScorer(Scorer scorer) { // Don't do anything. Assign scores in random } public override bool AcceptsDocsOutOfOrder { get { return true; } } } // Scores array to be used by MyTopDocsCollector. If it is changed, MAX_SCORE // must also change. private static readonly float[] scores = new float[]{0.7767749f, 1.7839992f, 8.9925785f, 7.9608946f, 0.07948637f, 2.6356435f, 7.4950366f, 7.1490803f, 8.108544f, 4.961808f, 2.2423935f, 7.285586f, 4.6699767f, 2.9655676f, 6.953706f, 5.383931f, 6.9916306f, 8.365894f, 7.888485f, 8.723962f, 3.1796896f, 0.39971232f, 1.3077754f, 6.8489285f, 9.17561f, 5.060466f, 7.9793315f, 8.601509f, 4.1858315f, 0.28146625f}; private const float MAX_SCORE = 9.17561f; private Directory dir = new RAMDirectory(); private TopDocsCollector<ScoreDoc> doSearch(int numResults) { Query q = new MatchAllDocsQuery(); IndexSearcher searcher = new IndexSearcher(dir, true); TopDocsCollector<ScoreDoc> tdc = new MyTopsDocCollector(numResults); searcher.Search(q, tdc); searcher.Close(); return tdc; } [SetUp] public override void SetUp() { base.SetUp(); // populate an index with 30 documents, this should be enough for the test. // The documents have no content - the test uses MatchAllDocsQuery(). dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new KeywordAnalyzer(), MaxFieldLength.UNLIMITED); for (int i = 0; i < 30; i++) { writer.AddDocument(new Document()); } writer.Close(); } [TearDown] public override void TearDown() { dir.Close(); dir = null; base.TearDown(); } [Test] public virtual void TestInvalidArguments() { int numResults = 5; TopDocsCollector<ScoreDoc> tdc = doSearch(numResults); // start < 0 Assert.AreEqual(0, tdc.TopDocs(- 1).ScoreDocs.Length); // start > pq.size() Assert.AreEqual(0, tdc.TopDocs(numResults + 1).ScoreDocs.Length); // start == pq.size() Assert.AreEqual(0, tdc.TopDocs(numResults).ScoreDocs.Length); // howMany < 0 Assert.AreEqual(0, tdc.TopDocs(0, - 1).ScoreDocs.Length); // howMany == 0 Assert.AreEqual(0, tdc.TopDocs(0, 0).ScoreDocs.Length); } [Test] public virtual void TestZeroResults() { TopDocsCollector<ScoreDoc> tdc = new MyTopsDocCollector(5); Assert.AreEqual(0, tdc.TopDocs(0, 1).ScoreDocs.Length); } [Test] public virtual void TestFirstResultsPage() { TopDocsCollector<ScoreDoc> tdc = doSearch(15); Assert.AreEqual(10, tdc.TopDocs(0, 10).ScoreDocs.Length); } [Test] public virtual void TestSecondResultsPages() { TopDocsCollector<ScoreDoc> tdc = doSearch(15); // ask for more results than are available Assert.AreEqual(5, tdc.TopDocs(10, 10).ScoreDocs.Length); // ask for 5 results (exactly what there should be tdc = doSearch(15); Assert.AreEqual(5, tdc.TopDocs(10, 5).ScoreDocs.Length); // ask for less results than there are tdc = doSearch(15); Assert.AreEqual(4, tdc.TopDocs(10, 4).ScoreDocs.Length); } [Test] public virtual void TestGetAllResults() { TopDocsCollector<ScoreDoc> tdc = doSearch(15); Assert.AreEqual(15, tdc.TopDocs().ScoreDocs.Length); } [Test] public virtual void TestGetResultsFromStart() { TopDocsCollector<ScoreDoc> tdc = doSearch(15); // should bring all results Assert.AreEqual(15, tdc.TopDocs(0).ScoreDocs.Length); tdc = doSearch(15); // get the last 5 only. Assert.AreEqual(5, tdc.TopDocs(10).ScoreDocs.Length); } [Test] public virtual void TestMaxScore() { // ask for all results TopDocsCollector<ScoreDoc> tdc = doSearch(15); TopDocs td = tdc.TopDocs(); Assert.AreEqual(MAX_SCORE, td.MaxScore, 0f); // ask for 5 last results tdc = doSearch(15); td = tdc.TopDocs(10); Assert.AreEqual(MAX_SCORE, td.MaxScore, 0f); } // This does not test the PQ's correctness, but whether topDocs() // implementations return the results in decreasing score order. [Test] public virtual void TestResultsOrder() { TopDocsCollector<ScoreDoc> tdc = doSearch(15); ScoreDoc[] sd = tdc.TopDocs().ScoreDocs; Assert.AreEqual(MAX_SCORE, sd[0].Score, 0f); for (int i = 1; i < sd.Length; i++) { Assert.IsTrue(sd[i - 1].Score >= sd[i].Score); } } } }
/* * 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.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Newtonsoft.Json; using QuantConnect.Configuration; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Orders.Serialization; using QuantConnect.Packets; using QuantConnect.Statistics; namespace QuantConnect.Lean.Engine.Results { /// <summary> /// Provides base functionality to the implementations of <see cref="IResultHandler"/> /// </summary> public abstract class BaseResultsHandler { // used for resetting out/error upon completion private static readonly TextWriter StandardOut = Console.Out; private static readonly TextWriter StandardError = Console.Error; private string _hostName; /// <summary> /// The main loop update interval /// </summary> protected virtual TimeSpan MainUpdateInterval => TimeSpan.FromSeconds(3); /// <summary> /// The chart update interval /// </summary> protected TimeSpan ChartUpdateInterval = TimeSpan.FromMinutes(1); /// <summary> /// The last position consumed from the <see cref="ITransactionHandler.OrderEvents"/> by <see cref="GetDeltaOrders"/> /// </summary> protected int LastDeltaOrderPosition; /// <summary> /// The last position consumed from the <see cref="ITransactionHandler.OrderEvents"/> while determining delta order events /// </summary> protected int LastDeltaOrderEventsPosition; /// <summary> /// The task in charge of running the <see cref="Run"/> update method /// </summary> private Thread _updateRunner; /// <summary> /// Boolean flag indicating the thread is still active. /// </summary> public bool IsActive => _updateRunner != null && _updateRunner.IsAlive; /// <summary> /// Live packet messaging queue. Queue the messages here and send when the result queue is ready. /// </summary> public ConcurrentQueue<Packet> Messages { get; set; } /// <summary> /// Storage for the price and equity charts of the live results. /// </summary> public ConcurrentDictionary<string, Chart> Charts { get; set; } /// <summary> /// True if the exit has been triggered /// </summary> protected volatile bool ExitTriggered; /// <summary> /// Event set when exit is triggered /// </summary> protected ManualResetEvent ExitEvent { get; } /// <summary> /// The log store instance /// </summary> protected List<LogEntry> LogStore { get; } /// <summary> /// Algorithms performance related chart names /// </summary> /// <remarks>Used to calculate the probabilistic sharpe ratio</remarks> protected List<string> AlgorithmPerformanceCharts { get; } = new List<string> { "Strategy Equity", "Benchmark" }; /// <summary> /// Lock to be used when accessing the chart collection /// </summary> protected object ChartLock { get; } /// <summary> /// The algorithm project id /// </summary> protected int ProjectId { get; set; } /// <summary> /// The maximum amount of RAM (in MB) this algorithm is allowed to utilize /// </summary> protected string RamAllocation { get; set; } /// <summary> /// The algorithm unique compilation id /// </summary> protected string CompileId { get; set; } /// <summary> /// The algorithm job id. /// This is the deploy id for live, backtesting id for backtesting /// </summary> protected string AlgorithmId { get; set; } /// <summary> /// The result handler start time /// </summary> protected DateTime StartTime { get; } /// <summary> /// Customizable dynamic statistics <see cref="IAlgorithm.RuntimeStatistics"/> /// </summary> protected Dictionary<string, string> RuntimeStatistics { get; } /// <summary> /// The handler responsible for communicating messages to listeners /// </summary> protected IMessagingHandler MessagingHandler; /// <summary> /// The transaction handler used to get the algorithms Orders information /// </summary> protected ITransactionHandler TransactionHandler; /// <summary> /// The algorithms starting portfolio value. /// Used to calculate the portfolio return /// </summary> protected decimal StartingPortfolioValue { get; set; } /// <summary> /// The algorithm instance /// </summary> protected IAlgorithm Algorithm { get; set; } /// <summary> /// Gets or sets the current alpha runtime statistics /// </summary> protected AlphaRuntimeStatistics AlphaRuntimeStatistics { get; set; } /// <summary> /// Algorithm currency symbol, used in charting /// </summary> protected string AlgorithmCurrencySymbol { get; set; } /// <summary> /// Closing portfolio value. Used to calculate daily performance. /// </summary> protected decimal DailyPortfolioValue; /// <summary> /// Cumulative max portfolio value. Used to calculate drawdown underwater. /// </summary> protected decimal CumulativeMaxPortfolioValue; /// <summary> /// Sampling period for timespans between resamples of the charting equity. /// </summary> /// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks> protected TimeSpan ResamplePeriod { get; set; } /// <summary> /// How frequently the backtests push messages to the browser. /// </summary> /// <remarks>Update frequency of notification packets</remarks> protected TimeSpan NotificationPeriod { get; set; } /// <summary> /// Directory location to store results /// </summary> protected string ResultsDestinationFolder; /// <summary> /// The order event json converter instance to use /// </summary> protected OrderEventJsonConverter OrderEventJsonConverter { get; set; } /// <summary> /// Creates a new instance /// </summary> protected BaseResultsHandler() { ExitEvent = new ManualResetEvent(false); Charts = new ConcurrentDictionary<string, Chart>(); Messages = new ConcurrentQueue<Packet>(); RuntimeStatistics = new Dictionary<string, string>(); StartTime = DateTime.UtcNow; CompileId = ""; AlgorithmId = ""; ChartLock = new object(); LogStore = new List<LogEntry>(); ResultsDestinationFolder = Config.Get("results-destination-folder", Directory.GetCurrentDirectory()); } /// <summary> /// New order event for the algorithm /// </summary> /// <param name="newEvent">New event details</param> public virtual void OrderEvent(OrderEvent newEvent) { } /// <summary> /// Terminate the result thread and apply any required exit procedures like sending final results /// </summary> public virtual void Exit() { // reset standard out/error Console.SetOut(StandardOut); Console.SetError(StandardError); } /// <summary> /// Gets the current Server statistics /// </summary> protected virtual Dictionary<string, string> GetServerStatistics(DateTime utcNow) { var serverStatistics = OS.GetServerStatistics(); serverStatistics["Hostname"] = _hostName; var upTime = utcNow - StartTime; serverStatistics["Up Time"] = $"{upTime.Days}d {upTime:hh\\:mm\\:ss}"; serverStatistics["Total RAM (MB)"] = RamAllocation; return serverStatistics; } /// <summary> /// Stores the order events /// </summary> /// <param name="utcTime">The utc date associated with these order events</param> /// <param name="orderEvents">The order events to store</param> protected virtual void StoreOrderEvents(DateTime utcTime, List<OrderEvent> orderEvents) { if (orderEvents.Count <= 0) { return; } var filename = $"{AlgorithmId}-order-events.json"; var path = GetResultsPath(filename); var data = JsonConvert.SerializeObject(orderEvents, Formatting.None, OrderEventJsonConverter); File.WriteAllText(path, data); } /// <summary> /// Gets the orders generated starting from the provided <see cref="ITransactionHandler.OrderEvents"/> position /// </summary> /// <returns>The delta orders</returns> protected virtual Dictionary<int, Order> GetDeltaOrders(int orderEventsStartPosition, Func<int, bool> shouldStop) { var deltaOrders = new Dictionary<int, Order>(); foreach (var orderId in TransactionHandler.OrderEvents.Skip(orderEventsStartPosition).Select(orderEvent => orderEvent.OrderId)) { LastDeltaOrderPosition++; if (deltaOrders.ContainsKey(orderId)) { // we can have more than 1 order event per order id continue; } var order = Algorithm.Transactions.GetOrderById(orderId); if (order == null) { // this shouldn't happen but just in case continue; } // for charting order.Price = order.Price.SmartRounding(); deltaOrders[orderId] = order; if (shouldStop(deltaOrders.Count)) { break; } } return deltaOrders; } /// <summary> /// Initialize the result handler with this result packet. /// </summary> /// <param name="job">Algorithm job packet for this result handler</param> /// <param name="messagingHandler">The handler responsible for communicating messages to listeners</param> /// <param name="api">The api instance used for handling logs</param> /// <param name="transactionHandler">The transaction handler used to get the algorithms <see cref="Order"/> information</param> public virtual void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, ITransactionHandler transactionHandler) { _hostName = job.HostName ?? Environment.MachineName; MessagingHandler = messagingHandler; TransactionHandler = transactionHandler; CompileId = job.CompileId; AlgorithmId = job.AlgorithmId; ProjectId = job.ProjectId; RamAllocation = job.RamAllocation.ToStringInvariant(); OrderEventJsonConverter = new OrderEventJsonConverter(AlgorithmId); _updateRunner = new Thread(Run, 0) { IsBackground = true, Name = "Result Thread" }; _updateRunner.Start(); } /// <summary> /// Result handler update method /// </summary> protected abstract void Run(); /// <summary> /// Gets the full path for a results file /// </summary> /// <param name="filename">The filename to add to the path</param> /// <returns>The full path, including the filename</returns> protected string GetResultsPath(string filename) { return Path.Combine(ResultsDestinationFolder, filename); } /// <summary> /// Event fired each time that we add/remove securities from the data feed /// </summary> public virtual void OnSecuritiesChanged(SecurityChanges changes) { } /// <summary> /// Returns the location of the logs /// </summary> /// <param name="id">Id that will be incorporated into the algorithm log name</param> /// <param name="logs">The logs to save</param> /// <returns>The path to the logs</returns> public virtual string SaveLogs(string id, List<LogEntry> logs) { var filename = $"{id}-log.txt"; var path = GetResultsPath(filename); var logLines = logs.Select(x => x.Message); File.WriteAllLines(path, logLines); return path; } /// <summary> /// Save the results to disk /// </summary> /// <param name="name">The name of the results</param> /// <param name="result">The results to save</param> public virtual void SaveResults(string name, Result result) { File.WriteAllText(GetResultsPath(name), JsonConvert.SerializeObject(result, Formatting.Indented)); } /// <summary> /// Sets the current alpha runtime statistics /// </summary> /// <param name="statistics">The current alpha runtime statistics</param> public virtual void SetAlphaRuntimeStatistics(AlphaRuntimeStatistics statistics) { AlphaRuntimeStatistics = statistics; } /// <summary> /// Purge/clear any outstanding messages in message queue. /// </summary> protected void PurgeQueue() { Messages.Clear(); } /// <summary> /// Stops the update runner task /// </summary> protected void StopUpdateRunner() { _updateRunner.StopSafely(TimeSpan.FromMinutes(10)); _updateRunner = null; } /// <summary> /// Gets the algorithm net return /// </summary> protected decimal GetNetReturn() { //Some users have $0 in their brokerage account / starting cash of $0. Prevent divide by zero errors return StartingPortfolioValue > 0 ? (Algorithm.Portfolio.TotalPortfolioValue - StartingPortfolioValue) / StartingPortfolioValue : 0; } /// <summary> /// Save the snapshot of the total results to storage. /// </summary> /// <param name="packet">Packet to store.</param> protected abstract void StoreResult(Packet packet); /// <summary> /// Gets the current portfolio value /// </summary> /// <remarks>Useful so that live trading implementation can freeze the returned value if there is no user exchange open /// so we ignore extended market hours updates</remarks> protected virtual decimal GetPortfolioValue() { return Algorithm.Portfolio.TotalPortfolioValue; } /// <summary> /// Gets the current benchmark value /// </summary> /// <remarks>Useful so that live trading implementation can freeze the returned value if there is no user exchange open /// so we ignore extended market hours updates</remarks> /// <param name="time">Time to resolve benchmark value at</param> protected virtual decimal GetBenchmarkValue(DateTime time) { return Algorithm.Benchmark.Evaluate(time).SmartRounding(); } /// <summary> /// Samples portfolio equity, benchmark, and daily performance /// Called by scheduled event every night at midnight algorithm time /// </summary> /// <param name="time">Current UTC time in the AlgorithmManager loop</param> public virtual void Sample(DateTime time) { var currentPortfolioValue = GetPortfolioValue(); var portfolioPerformance = DailyPortfolioValue == 0 ? 0 : Math.Round((currentPortfolioValue - DailyPortfolioValue) * 100 / DailyPortfolioValue, 10); // Update our max portfolio value CumulativeMaxPortfolioValue = Math.Max(currentPortfolioValue, CumulativeMaxPortfolioValue); // Sample all our default charts SampleEquity(time, currentPortfolioValue); SampleBenchmark(time, GetBenchmarkValue(time)); SamplePerformance(time, portfolioPerformance); SampleDrawdown(time, currentPortfolioValue); SampleSalesVolume(time); SampleExposure(time, currentPortfolioValue); SampleCapacity(time); // Update daily portfolio value; works because we only call sample once a day DailyPortfolioValue = currentPortfolioValue; } /// <summary> /// Sample the current equity of the strategy directly with time-value pair. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Current equity value.</param> protected virtual void SampleEquity(DateTime time, decimal value) { Sample("Strategy Equity", "Equity", 0, SeriesType.Candle, time, value, AlgorithmCurrencySymbol); } /// <summary> /// Sample the current daily performance directly with a time-value pair. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Current daily performance value.</param> protected virtual void SamplePerformance(DateTime time, decimal value) { if (Log.DebuggingEnabled) { Log.Debug("BaseResultsHandler.SamplePerformance(): " + time.ToShortTimeString() + " >" + value); } Sample("Strategy Equity", "Daily Performance", 1, SeriesType.Bar, time, value, "%"); } /// <summary> /// Sample the current benchmark performance directly with a time-value pair. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Current benchmark value.</param> /// <seealso cref="IResultHandler.Sample"/> protected virtual void SampleBenchmark(DateTime time, decimal value) { Sample("Benchmark", "Benchmark", 0, SeriesType.Line, time, value); } /// <summary> /// Sample drawdown of equity of the strategy /// </summary> /// <param name="time">Time of the sample</param> /// <param name="currentPortfolioValue">Current equity value</param> protected virtual void SampleDrawdown(DateTime time, decimal currentPortfolioValue) { // This will throw otherwise, in this case just don't sample if (CumulativeMaxPortfolioValue != 0) { // Calculate our drawdown and sample it var drawdown = Statistics.Statistics.DrawdownPercent(currentPortfolioValue, CumulativeMaxPortfolioValue); Sample("Drawdown", "Equity Drawdown", 0, SeriesType.Line, time, drawdown, "%"); } } /// <summary> /// Sample assets sales volume /// </summary> /// <param name="time">Time of the sample</param> protected virtual void SampleSalesVolume(DateTime time) { // Sample top 30 holdings by sales volume foreach (var holding in Algorithm.Portfolio.Values.Where(y => y.TotalSaleVolume != 0) .OrderByDescending(x => x.TotalSaleVolume).Take(30)) { Sample("Assets Sales Volume", $"{holding.Symbol.Value}", 0, SeriesType.Treemap, time, holding.TotalSaleVolume, AlgorithmCurrencySymbol); } } /// <summary> /// Sample portfolio exposure long/short ratios by security type /// </summary> /// <param name="time">Time of the sample</param> /// <param name="currentPortfolioValue">Current value of the portfolio</param> protected virtual void SampleExposure(DateTime time, decimal currentPortfolioValue) { // Will throw in this case, just return without sampling if (currentPortfolioValue == 0) { return; } // Split up our holdings in one enumeration into long and shorts holding values // only process those that we hold stock in. var shortHoldings = new Dictionary<SecurityType, decimal>(); var longHoldings = new Dictionary<SecurityType, decimal>(); foreach (var holding in Algorithm.Portfolio.Values.Where(x => x.HoldStock)) { // Ensure we have a value for this security type in both our dictionaries if (!longHoldings.ContainsKey(holding.Symbol.SecurityType)) { longHoldings.Add(holding.Symbol.SecurityType, 0); shortHoldings.Add(holding.Symbol.SecurityType, 0); } // Long Position if (holding.HoldingsValue > 0) { longHoldings[holding.Symbol.SecurityType] += holding.HoldingsValue; } // Short Position else { shortHoldings[holding.Symbol.SecurityType] += holding.HoldingsValue; } } // Sample our long and short positions SampleExposureHelper(PositionSide.Long, time, currentPortfolioValue, longHoldings); SampleExposureHelper(PositionSide.Short, time, currentPortfolioValue, shortHoldings); } /// <summary> /// Helper method for SampleExposure, samples our holdings value to /// our exposure chart by their position side and security type /// </summary> /// <param name="type">Side to sample from portfolio</param> /// <param name="time">Time of the sample</param> /// <param name="currentPortfolioValue">Current value of the portfolio</param> /// <param name="holdings">Enumerable of holdings to sample</param> private void SampleExposureHelper(PositionSide type, DateTime time, decimal currentPortfolioValue, Dictionary<SecurityType, decimal> holdings) { foreach (var kvp in holdings) { var ratio = Math.Round(kvp.Value / currentPortfolioValue, 4); Sample("Exposure", $"{kvp.Key} - {type} Ratio", 0, SeriesType.Line, time, ratio, ""); } } /// <summary> /// Sample estimated strategy capacity /// </summary> /// <param name="time">Time of the sample</param> protected virtual void SampleCapacity(DateTime time) { // NOP; Used only by BacktestingResultHandler because he owns a CapacityEstimate } /// <summary> /// Add a sample to the chart specified by the chartName, and seriesName. /// </summary> /// <param name="chartName">String chart name to place the sample.</param> /// <param name="seriesName">Series name for the chart.</param> /// <param name="seriesIndex">Series chart index - which chart should this series belong</param> /// <param name="seriesType">Series type for the chart.</param> /// <param name="time">Time for the sample</param> /// <param name="value">Value for the chart sample.</param> /// <param name="unit">Unit for the chart axis</param> /// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks> protected abstract void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$"); /// <summary> /// Gets the algorithm runtime statistics /// </summary> protected Dictionary<string, string> GetAlgorithmRuntimeStatistics(Dictionary<string, string> summary, Dictionary<string, string> runtimeStatistics = null, CapacityEstimate capacityEstimate = null) { if (runtimeStatistics == null) { runtimeStatistics = new Dictionary<string, string>(); } if (summary.ContainsKey("Probabilistic Sharpe Ratio")) { runtimeStatistics["Probabilistic Sharpe Ratio"] = summary["Probabilistic Sharpe Ratio"]; } else { runtimeStatistics["Probabilistic Sharpe Ratio"] = "0%"; } var accountCurrencySymbol = Currencies.GetCurrencySymbol(Algorithm.AccountCurrency); runtimeStatistics["Unrealized"] = accountCurrencySymbol + Algorithm.Portfolio.TotalUnrealizedProfit.ToStringInvariant("N2"); runtimeStatistics["Fees"] = $"-{accountCurrencySymbol}{Algorithm.Portfolio.TotalFees.ToStringInvariant("N2")}"; runtimeStatistics["Net Profit"] = accountCurrencySymbol + Algorithm.Portfolio.TotalProfit.ToStringInvariant("N2"); runtimeStatistics["Return"] = GetNetReturn().ToStringInvariant("P"); runtimeStatistics["Equity"] = accountCurrencySymbol + Algorithm.Portfolio.TotalPortfolioValue.ToStringInvariant("N2"); runtimeStatistics["Holdings"] = accountCurrencySymbol + Algorithm.Portfolio.TotalHoldingsValue.ToStringInvariant("N2"); runtimeStatistics["Volume"] = accountCurrencySymbol + Algorithm.Portfolio.TotalSaleVolume.ToStringInvariant("N2"); if (capacityEstimate != null) { runtimeStatistics["Capacity"] = accountCurrencySymbol + capacityEstimate.Capacity.RoundToSignificantDigits(2).ToFinancialFigures(); } return runtimeStatistics; } /// <summary> /// Will generate the statistics results and update the provided runtime statistics /// </summary> protected StatisticsResults GenerateStatisticsResults(Dictionary<string, Chart> charts, SortedDictionary<DateTime, decimal> profitLoss = null, CapacityEstimate estimatedStrategyCapacity = null) { var statisticsResults = new StatisticsResults(); if (profitLoss == null) { profitLoss = new SortedDictionary<DateTime, decimal>(); } try { //Generates error when things don't exist (no charting logged, runtime errors in main algo execution) const string strategyEquityKey = "Strategy Equity"; const string equityKey = "Equity"; const string dailyPerformanceKey = "Daily Performance"; const string benchmarkKey = "Benchmark"; // make sure we've taken samples for these series before just blindly requesting them if (charts.ContainsKey(strategyEquityKey) && charts[strategyEquityKey].Series.ContainsKey(equityKey) && charts[strategyEquityKey].Series.ContainsKey(dailyPerformanceKey) && charts.ContainsKey(benchmarkKey) && charts[benchmarkKey].Series.ContainsKey(benchmarkKey)) { var equity = charts[strategyEquityKey].Series[equityKey].Values; var performance = charts[strategyEquityKey].Series[dailyPerformanceKey].Values; var totalTransactions = Algorithm.Transactions.GetOrders(x => x.Status.IsFill()).Count(); var benchmark = charts[benchmarkKey].Series[benchmarkKey].Values; var trades = Algorithm.TradeBuilder.ClosedTrades; statisticsResults = StatisticsBuilder.Generate(trades, profitLoss, equity, performance, benchmark, StartingPortfolioValue, Algorithm.Portfolio.TotalFees, totalTransactions, estimatedStrategyCapacity); } } catch (Exception err) { Log.Error(err, "BaseResultsHandler.GenerateStatisticsResults(): Error generating statistics packet"); } return statisticsResults; } /// <summary> /// Save an algorithm message to the log store. Uses a different timestamped method of adding messaging to interweve debug and logging messages. /// </summary> /// <param name="message">String message to store</param> protected abstract void AddToLogStore(string message); /// <summary> /// Processes algorithm logs. /// Logs of the same type are batched together one per line and are sent out /// </summary> protected void ProcessAlgorithmLogs(int? messageQueueLimit = null) { ProcessAlgorithmLogsImpl(Algorithm.DebugMessages, PacketType.Debug, messageQueueLimit); ProcessAlgorithmLogsImpl(Algorithm.ErrorMessages, PacketType.HandledError, messageQueueLimit); ProcessAlgorithmLogsImpl(Algorithm.LogMessages, PacketType.Log, messageQueueLimit); } private void ProcessAlgorithmLogsImpl(ConcurrentQueue<string> concurrentQueue, PacketType packetType, int? messageQueueLimit = null) { if (concurrentQueue.Count <= 0) { return; } var result = new List<string>(); var endTime = DateTime.UtcNow.AddMilliseconds(250).Ticks; string message; var currentMessageCount = -1; while (DateTime.UtcNow.Ticks < endTime && concurrentQueue.TryDequeue(out message)) { if (messageQueueLimit.HasValue) { if (currentMessageCount == -1) { // this is expensive, so let's get it once currentMessageCount = Messages.Count; } if (currentMessageCount > messageQueueLimit) { //if too many in the queue already skip the logging and drop the messages continue; } } AddToLogStore(message); result.Add(message); // increase count after we add currentMessageCount++; } if (result.Count > 0) { message = string.Join(Environment.NewLine, result); if (packetType == PacketType.Debug) { Messages.Enqueue(new DebugPacket(ProjectId, AlgorithmId, CompileId, message)); } else if (packetType == PacketType.Log) { Messages.Enqueue(new LogPacket(AlgorithmId, message)); } else if (packetType == PacketType.HandledError) { Messages.Enqueue(new HandledErrorPacket(AlgorithmId, message)); } } } } }
//#define LOG using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.IO; using System.Diagnostics; namespace ICSimulator { public abstract class Router { public Coord coord; public int subnet; public int ID { get { return coord.ID; } } public bool enable; public Link[] linkOut = new Link[4]; public Link[] linkIn = new Link[4]; public Link[] bypassLinkIn = new Link[Config.num_bypass]; public Link[] bypassLinkOut = new Link[Config.num_bypass]; public Link[] LLinkIn; public Link[] LLinkOut; public Link[] GLinkIn; public Link[] GLinkOut; public Router[] neigh = new Router[4]; public int neighbors; public int RouterType = -1; public int starveCount = 0; protected string routerName; protected Node m_n; // Keep track of the current router's average queue length over the // last INJ_RATE_WIN cycles public const int AVG_QLEN_WIN=1000; public float avg_qlen; public int[] qlen_win; public int qlen_ptr; public int qlen_count; public ulong m_lastInj; public ulong last_starve, starve_interval; public ulong m_inject = 0; public ulong Inject { get { return m_inject; } } // -------------------------------------------------------------------- public struct PreferredDirection { public int xDir; public int yDir; } public Router(Coord myCoord) { coord = myCoord; m_n = Simulator.network.nodes[ID]; routerName = "Router"; neighbors = 0; m_lastInj = 0; last_starve = 0; starve_interval = 0; qlen_win = new int[AVG_QLEN_WIN]; } public Router() { routerName = "Router"; qlen_win = new int[AVG_QLEN_WIN]; } public void setNode(Node n) { m_n = n; } /******************************************************** * PUBLIC API ********************************************************/ // called from Network public void doStep() { statsInput(); _doStep(); statsOutput(); } protected abstract void _doStep(); // called from Network public virtual void Scalable_doStep() {return;} public abstract bool canInjectFlit(Flit f); // called from Processor public abstract void InjectFlit(Flit f); // called from Processor public virtual void InjectFlitMultNet(int subnet, Flit f) {} // For multiple networks public virtual bool canInjectFlitMultNet(int subnet, Flit f) { return false; } public virtual int rank(Flit f1, Flit f2) { return 0; } // finally, subclasses should call myProcessor.ejectFlit() whenever a flit // arrives (or is part of a reassembled packet ready to be delivered, or whatever) // also, subclasses should call statsInput() before removing // inputs, statsOutput() after placing outputs, and // statsInjectFlit(f) if a flit is injected, // and statsEjectFlit(f) if a flit is ejected. // Buffered hierarchical ring: check downstream ring/ejection buffer and see if it's available public virtual bool creditAvailable(Flit f) {return false;} // Whether it wants to into the global ring or loca ring public virtual bool productive(Flit f, int level) {return false;} // for flush/retry mechanisms: clear all router state. public virtual void flush() { } // only work for 4x4 network public static bool [] starved = new bool [Config.N + 16]; public static bool [] now_starved = new bool [Config.N + 16]; public static Queue<bool[]> starveDelay = new Queue<bool[]>(); public static Queue<bool[]> throttleDelay = new Queue<bool[]>(); public static bool [] throttle = new bool [Config.N]; public static int n = 0; public static int working = -1; public static void livelockFreedom() { bool [] starvetmp = new bool [Config.N + 16]; bool [] throttletmp = new bool [Config.N]; for (int i = 0; i < Config.N + 16; i++) starvetmp[i] = starved[i]; starveDelay.Enqueue(starvetmp); if (starveDelay.Count > Config.starveDelay) now_starved = starveDelay.Dequeue(); // else // Console.WriteLine("starveDelay.Count:{0}", starveDelay.Count); // Console.WriteLine("n = {0}", n); if (now_starved[n]) { /* Console.WriteLine("cycle: {0}", Simulator.CurrentRound); for (int i = 0; i < 24; i++) Console.WriteLine("starved[{0}] = {1}\tnow_starved[{2}] = {3}", i, starved[i], i, now_starved[i]); Console.WriteLine("\n"); for (int j = 0; j < starveDelay.Count; j++) { for (int i = 0; i < 24; i++) Console.WriteLine("now_starved[{0}] = {1}", i, now_starved[i]); now_starved = starveDelay.Dequeue(); } */ // Console.ReadKey(true); if (throttletmp[(n+1) % Config.N] == false) Simulator.stats.starveTriggered.Add(1); Simulator.stats.allNodeThrottled.Add(1); for (int i = 0; i < Config.N; i++) if (i != n) throttletmp[i] = true; working = n; } else working = -1; if (working == -1) { for (int i = 0; i < Config.N; i++) throttletmp[i] = false; n = (n == Config.N + 8 - 1) ? 0 : n + 1; } throttleDelay.Enqueue(throttletmp); if (throttleDelay.Count > Config.starveDelay) throttle = throttleDelay.Dequeue(); // for (int i = 0; i < Config.N; i++) // Console.WriteLine("delay {0}. throttle[{1}] : {2}", Config.starveDelay, i, throttle[i]); // Console.WriteLine("\n"); // Console.ReadKey(true); } /******************************************************** * ROUTING HELPERS ********************************************************/ protected PreferredDirection determineDirection(Flit f) { return determineDirection(f, new Coord(0, 0)); } protected bool [] determineDirection (Flit f, Coord current, int[,] mcMask) { bool [] preferredDirVector = new bool [5]; for (int i = 0; i < 5; i++) preferredDirVector [i] = false; List <Coord> destList; int nodeID; destList = f.destList; foreach (Coord dest in destList) { nodeID = dest.ID; // U-Turn is disabled to avoid livelock if (mcMask [Simulator.DIR_UP, nodeID] == 1 && preferredDirVector [Simulator.DIR_UP] != true && f.inDir != Simulator.DIR_UP) preferredDirVector [Simulator.DIR_UP] = true; if (mcMask [Simulator.DIR_RIGHT, nodeID] == 1 && preferredDirVector [Simulator.DIR_RIGHT] != true && f.inDir != Simulator.DIR_RIGHT) preferredDirVector [Simulator.DIR_RIGHT] = true; if (mcMask [Simulator.DIR_DOWN, nodeID] == 1 && preferredDirVector [Simulator.DIR_DOWN] != true && f.inDir != Simulator.DIR_DOWN) preferredDirVector [Simulator.DIR_DOWN] = true; if (mcMask [Simulator.DIR_LEFT, nodeID] == 1 && preferredDirVector [Simulator.DIR_LEFT] != true && f.inDir != Simulator.DIR_LEFT) preferredDirVector [Simulator.DIR_LEFT] = true; if (nodeID == current.ID) preferredDirVector [Simulator.DIR_LOCAL] = true; //else // Debug.Assert (false, "ERROR: Direction doesn't exist\n"); } return preferredDirVector; } protected PreferredDirection determineDirection(Flit f, Coord current) { PreferredDirection pd; pd.xDir = Simulator.DIR_NONE; pd.yDir = Simulator.DIR_NONE; if (f.state == Flit.State.Placeholder) return pd; return determineDirection(f.dest); } protected PreferredDirection determineDirection(Coord c) { PreferredDirection pd; pd.xDir = Simulator.DIR_NONE; pd.yDir = Simulator.DIR_NONE; if(Config.torus) { int x_sdistance = Math.Abs(c.x - coord.x); int x_wdistance = Config.network_nrX - Math.Abs(c.x - coord.x); int y_sdistance = Math.Abs(c.y - coord.y); int y_wdistance = Config.network_nrY - Math.Abs(c.y - coord.y); bool x_dright, y_ddown; x_dright = coord.x < c.x; y_ddown = c.y < coord.y; if(c.x == coord.x) pd.xDir = Simulator.DIR_NONE; else if(x_sdistance < x_wdistance) pd.xDir = (x_dright) ? Simulator.DIR_RIGHT : Simulator.DIR_LEFT; else pd.xDir = (x_dright) ? Simulator.DIR_LEFT : Simulator.DIR_RIGHT; if(c.y == coord.y) pd.yDir = Simulator.DIR_NONE; else if(y_sdistance < y_wdistance) pd.yDir = (y_ddown) ? Simulator.DIR_DOWN : Simulator.DIR_UP; else pd.yDir = (y_ddown) ? Simulator.DIR_UP : Simulator.DIR_DOWN; } else { if (c.x > coord.x) pd.xDir = Simulator.DIR_RIGHT; else if (c.x < coord.x) pd.xDir = Simulator.DIR_LEFT; else pd.xDir = Simulator.DIR_NONE; if (c.y > coord.y) pd.yDir = Simulator.DIR_UP; else if (c.y < coord.y) pd.yDir = Simulator.DIR_DOWN; else pd.yDir = Simulator.DIR_NONE; } if (Config.dor_only && pd.xDir != Simulator.DIR_NONE) pd.yDir = Simulator.DIR_NONE; return pd; } // returns true if the direction is good for this packet. protected bool isDirectionProductive(Coord dest, int direction) { bool answer = false; switch (direction) { case Simulator.DIR_UP: answer = (dest.y > coord.y); break; case Simulator.DIR_RIGHT: answer = (dest.x > coord.x); break; case Simulator.DIR_LEFT: answer = (dest.x < coord.x); break; case Simulator.DIR_DOWN: answer = (dest.y < coord.y); break; default: throw new Exception("This function shouldn't be called in this case!"); } return answer; } protected int dimension_order_route(Flit f) { if (f.packet.dest.x < coord.x) return Simulator.DIR_LEFT; else if (f.packet.dest.x > coord.x) return Simulator.DIR_RIGHT; else if (f.packet.dest.y < coord.y) return Simulator.DIR_DOWN; else if (f.packet.dest.y > coord.y) return Simulator.DIR_UP; else //if the destination's coordinates are equal to the router's coordinates return Simulator.DIR_UP; } /******************************************************** * STATISTICS ********************************************************/ protected int incomingFlits; private void statsInput() { //int goldenCount = 0; incomingFlits = 0; if (Config.topology == Topology.Mesh) for (int i = 0; i < 4; i++) if (linkIn[i] != null && linkIn[i].Out != null) Simulator.stats.flitsToRouter.Add(1); if (Config.topology == Topology.Mesh_Multi) { for (int i = 0; i < 4; i++) if (linkIn[i] != null && linkIn[i].Out != null) Simulator.stats.flitsToRouter.Add(1); for (int i = 0; i < Config.num_bypass; i++) if (bypassLinkIn[i] != null && bypassLinkIn[i].Out != null) Simulator.stats.flitsToRouter.Add(1); } if (Config.topology == Topology.HR_8drop || Config.topology == Topology.MeshOfRings) { if (this is Router_Node) for (int i = 0; i < 2; i++) if (linkIn[i].Out != null) Simulator.stats.flitsToHRnode.Add(1); if (this is Router_Bridge) { if (RouterType == 1) { for (int i = 0; i < 2; i++) if (LLinkIn[i].Out != null) Simulator.stats.flitsToHRbridge.Add(1); for (int i = 0; i < 4; i++) if (GLinkIn[i].Out != null) Simulator.stats.flitsToHRbridge.Add(1); } else if (RouterType == 2) { for (int i = 0; i < 4; i++) if (LLinkIn[i].Out != null) Simulator.stats.flitsToHRbridge.Add(1); for (int i = 0; i < 8; i++) if (GLinkIn[i].Out != null) Simulator.stats.flitsToHRbridge.Add(1); } else throw new Exception("The RouterType should only be 1 or 2"); } } } private void statsOutput() { int deflected = 0; int unproductive = 0; int traversals = 0; int bypassed = 0; int links = (Config.RingClustered || Config.ScalableRingClustered)? 2:4; for (int i = 0; i < links; i++) { if (linkOut[i] != null && linkOut[i].In != null) { if (linkOut[i].In.Deflected) { // deflected! (may still be productive, depending on deflection definition/DOR used) deflected++; linkOut[i].In.nrOfDeflections++; Simulator.stats.deflect_flit_byloc[ID].Add(); if (linkOut[i].In.packet != null) { Simulator.stats.deflect_flit_bysrc[linkOut[i].In.packet.src.ID].Add(); //Simulator.stats.deflect_flit_byreq[linkOut[i].In.packet.requesterID].Add(); } } if (!isDirectionProductive(linkOut[i].In.dest, i)) { //unproductive! unproductive++; Simulator.stats.unprod_flit_byloc[ID].Add(); if (linkOut[i].In.packet != null) Simulator.stats.unprod_flit_bysrc[linkOut[i].In.packet.src.ID].Add(); } traversals++; //linkOut[i].In.deflectTest(); } } for (int i = 0; i < Config.num_bypass; i++) { if (bypassLinkOut[i] != null && bypassLinkOut[i].In != null) { bypassed++; traversals++; } } Simulator.stats.bypass_flit.Add(bypassed); Simulator.stats.deflect_flit.Add(deflected); Simulator.stats.deflect_flit_byinc[incomingFlits].Add(deflected); Simulator.stats.unprod_flit.Add(unproductive); Simulator.stats.unprod_flit_byinc[incomingFlits].Add(unproductive); Simulator.stats.flit_traversals.Add(traversals); int qlen = m_n.RequestQueueLen; qlen_count -= qlen_win[qlen_ptr]; qlen_count += qlen; // Compute the average queue length qlen_win[qlen_ptr] = qlen; if(++qlen_ptr >= AVG_QLEN_WIN) qlen_ptr=0; avg_qlen = (float)qlen_count / (float)AVG_QLEN_WIN; } protected void statsInjectFlit(Flit f) { //if (f.packet.src.ID == 3) Console.WriteLine("inject flit: packet {0}, seq {1}", // f.packet.ID, f.flitNr); Simulator.stats.inject_flit.Add(); if (f.isHeadFlit) Simulator.stats.inject_flit_head.Add(); if (f.packet != null) { Simulator.stats.inject_flit_bysrc[f.packet.src.ID].Add(); //Simulator.stats.inject_flit_srcdest[f.packet.src.ID, f.packet.dest.ID].Add(); } if (f.packet != null && f.packet.injectionTime == ulong.MaxValue) f.packet.injectionTime = Simulator.CurrentRound; f.injectionTime = Simulator.CurrentRound; ulong hoq = Simulator.CurrentRound - m_lastInj; // hoq record the gap between each injection. m_lastInj = Simulator.CurrentRound; Simulator.stats.hoq_latency.Add(hoq); Simulator.stats.hoq_latency_bysrc[coord.ID].Add(hoq); m_inject++; } protected void statsEjectFlit(Flit f) { // per-flit latency stats //Console.Write("Packet {0}.{1} Traverse: ", f.packet.ID, f.flitNr); //foreach (int i in f.roadMap) // Console.Write (" {0}", i); //Console.WriteLine (); ulong net_latency; ulong total_latency; ulong inj_latency; net_latency = Simulator.CurrentRound - f.injectionTime; total_latency = Simulator.CurrentRound - f.creationTime; inj_latency = total_latency - net_latency; Simulator.stats.flit_intf.Add(f.intfCycle); Simulator.stats.flit_inj_latency.Add(inj_latency); Simulator.stats.flit_net_latency.Add(net_latency); Simulator.stats.flit_total_latency.Add(total_latency); Simulator.stats.ejectTrial.Add(f.ejectTrial); Simulator.stats.minNetLatency.Add(f.firstEjectTrial - f.injectionTime); if (f.ejectTrial > 1) { Simulator.stats.destDeflectedNetLatency.Add(net_latency); Simulator.stats.destDeflectedMinLatency.Add(f.firstEjectTrial - f.injectionTime); Simulator.stats.multiEjectTrialFlits.Add(); } else if (f.ejectTrial == 1) Simulator.stats.singleEjectTrialFlits.Add(); if (Config.N == 16) { if (f.packet.dest.ID / 4 == f.packet.src.ID / 4) { Simulator.stats.flitLocal.Add(1); Simulator.stats.netLatency_local.Add(net_latency); } else if (Math.Abs(f.packet.dest.ID / 4 - f.packet.src.ID / 4) != 2) // one hop { Simulator.stats.flit1hop.Add(1); Simulator.stats.netLatency_1hop.Add(net_latency); Simulator.stats.timeInBuffer1hop.Add(f.timeSpentInBuffer); Simulator.stats.timeInTheDestRing.Add(f.timeInTheDestRing); Simulator.stats.timeInTheSourceRing.Add(f.timeInTheSourceRing); Simulator.stats.timeInGR1hop.Add(f.timeInGR); } else // 2 hop { Simulator.stats.flit2hop.Add(1); Simulator.stats.netLatency_2hop.Add(net_latency); Simulator.stats.timeInBuffer2hop.Add(f.timeSpentInBuffer); Simulator.stats.timeInTheDestRing.Add(f.timeInTheDestRing); Simulator.stats.timeInTheTransitionRing.Add(f.timeInTheTransitionRing); Simulator.stats.timeInGR2hop.Add(f.timeInGR); Simulator.stats.timeInTheSourceRing.Add(f.timeInTheSourceRing); } Simulator.stats.timeWaitToInject.Add(f.timeWaitToInject); } if (Config.N == 64) { if (f.packet.dest.ID / 4 == f.packet.src.ID / 4) Simulator.stats.flitLocal.Add(1); else if (f.packet.dest.ID /16 == f.packet.src.ID / 16) Simulator.stats.flitL1Global.Add(1); } Simulator.stats.eject_flit.Add(f.ackCount); Simulator.stats.eject_flit_bydest[f.packet.dest.ID].Add(f.ackCount); int minpath = Math.Abs(f.packet.dest.x - f.packet.src.x) + Math.Abs(f.packet.dest.y - f.packet.src.y); Simulator.stats.minpath.Add(minpath); Simulator.stats.minpath_bysrc[f.packet.src.ID].Add(minpath); //f.dumpDeflections(); Simulator.stats.deflect_perdist[f.distance].Add(f.nrOfDeflections); //if(f.nrOfDeflections!=0) // Simulator.stats.deflect_perflit_byreq[f.packet.requesterID].Add(f.nrOfDeflections); } public virtual void statsEjectPacket(Packet p) { ScoreBoard.UnregPacket (ID, p.ID); // TODO: merged packet may cause issue. if (!p.mc && !p.gather) { if (p.nrOfFlits == Config.router.addrPacketSize) Simulator.stats.ctrl_pkt.Add (); else if (p.nrOfFlits == Config.router.dataPacketSize) Simulator.stats.data_pkt.Add (); else throw new Exception ("packet size is undefined, yet received!"); } else if (p.gather) { Simulator.stats.ctrl_pkt.Add (); } else { if (p.nrOfFlits == 2*Config.router.addrPacketSize) Simulator.stats.ctrl_pkt.Add (); else if (p.nrOfFlits == 2*Config.router.dataPacketSize) Simulator.stats.data_pkt.Add (); else throw new Exception ("packet size is undefined, yet received!"); } ulong net_latency; ulong total_latency; if (p.mc) { if (p.creationTimeMC [ID] == p.creationTime) { // if true, this is a master copy, not replciated. net_latency = Simulator.CurrentRound - p.injectionTime; total_latency = Simulator.CurrentRound - p.creationTime; } else { net_latency = Simulator.CurrentRound - p.creationTimeMC[ID]; total_latency = net_latency; // for replicated packet, injection_latency = 0; } } else { net_latency = Simulator.CurrentRound - p.injectionTime; total_latency = Simulator.CurrentRound - p.creationTime; } bool stop = false; if (total_latency > 120) stop = true; Simulator.stats.packet_intf.Add(p.intfCycle); Simulator.stats.net_latency.Add(net_latency); Simulator.stats.total_latency.Add(total_latency); Simulator.stats.net_latency_bysrc[p.src.ID].Add(net_latency); Simulator.stats.net_latency_bydest[p.dest.ID].Add(net_latency); //Simulator.stats.net_latency_srcdest[p.src.ID, p.dest.ID].Add(net_latency); Simulator.stats.total_latency_bysrc[p.src.ID].Add(total_latency); Simulator.stats.total_latency_bydest[p.dest.ID].Add(total_latency); //Simulator.stats.total_latency_srcdest[p.src.ID, p.dest.ID].Add(total_latency); } public override string ToString() { return routerName + " (" + coord.x + "," + coord.y + ")"; } public string getRouterName() { return routerName; } public Router neighbor(int dir) { int x, y; switch (dir) { case Simulator.DIR_UP: x = coord.x; y = coord.y + 1; break; case Simulator.DIR_DOWN: x = coord.x; y = coord.y - 1; break; case Simulator.DIR_RIGHT: x = coord.x + 1; y = coord.y; break; case Simulator.DIR_LEFT: x = coord.x - 1; y = coord.y; break; default: return null; } // mesh, not torus: detect edge if (x < 0 || x >= Config.network_nrX || y < 0 || y >= Config.network_nrY) return null; return Simulator.network.routers[Coord.getIDfromXY(x, y)]; } public void close() { } public virtual void visitFlits(Flit.Visitor fv) { } public void statsStarve(Flit f) { Simulator.stats.starve_flit.Add(); Simulator.stats.starve_flit_bysrc[f.packet.src.ID].Add(); if (last_starve == Simulator.CurrentRound - 1) { starve_interval++; } else { Simulator.stats.starve_interval_bysrc[f.packet.src.ID].Add(starve_interval); starve_interval = 0; } last_starve = Simulator.CurrentRound; } public int linkUtil() { int count = 0; for (int i = 0; i < 4; i++) if (linkIn[i] != null && linkIn[i].Out != null) count++; return count; } public double linkUtilNeighbors() { int tot = 0, used = 0; for (int dir = 0; dir < 4; dir++) { Router n = neighbor(dir); if (n == null) continue; tot += n.neighbors; used += n.linkUtil(); } return (double)used / tot; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // This RegexFCD class is internal to the Regex package. // It builds a bunch of FC information (RegexFC) about // the regex for optimization purposes. // Implementation notes: // // This step is as simple as walking the tree and emitting // sequences of codes. using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexFCD { private int[] _intStack; private int _intDepth; private RegexFC[] _fcStack; private int _fcDepth; private bool _skipAllChildren; // don't process any more children at the current level private bool _skipchild; // don't process the current child. private bool _failed = false; private const int BeforeChild = 64; private const int AfterChild = 128; // where the regex can be pegged internal const int Beginning = 0x0001; internal const int Bol = 0x0002; internal const int Start = 0x0004; internal const int Eol = 0x0008; internal const int EndZ = 0x0010; internal const int End = 0x0020; internal const int Boundary = 0x0040; internal const int ECMABoundary = 0x0080; /* * This is the one of the only two functions that should be called from outside. * It takes a RegexTree and computes the set of chars that can start it. */ internal static RegexPrefix FirstChars(RegexTree t) { RegexFCD s = new RegexFCD(); RegexFC fc = s.RegexFCFromRegexTree(t); if (fc == null || fc._nullable) return null; CultureInfo culture = ((t._options & RegexOptions.CultureInvariant) != 0) ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; return new RegexPrefix(fc.GetFirstChars(culture), fc.IsCaseInsensitive()); } /* * This is a related computation: it takes a RegexTree and computes the * leading substring if it see one. It's quite trivial and gives up easily. */ internal static RegexPrefix Prefix(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; curNode = tree._root; for (; ;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Oneloop: case RegexNode.Onelazy: if (curNode._m > 0) { string pref = String.Empty.PadRight(curNode._m, curNode._ch); return new RegexPrefix(pref, 0 != (curNode._options & RegexOptions.IgnoreCase)); } else return RegexPrefix.Empty; case RegexNode.One: return new RegexPrefix(curNode._ch.ToString(), 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Multi: return new RegexPrefix(curNode._str, 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return RegexPrefix.Empty; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return RegexPrefix.Empty; curNode = concatNode.Child(nextChild++); } } /* * Yet another related computation: it takes a RegexTree and computes the * leading anchors that it encounters. */ internal static int Anchors(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; int result = 0; curNode = tree._root; for (; ;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: return result | AnchorFromType(curNode._type); case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return result; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return result; curNode = concatNode.Child(nextChild++); } } /* * Convert anchor type to anchor bit. */ private static int AnchorFromType(int type) { switch (type) { case RegexNode.Bol: return Bol; case RegexNode.Eol: return Eol; case RegexNode.Boundary: return Boundary; case RegexNode.ECMABoundary: return ECMABoundary; case RegexNode.Beginning: return Beginning; case RegexNode.Start: return Start; case RegexNode.EndZ: return EndZ; case RegexNode.End: return End; default: return 0; } } #if DEBUG internal static String AnchorDescription(int anchors) { StringBuilder sb = new StringBuilder(); if (0 != (anchors & Beginning)) sb.Append(", Beginning"); if (0 != (anchors & Start)) sb.Append(", Start"); if (0 != (anchors & Bol)) sb.Append(", Bol"); if (0 != (anchors & Boundary)) sb.Append(", Boundary"); if (0 != (anchors & ECMABoundary)) sb.Append(", ECMABoundary"); if (0 != (anchors & Eol)) sb.Append(", Eol"); if (0 != (anchors & End)) sb.Append(", End"); if (0 != (anchors & EndZ)) sb.Append(", EndZ"); if (sb.Length >= 2) return (sb.ToString(2, sb.Length - 2)); return "None"; } #endif /* * private constructor; can't be created outside */ private RegexFCD() { _fcStack = new RegexFC[32]; _intStack = new int[32]; } /* * To avoid recursion, we use a simple integer stack. * This is the push. */ private void PushInt(int I) { if (_intDepth >= _intStack.Length) { int[] expanded = new int[_intDepth * 2]; System.Array.Copy(_intStack, 0, expanded, 0, _intDepth); _intStack = expanded; } _intStack[_intDepth++] = I; } /* * True if the stack is empty. */ private bool IntIsEmpty() { return _intDepth == 0; } /* * This is the pop. */ private int PopInt() { return _intStack[--_intDepth]; } /* * We also use a stack of RegexFC objects. * This is the push. */ private void PushFC(RegexFC fc) { if (_fcDepth >= _fcStack.Length) { RegexFC[] expanded = new RegexFC[_fcDepth * 2]; System.Array.Copy(_fcStack, 0, expanded, 0, _fcDepth); _fcStack = expanded; } _fcStack[_fcDepth++] = fc; } /* * True if the stack is empty. */ private bool FCIsEmpty() { return _fcDepth == 0; } /* * This is the pop. */ private RegexFC PopFC() { return _fcStack[--_fcDepth]; } /* * This is the top. */ private RegexFC TopFC() { return _fcStack[_fcDepth - 1]; } /* * The main FC computation. It does a shortcutted depth-first walk * through the tree and calls CalculateFC to emits code before * and after each child of an interior node, and at each leaf. */ private RegexFC RegexFCFromRegexTree(RegexTree tree) { RegexNode curNode; int curChild; curNode = tree._root; curChild = 0; for (; ;) { if (curNode._children == null) { // This is a leaf node CalculateFC(curNode._type, curNode, 0); } else if (curChild < curNode._children.Count && !_skipAllChildren) { // This is an interior node, and we have more children to analyze CalculateFC(curNode._type | BeforeChild, curNode, curChild); if (!_skipchild) { curNode = (RegexNode)curNode._children[curChild]; // this stack is how we get a depth first walk of the tree. PushInt(curChild); curChild = 0; } else { curChild++; _skipchild = false; } continue; } // This is an interior node where we've finished analyzing all the children, or // the end of a leaf node. _skipAllChildren = false; if (IntIsEmpty()) break; curChild = PopInt(); curNode = curNode._next; CalculateFC(curNode._type | AfterChild, curNode, curChild); if (_failed) return null; curChild++; } if (FCIsEmpty()) return null; return PopFC(); } /* * Called in Beforechild to prevent further processing of the current child */ private void SkipChild() { _skipchild = true; } /* * FC computation and shortcut cases for each node type */ private void CalculateFC(int NodeType, RegexNode node, int CurIndex) { bool ci = false; bool rtl = false; if (NodeType <= RegexNode.Ref) { if ((node._options & RegexOptions.IgnoreCase) != 0) ci = true; if ((node._options & RegexOptions.RightToLeft) != 0) rtl = true; } switch (NodeType) { case RegexNode.Concatenate | BeforeChild: case RegexNode.Alternate | BeforeChild: case RegexNode.Testref | BeforeChild: case RegexNode.Loop | BeforeChild: case RegexNode.Lazyloop | BeforeChild: break; case RegexNode.Testgroup | BeforeChild: if (CurIndex == 0) SkipChild(); break; case RegexNode.Empty: PushFC(new RegexFC(true)); break; case RegexNode.Concatenate | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, true); } if (!TopFC()._nullable) _skipAllChildren = true; break; case RegexNode.Testgroup | AfterChild: if (CurIndex > 1) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Alternate | AfterChild: case RegexNode.Testref | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Loop | AfterChild: case RegexNode.Lazyloop | AfterChild: if (node._m == 0) TopFC()._nullable = true; break; case RegexNode.Group | BeforeChild: case RegexNode.Group | AfterChild: case RegexNode.Capture | BeforeChild: case RegexNode.Capture | AfterChild: case RegexNode.Greedy | BeforeChild: case RegexNode.Greedy | AfterChild: break; case RegexNode.Require | BeforeChild: case RegexNode.Prevent | BeforeChild: SkipChild(); PushFC(new RegexFC(true)); break; case RegexNode.Require | AfterChild: case RegexNode.Prevent | AfterChild: break; case RegexNode.One: case RegexNode.Notone: PushFC(new RegexFC(node._ch, NodeType == RegexNode.Notone, false, ci)); break; case RegexNode.Oneloop: case RegexNode.Onelazy: PushFC(new RegexFC(node._ch, false, node._m == 0, ci)); break; case RegexNode.Notoneloop: case RegexNode.Notonelazy: PushFC(new RegexFC(node._ch, true, node._m == 0, ci)); break; case RegexNode.Multi: if (node._str.Length == 0) PushFC(new RegexFC(true)); else if (!rtl) PushFC(new RegexFC(node._str[0], false, false, ci)); else PushFC(new RegexFC(node._str[node._str.Length - 1], false, false, ci)); break; case RegexNode.Set: PushFC(new RegexFC(node._str, false, ci)); break; case RegexNode.Setloop: case RegexNode.Setlazy: PushFC(new RegexFC(node._str, node._m == 0, ci)); break; case RegexNode.Ref: PushFC(new RegexFC(RegexCharClass.AnyClass, true, false)); break; case RegexNode.Nothing: case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.Nonboundary: case RegexNode.ECMABoundary: case RegexNode.NonECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: PushFC(new RegexFC(true)); break; default: throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, NodeType.ToString(CultureInfo.CurrentCulture))); } } } internal sealed class RegexFC { internal RegexCharClass _cc; internal bool _nullable; internal bool _caseInsensitive; internal RegexFC(bool nullable) { _cc = new RegexCharClass(); _nullable = nullable; } internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive) { _cc = new RegexCharClass(); if (not) { if (ch > 0) _cc.AddRange('\0', (char)(ch - 1)); if (ch < 0xFFFF) _cc.AddRange((char)(ch + 1), '\uFFFF'); } else { _cc.AddRange(ch, ch); } _caseInsensitive = caseInsensitive; _nullable = nullable; } internal RegexFC(String charClass, bool nullable, bool caseInsensitive) { _cc = RegexCharClass.Parse(charClass); _nullable = nullable; _caseInsensitive = caseInsensitive; } internal bool AddFC(RegexFC fc, bool concatenate) { if (!_cc.CanMerge || !fc._cc.CanMerge) { return false; } if (concatenate) { if (!_nullable) return true; if (!fc._nullable) _nullable = false; } else { if (fc._nullable) _nullable = true; } _caseInsensitive |= fc._caseInsensitive; _cc.AddCharClass(fc._cc); return true; } internal String GetFirstChars(CultureInfo culture) { if (_caseInsensitive) _cc.AddLowercase(culture); return _cc.ToStringClass(); } internal bool IsCaseInsensitive() { return _caseInsensitive; } } internal sealed class RegexPrefix { internal String _prefix; internal bool _caseInsensitive; internal static RegexPrefix _empty = new RegexPrefix(String.Empty, false); internal RegexPrefix(String prefix, bool ci) { _prefix = prefix; _caseInsensitive = ci; } internal String Prefix { get { return _prefix; } } internal bool CaseInsensitive { get { return _caseInsensitive; } } internal static RegexPrefix Empty { get { return _empty; } } } }
using System; using System.Windows.Forms; using System.Diagnostics; namespace Kakuro { public class Board { public Board(int nRows, int nCols) { m_nRows = nRows; m_nCols = nCols; m_board = new Element[nRows, nCols]; } public Element this[int row, int col] { get { return m_board[row, col]; } set { m_board[row, col] = value; } } private IStatusUpdater m_updater; private System.DateTime m_dtNextUpdate; private int m_nUpdateSeconds; private ulong m_nIterations; public bool Solve(IStatusUpdater updater, int nSeconds) { m_updater = updater; m_dtNextUpdate = System.DateTime.Now.AddSeconds(nSeconds); m_nUpdateSeconds = nSeconds; m_nIterations = 0; //return SolveAt(0, 0); bool bSolved = SolveIterate(); updater.UpdateStatus(); return bSolved; } private bool SolveIterate() { m_nIterations++; if (System.DateTime.Now > m_dtNextUpdate) { m_updater.UpdateStatus(); m_dtNextUpdate = System.DateTime.Now.AddSeconds(m_nUpdateSeconds); } // find out what is the best element to work on int nRow, nCol, nOpts, baLegals; int nBestRow = -1, nBestCol = -1, nBestOpts = 100, baBestLegals = 0; for (nRow = 0; nRow < m_nRows; nRow++) { nOpts = 100; for (nCol = 0; nCol < m_nCols; nCol++) { if (this[nRow, nCol].Value != Element.Unknown) continue; baLegals = FindOptions(nRow, nCol, out nOpts); if (nOpts < nBestOpts) { nBestRow = nRow; nBestCol = nCol; nBestOpts = nOpts; baBestLegals = baLegals; } if (nOpts == 0) return false; // found contradiction if (nOpts == 1) break; } if (nOpts == 1) break; } // ending condition if (nBestOpts == 100) { // we're done return true; } // work on the best element for (int curValue = 9; curValue >= 1; curValue--) { if ((baBestLegals & (1 << curValue)) == 0) continue; // illegal option this[nBestRow, nBestCol].Value = curValue; // recurse if (SolveIterate()) return true; } // couldn't find any solution this[nBestRow, nBestCol].Value = Element.Unknown; return false; } /// <summary> /// Find and return all legal options for the specified element. /// We assume we are given a value-type element. /// </summary> /// <param name="nRow">Row of specified element</param> /// <param name="nCol">Column of specified element</param> /// <param name="nOpts">(out) number of legal options for the element</param> /// <returns>A bit array which contains the legal options for the specified element</returns> private int FindOptions(int nRow, int nCol, out int nOpts) { Debug.Assert(this[nRow, nCol].Value == Element.Unknown); // first, find information about the current column and row. int nColStart, nColEnd, nColSum; //NB: nColStart is the ROW in which the current column starts! int nRowStart, nRowEnd, nRowSum; //NB: nRowStart is the COLUMN in which the current row starts! // find the row in which the current column starts for (nColStart = nRow; this[nColStart - 1, nCol].HasValue; nColStart--) ; // find the row in which the current column ends for (nColEnd = nRow; nColEnd < m_nRows - 1 && this[nColEnd + 1, nCol].HasValue; nColEnd++) ; // find the column in which the current row starts for (nRowStart = nCol; this[nRow, nRowStart - 1].HasValue; nRowStart--) ; // find the column in which the current row ends for (nRowEnd = nCol; nRowEnd < m_nCols - 1 && this[nRow, nRowEnd + 1].HasValue; nRowEnd++) ; // find the expected sums for the current row and column nColSum = this[nColStart - 1, nCol].SumDown; nRowSum = this[nRow, nRowStart - 1].SumRight; Debug.Assert(nColSum != Element.Unused); Debug.Assert(nRowSum != Element.Unused); // find illegal values for the current element. // these are stored in the bitarray illegalValues: // value i is illegal iff bit i is 1 int illegalValues = 0; int illegalColValues = 0; int illegalRowValues = 0; // stage 1: must not appear in the current column // (we also use this pass to calculate the column sum so far, and the number // of unknown elements in the column) int colsum = 0; int nColElemsUnknown = 0; for (int i = nColStart; i <= nColEnd; i++) { int valHere = this[i, nCol].Value; if (valHere != Element.Unknown) { illegalColValues |= (1 << valHere); colsum += valHere; } else { nColElemsUnknown++; } } nColElemsUnknown--; // subtract one for the current element, which is always unknown illegalValues |= illegalColValues; // stage 1a: calculate minimum and maximum possible sum of the unknown values int mincolsum, maxcolsum; FindMinMaxSum(illegalColValues, nColElemsUnknown, out mincolsum, out maxcolsum); // stage 2: must not appear in the current row // (we also use this pass to calculate the row sum so far, and the number of // unknown elements in the current row) int rowsum = 0; int nRowElemsUnknown = 0; for (int i = nRowStart; i <= nRowEnd; i++) { int valHere = this[nRow, i].Value; if (valHere != Element.Unknown) { illegalRowValues |= (1 << valHere); rowsum += valHere; } else { nRowElemsUnknown++; } } nRowElemsUnknown--; // subtract one for the current element, which is always unknown illegalValues |= illegalRowValues; // stage 2a: calculate minimum and maximum possible sum of the unknown values int minrowsum, maxrowsum; FindMinMaxSum(illegalRowValues, nRowElemsUnknown, out minrowsum, out maxrowsum); // count the number of legal options nOpts = 0; int retval = 0; for (int curValue = 9; curValue >= 1; curValue--) { // see if the this value is legal if ((illegalValues & (1 << curValue)) == 0) { // digit doesn't yet appear if (colsum + curValue + mincolsum <= nColSum && colsum + curValue + maxcolsum >= nColSum) { // we're still in possible range for the expected column sum if (rowsum + curValue + minrowsum <= nRowSum && rowsum + curValue + maxrowsum >= nRowSum) { // we're still in possible range for the expected row sum // this is a legal value nOpts++; retval |= (1 << curValue); } } } } return retval; } /// <summary> /// Find the minimum and maximum possible sums of nElements different positive /// integers in the range 1-9, which cannot be equal to any of the values in the /// bitarray illegalValues. /// </summary> void FindMinMaxSum(int illegalValues, int nElements, out int minsum, out int maxsum) { minsum = 0; maxsum = 0; if (nElements == 0) return; int j = 0; for (int i = 1; i <= 9; i++) { if ((illegalValues & (1 << i)) == 0) { minsum += i; j++; if (j == nElements) break; } } j = 0; for (int i = 9; i >= 1; i--) { if ((illegalValues & (1 << i)) == 0) { maxsum += i; j++; if (j == nElements) break; } } } /// <summary> /// MinimumSum[n] : the smallest possible sum of n different positive integers /// </summary> private static int[] MinimumSum = new int[10] { 0, 1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5, 1 + 2 + 3 + 4 + 5 + 6, 1 + 2 + 3 + 4 + 5 + 6 + 7, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 }; /// <summary> /// MaximumSum[n] : the largest possible sum of n different positive integers /// </summary> private static int[] MaximumSum = new int[10] { 0, 9, 9 + 8, 9 + 8 + 7, 9 + 8 + 7 + 6, 9 + 8 + 7 + 6 + 5, 9 + 8 + 7 + 6 + 5 + 4, 9 + 8 + 7 + 6 + 5 + 4 + 3, 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2, 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 }; /// <summary> /// DEPRECATED FUNCTION - USE SolveIterate instead /// </summary> private bool SolveAt(int nRow, int nCol) { if (System.DateTime.Now > m_dtNextUpdate) { m_updater.UpdateStatus(); m_dtNextUpdate = System.DateTime.Now.AddSeconds(m_nUpdateSeconds); } if (nCol == m_nCols) { nCol = 0; nRow++; } if (nRow == m_nRows && nCol == 0) { // complete! return true; } // if we are in a sum-type element, then advance to next element if (!this[nRow, nCol].HasValue) { return SolveAt(nRow, nCol + 1); } // we are in a value-type element. see if we can make it work. // first, find information about the current column and row. int nColStart, nColEnd, nColSum; //NB: nColStart is the ROW in which the current column starts! int nRowStart, nRowEnd, nRowSum; //NB: nRowStart is the COLUMN in which the current row starts! // find the row in which the current column starts for (nColStart = nRow; this[nColStart - 1, nCol].HasValue; nColStart--) ; // find the row in which the current column ends for (nColEnd = nRow; nColEnd < m_nRows - 1 && this[nColEnd + 1, nCol].HasValue; nColEnd++) ; // find the column in which the current row starts for (nRowStart = nCol; this[nRow, nRowStart - 1].HasValue; nRowStart--) ; // find the column in which the current row ends for (nRowEnd = nCol; nRowEnd < m_nCols - 1 && this[nRow, nRowEnd + 1].HasValue; nRowEnd++) ; // find the expected sums for the current row and column nColSum = this[nColStart - 1, nCol].SumDown; nRowSum = this[nRow, nRowStart - 1].SumRight; Debug.Assert(nColSum != Element.Unused); Debug.Assert(nRowSum != Element.Unused); // find illegal values for the current element. // these are stored in the bitarray illegalValues: // value i is illegal iff bit i is 1 int illegalValues = 0; // stage 1: must not appear in the current column // (we also use this pass to calculate the column sum so far) int colsum = 0; for (int i = nColStart; i < nRow; i++) { int valHere = this[i, nCol].Value; illegalValues |= (1 << valHere); colsum += valHere; } // stage 2: must not appear in the current row // (we also use this pass to calculate the row sum so far) int rowsum = 0; for (int i = nRowStart; i < nCol; i++) { int valHere = this[nRow, i].Value; illegalValues |= (1 << valHere); rowsum += valHere; } int curValue = 0; // if we are in the last element of the column/row, we must behave differently, // since there is only one possible value here if (nCol == nRowEnd) { curValue = nRowSum - rowsum; if (curValue < 1 || curValue > 9) return false; } if (nRow == nColEnd) { int required = nColSum - colsum; if (required < 1 || required > 9) return false; if (curValue == 0) curValue = required; else { if (curValue != required) { // contradiction between row and column requirements; we failed return false; } else { // row and column requirements agree; continue } } } if (curValue != 0) { // we have a row or column requirement; see if the required value is legal if ((illegalValues & (1 << curValue)) == 0) { // digit doesn't yet appear if (colsum + curValue <= nColSum) { // digit doesn't exceed expected column sum if (rowsum + curValue <= nRowSum) { // digit doesn't exceed expected row sum // set value in current cell this[nRow, nCol].Value = curValue; // recurse if (SolveAt(nRow, nCol + 1)) { // success! return true; } else { // this doesn't work; we failed } } } } } else { // no row or column requirements; check all legal possibilities for (curValue = 9; curValue >= 1; curValue--) { // see if this value is legal if ((illegalValues & (1 << curValue)) != 0) continue; // digit already appears in current row or column if (colsum + curValue > nColSum) continue; // exceeded expected column sum if (rowsum + curValue > nRowSum) continue; // exceeded expected row sum // set value in current cell this[nRow, nCol].Value = curValue; // recurse if (SolveAt(nRow, nCol + 1)) { // success! return true; } else { // that didn't work, try the next one } } } // nothing worked; // let's clear the field so the higher recursion level can try again this[nRow, nCol].Value = Element.Unknown; return false; } public int Rows { get { return m_nRows; } } public int Cols { get { return m_nCols; } } private int m_nRows, m_nCols; private Element[,] m_board; } /// <summary> /// A single element in a Kakuro board. /// May be either a value element, or a sum element. /// Value elements contain a digit (1-9). /// Sum elements contain either a sumDown, or a sumRight, or both. /// </summary> public class Element { /// <summary> /// Indicates that this member is not used in the current element type /// (for example, SumDown in an element containing a digit value) /// </summary> public const int Unused = -1; /// <summary> /// Indicates that the element contains an unknown value /// </summary> public const int Unknown = 0; /// <summary> /// An illegal value - should not appear when solving /// </summary> public const int Illegal = -100; /// <summary> /// default constructor creates an element with an unknown value /// </summary> public Element() { m_nValue = Unknown; m_nSumDown = Unused; m_nSumRight = Unused; } /// <summary> /// create an element with a certain value /// </summary> public Element(int val) { SetValue(val); } /// <summary> /// Set to a value element /// </summary> public void SetValue(int val) { m_nValue = val; m_nSumDown = Unused; m_nSumRight = Unused; } /// <summary> /// create an element with one or two sums /// </summary> /// <param name="sumdown">Sum in downwards direction /// (use Element.Unknown if irrelevant)</param> /// <param name="sumright">Sum to the right /// (use Element.Unknown if irrelevant)</param> public Element(int sumdown, int sumright) { SetSum(sumdown, sumright); } /// <summary> /// Change the element to a sum-type element /// </summary> /// <param name="sumdown">Sum in downwards direction /// (use Element.Unknown if irrelevant)</param> /// <param name="sumright">Sum to the right /// (use Element.Unknown if irrelevant)</param> public void SetSum(int sumdown, int sumright) { m_nValue = Unused; m_nSumDown = sumdown; m_nSumRight = sumright; } public override string ToString() { if (HasValue) { if (Value == Unknown) return ""; else return Value.ToString(); } else { return string.Format("{0}\\{1}", HasSumDown ? SumDown.ToString() : "", HasSumRight ? SumRight.ToString() : ""); } } public int SumDown { get { return m_nSumDown; } } public int SumRight { get { return m_nSumRight; } } public int Value { get { return m_nValue; } set { if (m_nValue == Unused) throw new InvalidOperationException("This cell cannot contain digit values"); m_nValue = value; } } public bool HasValue { get { return (m_nValue != Unused); } } public bool HasSumDown { get { return (m_nSumDown != Unused); } } public bool HasSumRight { get { return (m_nSumRight != Unused); } } private int m_nValue; private int m_nSumDown; private int m_nSumRight; } }
//----------------------------------------------------------------------- // <copyright file="Manipulator.cs" company="Google LLC"> // // Copyright 2018 Google LLC. 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.ObjectManipulation { using UnityEngine; /// <summary> /// Base class that manipulates an object via a gesture. /// </summary> public abstract class Manipulator : MonoBehaviour { private bool m_IsManipulating; private GameObject m_SelectedObject; /// <summary> /// Makes this game object become the Selected Object. /// </summary> public void Select() { ManipulationSystem.Instance.Select(gameObject); } /// <summary> /// Unselects this game object if it is currently the Selected Object. /// </summary> public void Deselect() { if (IsSelected()) { ManipulationSystem.Instance.Deselect(); } } /// <summary> /// Whether this game object is the Selected Object. /// </summary> /// <returns><c>true</c>, if this is the Selected Object, <c>false</c> otherwise.</returns> public bool IsSelected() { return m_SelectedObject == gameObject; } /// <summary> /// Returns true if the manipulation can be started for the given gesture. /// </summary> /// <param name="gesture">The current gesture.</param> /// <returns>True if the manipulation can be started.</returns> protected virtual bool CanStartManipulationForGesture(DragGesture gesture) { return false; } /// <summary> /// Returns true if the manipulation can be started for the given gesture. /// </summary> /// <param name="gesture">The current gesture.</param> /// <returns>True if the manipulation can be started.</returns> protected virtual bool CanStartManipulationForGesture(PinchGesture gesture) { return false; } /// <summary> /// Returns true if the manipulation can be started for the given gesture. /// </summary> /// <param name="gesture">The current gesture.</param> /// <returns>True if the manipulation can be started.</returns> protected virtual bool CanStartManipulationForGesture(TapGesture gesture) { return false; } /// <summary> /// Returns true if the manipulation can be started for the given gesture. /// </summary> /// <param name="gesture">The current gesture.</param> /// <returns>True if the manipulation can be started.</returns> protected virtual bool CanStartManipulationForGesture(TwistGesture gesture) { return false; } /// <summary> /// Returns true if the manipulation can be started for the given gesture. /// </summary> /// <param name="gesture">The current gesture.</param> /// <returns>True if the manipulation can be started.</returns> protected virtual bool CanStartManipulationForGesture(TwoFingerDragGesture gesture) { return false; } /// <summary> /// Function called when the manipulation is started. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnStartManipulation(DragGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is started. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnStartManipulation(PinchGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is started. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnStartManipulation(TapGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is started. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnStartManipulation(TwistGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is started. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnStartManipulation(TwoFingerDragGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is continued. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnContinueManipulation(DragGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is continued. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnContinueManipulation(PinchGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is continued. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnContinueManipulation(TapGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is continued. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnContinueManipulation(TwistGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is continued. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnContinueManipulation(TwoFingerDragGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is ended. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnEndManipulation(DragGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is ended. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnEndManipulation(PinchGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is ended. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnEndManipulation(TapGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is ended. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnEndManipulation(TwistGesture gesture) { // Optional override. } /// <summary> /// Function called when the manipulation is ended. /// </summary> /// <param name="gesture">The current gesture.</param> protected virtual void OnEndManipulation(TwoFingerDragGesture gesture) { // Optional override. } /// <summary> /// Function called when this game object becomes the Selected Object. /// </summary> protected virtual void OnSelected() { // Optional override. } /// <summary> /// Function called when this game object is deselected if it was the Selected Object. /// </summary> protected virtual void OnDeselected() { // Optional override. } /// <summary> /// Enables the manipulator. /// </summary> protected virtual void OnEnable() { ConnectToRecognizers(); } /// <summary> /// Disables the manipulator. /// </summary> protected virtual void OnDisable() { DisconnectFromRecognizers(); } /// <summary> /// The Unity Update() method. /// </summary> protected virtual void Update() { if (m_SelectedObject == gameObject && ManipulationSystem.Instance.SelectedObject != gameObject) { m_SelectedObject = ManipulationSystem.Instance.SelectedObject; OnDeselected(); } else if (m_SelectedObject != gameObject && ManipulationSystem.Instance.SelectedObject == gameObject) { m_SelectedObject = ManipulationSystem.Instance.SelectedObject; OnSelected(); } else { m_SelectedObject = ManipulationSystem.Instance.SelectedObject; } } private void ConnectToRecognizers() { if (ManipulationSystem.Instance == null) { Debug.LogError("Manipulation system not found in scene."); return; } DragGestureRecognizer dragGestureRecognizer = ManipulationSystem.Instance.DragGestureRecognizer; if (dragGestureRecognizer != null) { dragGestureRecognizer.onGestureStarted += OnGestureStarted; } PinchGestureRecognizer pinchGestureRecognizer = ManipulationSystem.Instance.PinchGestureRecognizer; if (pinchGestureRecognizer != null) { pinchGestureRecognizer.onGestureStarted += OnGestureStarted; } TapGestureRecognizer tapGestureRecognizer = ManipulationSystem.Instance.TapGestureRecognizer; if (tapGestureRecognizer != null) { tapGestureRecognizer.onGestureStarted += OnGestureStarted; } TwistGestureRecognizer twistGestureRecognizer = ManipulationSystem.Instance.TwistGestureRecognizer; if (twistGestureRecognizer != null) { twistGestureRecognizer.onGestureStarted += OnGestureStarted; } TwoFingerDragGestureRecognizer twoFingerDragGestureRecognizer = ManipulationSystem.Instance.TwoFingerDragGestureRecognizer; if (twoFingerDragGestureRecognizer != null) { twoFingerDragGestureRecognizer.onGestureStarted += OnGestureStarted; } } private void DisconnectFromRecognizers() { if (ManipulationSystem.Instance == null) { Debug.LogError("Manipulation system not found in scene."); return; } DragGestureRecognizer dragGestureRecognizer = ManipulationSystem.Instance.DragGestureRecognizer; if (dragGestureRecognizer != null) { dragGestureRecognizer.onGestureStarted -= OnGestureStarted; } PinchGestureRecognizer pinchGestureRecognizer = ManipulationSystem.Instance.PinchGestureRecognizer; if (pinchGestureRecognizer != null) { pinchGestureRecognizer.onGestureStarted -= OnGestureStarted; } TapGestureRecognizer tapGestureRecognizer = ManipulationSystem.Instance.TapGestureRecognizer; if (tapGestureRecognizer != null) { tapGestureRecognizer.onGestureStarted -= OnGestureStarted; } TwistGestureRecognizer twistGestureRecognizer = ManipulationSystem.Instance.TwistGestureRecognizer; if (twistGestureRecognizer != null) { twistGestureRecognizer.onGestureStarted -= OnGestureStarted; } TwoFingerDragGestureRecognizer twoFingerDragGestureRecognizer = ManipulationSystem.Instance.TwoFingerDragGestureRecognizer; if (twoFingerDragGestureRecognizer != null) { twoFingerDragGestureRecognizer.onGestureStarted -= OnGestureStarted; } } private void OnGestureStarted(DragGesture gesture) { if (m_IsManipulating) { return; } if (CanStartManipulationForGesture(gesture)) { m_IsManipulating = true; gesture.onUpdated += OnUpdated; gesture.onFinished += OnFinished; OnStartManipulation(gesture); } } private void OnGestureStarted(PinchGesture gesture) { if (m_IsManipulating) { return; } if (CanStartManipulationForGesture(gesture)) { m_IsManipulating = true; gesture.onUpdated += OnUpdated; gesture.onFinished += OnFinished; OnStartManipulation(gesture); } } private void OnGestureStarted(TapGesture gesture) { if (m_IsManipulating) { return; } if (CanStartManipulationForGesture(gesture)) { m_IsManipulating = true; gesture.onUpdated += OnUpdated; gesture.onFinished += OnFinished; OnStartManipulation(gesture); } } private void OnGestureStarted(TwistGesture gesture) { if (m_IsManipulating) { return; } if (CanStartManipulationForGesture(gesture)) { m_IsManipulating = true; gesture.onUpdated += OnUpdated; gesture.onFinished += OnFinished; OnStartManipulation(gesture); } } private void OnGestureStarted(TwoFingerDragGesture gesture) { if (m_IsManipulating) { return; } if (CanStartManipulationForGesture(gesture)) { m_IsManipulating = true; gesture.onUpdated += OnUpdated; gesture.onFinished += OnFinished; OnStartManipulation(gesture); } } private void OnUpdated(DragGesture gesture) { if (!m_IsManipulating) { return; } // Can only transform selected Items. if (ManipulationSystem.Instance.SelectedObject != gameObject) { m_IsManipulating = false; OnEndManipulation(gesture); return; } OnContinueManipulation(gesture); } private void OnUpdated(PinchGesture gesture) { if (!m_IsManipulating) { return; } // Can only transform selected Items. if (ManipulationSystem.Instance.SelectedObject != gameObject) { m_IsManipulating = false; OnEndManipulation(gesture); return; } OnContinueManipulation(gesture); } private void OnUpdated(TapGesture gesture) { if (!m_IsManipulating) { return; } // Can only transform selected Items. if (ManipulationSystem.Instance.SelectedObject != gameObject) { m_IsManipulating = false; OnEndManipulation(gesture); return; } OnContinueManipulation(gesture); } private void OnUpdated(TwistGesture gesture) { if (!m_IsManipulating) { return; } // Can only transform selected Items. if (ManipulationSystem.Instance.SelectedObject != gameObject) { m_IsManipulating = false; OnEndManipulation(gesture); return; } OnContinueManipulation(gesture); } private void OnUpdated(TwoFingerDragGesture gesture) { if (!m_IsManipulating) { return; } // Can only transform selected Items. if (ManipulationSystem.Instance.SelectedObject != gameObject) { m_IsManipulating = false; OnEndManipulation(gesture); return; } OnContinueManipulation(gesture); } private void OnFinished(DragGesture gesture) { m_IsManipulating = false; OnEndManipulation(gesture); } private void OnFinished(PinchGesture gesture) { m_IsManipulating = false; OnEndManipulation(gesture); } private void OnFinished(TapGesture gesture) { m_IsManipulating = false; OnEndManipulation(gesture); } private void OnFinished(TwistGesture gesture) { m_IsManipulating = false; OnEndManipulation(gesture); } private void OnFinished(TwoFingerDragGesture gesture) { m_IsManipulating = false; OnEndManipulation(gesture); } } }
//----------------------------------------------------------------------- // <copyright> // Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project. // // This file is subject to the terms and conditions of the Microsoft Public License (MS-PL). // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Microsoft.Web.Management.Client; using Microsoft.Web.Management.Client.Win32; using Microsoft.Web.Management.Server; using Web.Management.PHP.Config; namespace Web.Management.PHP.Settings { [ModulePageIdentifier(Globals.RuntimeLimitsPageIdentifier)] internal sealed class RuntimeLimitsPage : ModulePropertiesPage, IModuleChildPage { // If adding properties here make sure to update the RuntimeLimistGlobal.cs private readonly string [] _settingNames = { "max_execution_time", "max_input_time", "memory_limit", "post_max_size", "upload_max_filesize", "max_file_uploads" }; private PropertyBag _clone; private PropertyBag _bag; private PageTaskList _taskList; private IModulePage _parentPage; protected override bool CanApplyChanges { get { return true; } } protected override bool ConfigNamesPresent { get { return true; } } internal bool IsReadOnly { get { return Connection.ConfigurationPath.PathType == Microsoft.Web.Management.Server.ConfigurationPathType.Site && !Connection.IsUserServerAdministrator; } } private new PHPModule Module { get { return (PHPModule)base.Module; } } public IModulePage ParentPage { get { return _parentPage; } set { _parentPage = value; } } protected override TaskListCollection Tasks { get { TaskListCollection tasks = base.Tasks; if (_taskList == null) { _taskList = new PageTaskList(this); } tasks.Add(_taskList); return tasks; } } protected override PropertyBag GetProperties() { PropertyBag result = new PropertyBag(); object o = Module.Proxy.GetPHPIniSettings(); PHPIniFile file = new PHPIniFile(); file.SetData(o); for (int i = 0; i < _settingNames.Length; i++) { PHPIniSetting setting = file.GetSetting(_settingNames[i]); if (setting != null) { result[i] = setting.Value; } } return result; } private void GoBack() { Navigate(typeof(PHPPage)); } protected override void ProcessProperties(PropertyBag properties) { _bag = properties; _clone = _bag.Clone(); RuntimeLimitSettings settings = TargetObject as RuntimeLimitSettings; if (settings == null) { settings = new RuntimeLimitSettings(this, this.IsReadOnly, _clone); TargetObject = settings; } else { settings.Initialize(_clone); } ClearDirty(); } protected override bool ShowHelp() { return ShowOnlineHelp(); } protected override bool ShowOnlineHelp() { return Helper.Browse(Globals.RuntimeLimitsOnlineHelp); } protected override PropertyBag UpdateProperties(out bool updateSuccessful) { updateSuccessful = false; RemoteObjectCollection<PHPIniSetting> settings = new RemoteObjectCollection<PHPIniSetting>(); for (int i = 0; i < _settingNames.Length; i++) { settings.Add(new PHPIniSetting(_settingNames[i], (string)_clone[i], "PHP")); } try { Module.Proxy.AddOrUpdateSettings(settings); _bag = _clone; updateSuccessful = true; } catch(Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } return _bag; } private class PageTaskList : TaskList { private RuntimeLimitsPage _page; public PageTaskList(RuntimeLimitsPage page) { _page = page; } public override System.Collections.ICollection GetTaskItems() { List<TaskItem> tasks = new List<TaskItem>(); if (_page.IsReadOnly) { tasks.Add(new MessageTaskItem(MessageTaskItemType.Information, Resources.AllPagesPageIsReadOnly, "Information")); } tasks.Add(new MethodTaskItem("GoBack", Resources.AllPagesGoBackTask, "Tasks", null, Resources.GoBack16)); return tasks; } public void GoBack() { _page.GoBack(); } } } }
using System; using System.Collections.Generic; namespace DuckGame { // Token: 0x02000509 RID: 1289 [BaggedProperty("isSuperWeapon", true)] [EditorGroup("guns|melee")] public class Chainsaw : Gun { // Token: 0x17000661 RID: 1633 // (get) Token: 0x06002300 RID: 8960 // (set) Token: 0x06002301 RID: 8961 public override float angle { get { return base.angle + this._hold * (float)this.offDir + this._animRot * (float)this.offDir + this._rotSway * (float)this.offDir; } set { this._angle = value; } } // Token: 0x17000662 RID: 1634 // (get) Token: 0x06002302 RID: 8962 public Vec2 barrelStartPos { get { return this.position + (this.Offset(base.barrelOffset) - this.position).normalized * 2f; } } // Token: 0x17000663 RID: 1635 // (get) Token: 0x06002303 RID: 8963 public bool throttle { get { return this._throttle; } } // Token: 0x06002304 RID: 8964 public Chainsaw(float xval, float yval) : base(xval, yval) { this.ammo = 4; this._ammoType = new ATLaser(); this._ammoType.range = 170f; this._ammoType.accuracy = 0.8f; this._type = "gun"; this._sprite = new SpriteMap("chainsaw", 29, 13, false); this.graphic = this._sprite; this.center = new Vec2(8f, 7f); this.collisionOffset = new Vec2(-8f, -6f); this.collisionSize = new Vec2(20f, 11f); this._barrelOffsetTL = new Vec2(27f, 8f); this._sprite.AddAnimation("empty", 1f, true, new int[] { 1 }); this._fireSound = "smg"; this._fullAuto = true; this._fireWait = 1f; this._kickForce = 3f; this._holdOffset = new Vec2(-4f, 4f); this.weight = 5f; this.physicsMaterial = PhysicsMaterial.Metal; this._swordSwing = new SpriteMap("swordSwipe", 32, 32, false); this._swordSwing.AddAnimation("swing", 0.6f, false, new int[] { 0, 1, 1, 2 }); this._swordSwing.currentAnimation = "swing"; this._swordSwing.speed = 0f; this._swordSwing.center = new Vec2(9f, 25f); this.throwSpeedMultiplier = 0.5f; this._bouncy = 0.5f; this._impactThreshold = 0.3f; base.collideSounds.Add("landTV"); } // Token: 0x06002305 RID: 8965 public override void Initialize() { this._sprite = new SpriteMap("chainsaw", 29, 13, false); if (this.souped) { this._sprite = new SpriteMap("turbochainsaw", 29, 13, false); } this.graphic = this._sprite; base.Initialize(); } // Token: 0x06002306 RID: 8966 public override void Terminate() { this._sound.Kill(); this._bladeSound.Kill(); this._bladeSoundLow.Kill(); } // Token: 0x06002307 RID: 8967 public void Shing(Thing wall) { if (!this._shing) { this._struggling = true; this._shing = true; if (!Chainsaw._playedShing) { Chainsaw._playedShing = true; SFX.Play("chainsawClash", Rando.Float(0.4f, 0.55f), Rando.Float(-0.2f, 0.2f), Rando.Float(-0.1f, 0.1f), false); } Vec2 normalized = (this.position - base.barrelPosition).normalized; Vec2 value = base.barrelPosition; for (int i = 0; i < 6; i++) { Level.Add(Spark.New(value.x, value.y, new Vec2(Rando.Float(-1f, 1f), Rando.Float(-1f, 1f)), 0.02f)); value += normalized * 4f; } this._swordSwing.speed = 0f; if (Recorder.currentRecording != null) { Recorder.currentRecording.LogAction(7); } if (base.duck != null) { Duck duck = base.duck; if (wall.bottom < duck.top) { duck.vSpeed += 2f; return; } if (duck.sliding) { duck.sliding = false; } if (wall.x > duck.x) { duck.hSpeed -= 5f; } else { duck.hSpeed += 5f; } duck.vSpeed -= 2f; } } } // Token: 0x06002308 RID: 8968 public override bool Hit(Bullet bullet, Vec2 hitPos) { SFX.Play("ting", 1f, 0f, 0f, false); return base.Hit(bullet, hitPos); } // Token: 0x06002309 RID: 8969 public override void OnSoftImpact(MaterialThing with, ImpactedFrom from) { if (this.owner == null && with is Block) { this.Shing(with); if (base.totalImpactPower > 3f) { this._started = false; } } } // Token: 0x0600230A RID: 8970 public override void ReturnToWorld() { this._throwSpin = 90f; } // Token: 0x0600230B RID: 8971 public void PullEngine() { float pitch = this.souped ? 0.3f : 0f; if (!this._flooded && this._gas > 0f && (this._warmUp > 0.5f || this._engineResistance < 1f)) { SFX.Play("chainsawFire", 1f, 0f, 0f, false); this._started = true; this._engineSpin = 1.5f; for (int i = 0; i < 2; i++) { Level.Add(SmallSmoke.New(base.x + (float)(this.offDir * 4), base.y + 5f)); } this._flooded = false; this._flood = 0f; } else { if (this._flooded && this._gas > 0f) { SFX.Play("chainsawFlooded", 0.9f, Rando.Float(-0.2f, 0.2f), 0f, false); this._engineSpin = 1.6f; } else { if (this._gas == 0f || Rando.Float(1f) > 0.3f) { SFX.Play("chainsawPull", 1f, pitch, 0f, false); } else { SFX.Play("chainsawFire", 1f, pitch, 0f, false); } this._engineSpin = 0.8f; } if (Rando.Float(1f) > 0.8f) { this._flooded = false; this._flood = 0f; } } this._engineResistance -= 0.5f; if (this._gas > 0f) { int num = this._flooded ? 4 : 2; for (int j = 0; j < num; j++) { Level.Add(SmallSmoke.New(base.x + (float)(this.offDir * 4), base.y + 5f)); } } } // Token: 0x0600230C RID: 8972 public override void Update() { base.Update(); float num = 1f; if (this.souped) { num = 1.3f; } if (this._swordSwing.finished) { this._swordSwing.speed = 0f; } if (this._hitWait > 0) { this._hitWait--; } if (this._gas < 0.01f) { this.ammo = 0; } this._framesExisting++; if (this._framesExisting > 100) { this._framesExisting = 100; } float pitch = this.souped ? 0.3f : 0f; this._sound.lerpVolume = ((this._started && !this._throttle) ? 0.6f : 0f); this._sound.pitch = pitch; if (this._started) { this._warmUp += 0.001f; if (this._warmUp > 1f) { this._warmUp = 1f; } if (!this._puffClick && this._idleWave > 0.9f) { this._skipSmoke = !this._skipSmoke; if (this._throttle || !this._skipSmoke) { Level.Add(SmallSmoke.New(base.x + (float)(this.offDir * 4), base.y + 5f, this._smokeFlipper ? -0.1f : 0.8f, 0.7f)); this._smokeFlipper = !this._smokeFlipper; this._puffClick = true; } } else if (this._puffClick && this._idleWave < 0f) { this._puffClick = false; } if (this._pullState < 0) { float num2 = 1f + Maths.NormalizeSection(this._engineSpin, 1f, 2f) * 2f; float num3 = this._idleWave; if (num2 > 1f) { num3 = this._spinWave; } this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(0f, 2f + num3 * num2), 0.23f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f + num3 * num2), 0.23f); float num4 = Maths.NormalizeSection(this._engineSpin, 1f, 2f) * 3f; this._rotSway = this._idleWave.normalized * num4 * 0.03f; } else { this._rotSway = 0f; } this._gas -= 3E-05f; if (this._throttle) { this._gas -= 0.0002f; } if (this._gas < 0f) { this._gas = 0f; this._started = false; this._throttle = false; } if (this._triggerHeld) { if (this._releasedSincePull) { if (!this._throttle) { this._throttle = true; SFX.Play("chainsawBladeRevUp", 0.5f, pitch, 0f, false); } this._engineSpin = Lerp.FloatSmooth(this._engineSpin, 4f, 0.1f, 1f); } } else { if (this._throttle) { this._throttle = false; if (this._engineSpin > 1.7f) { SFX.Play("chainsawBladeRevDown", 0.5f, pitch, 0f, false); } } this._engineSpin = Lerp.FloatSmooth(this._engineSpin, 0f, 0.1f, 1f); this._releasedSincePull = true; } } else { this._warmUp -= 0.001f; if (this._warmUp < 0f) { this._warmUp = 0f; } this._releasedSincePull = false; this._throttle = false; } this._bladeSound.lerpSpeed = 0.1f; this._throttleWait = Lerp.Float(this._throttleWait, this._throttle ? 1f : 0f, 0.07f); this._bladeSound.lerpVolume = ((this._throttleWait > 0.96f) ? 0.6f : 0f); if (this._struggling) { this._bladeSound.lerpVolume = 0f; } this._bladeSoundLow.lerpVolume = ((this._throttleWait > 0.96f && this._struggling) ? 0.6f : 0f); this._bladeSound.pitch = pitch; this._bladeSoundLow.pitch = pitch; if (this.owner == null) { this.collisionOffset = new Vec2(-8f, -6f); this.collisionSize = new Vec2(13f, 11f); } else if (base.duck != null && (base.duck.sliding || base.duck.crouch)) { this.collisionOffset = new Vec2(-8f, -6f); this.collisionSize = new Vec2(6f, 11f); } else { this.collisionOffset = new Vec2(-8f, -6f); this.collisionSize = new Vec2(10f, 11f); } if (this.owner != null) { this._resetDuck = false; if (this._pullState == -1) { if (!this._started) { this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(0f, 2f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f), 0.23f); } this._upWait = 0f; } else if (this._pullState == 0) { this._animRot = Lerp.FloatSmooth(this._animRot, -0.4f, 0.15f, 1f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(-2f, -2f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(-4f, 4f), 0.23f); if (this._animRot <= -0.35f) { this._animRot = -0.4f; this._pullState = 1; this.PullEngine(); } this._upWait = 0f; } else if (this._pullState == 1) { this._releasePull = false; this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(2f, 3f), 0.23f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(-4f, -2f), 0.23f); this._animRot = Lerp.FloatSmooth(this._animRot, -0.5f, 0.07f, 1f); if (this._animRot < -0.45f) { this._animRot = -0.5f; this._pullState = 2; } this._upWait = 0f; } else if (this._pullState == 2) { if (this._releasePull || !this._triggerHeld) { this._releasePull = true; if (this._started) { this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(0f, 2f + this._idleWave.normalized), 0.23f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f + this._idleWave.normalized), 0.23f); this._animRot = Lerp.FloatSmooth(this._animRot, 0f, 0.1f, 1f); if (this._animRot > -0.07f) { this._animRot = 0f; this._pullState = -1; } } else { this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(-4f, 4f), 0.24f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(-2f, -2f), 0.24f); this._animRot = Lerp.FloatSmooth(this._animRot, -0.4f, 0.12f, 1f); if (this._animRot > -0.44f) { this._releasePull = false; this._animRot = -0.4f; this._pullState = 3; this._holdOffset = new Vec2(-4f, 4f); this.handOffset = new Vec2(-2f, -2f); } } } this._upWait = 0f; } else if (this._pullState == 3) { this._releasePull = false; this._upWait += 0.1f; if (this._upWait > 6f) { this._pullState = -1; } } this._bladeSpin += this._engineSpin; while (this._bladeSpin >= 1f) { this._bladeSpin -= 1f; int num5 = this._sprite.frame + 1; if (num5 > 15) { num5 = 0; } this._sprite.frame = num5; } this._engineSpin = Lerp.FloatSmooth(this._engineSpin, 0f, 0.1f, 1f); this._engineResistance = Lerp.FloatSmooth(this._engineResistance, 1f, 0.01f, 1f); this._hold = -0.4f; this.center = new Vec2(8f, 7f); this._framesSinceThrown = 0; } else { this._rotSway = 0f; this._shing = false; this._animRot = Lerp.FloatSmooth(this._animRot, 0f, 0.18f, 1f); if (this._framesSinceThrown == 1) { this._throwSpin = base.angleDegrees; } this._hold = 0f; base.angleDegrees = this._throwSpin; this.center = new Vec2(8f, 7f); bool flag = false; bool flag2 = false; if ((Math.Abs(this.hSpeed) + Math.Abs(this.vSpeed) > 2f || !base.grounded) && this.gravMultiplier > 0f) { if (!base.grounded && Level.CheckRect<Block>(this.position + new Vec2(-8f, -6f), this.position + new Vec2(8f, -2f), null) != null) { flag2 = true; } if (!flag2 && !this._grounded && Level.CheckPoint<IPlatform>(this.position + new Vec2(0f, 8f), null, null) == null) { if (this.offDir > 0) { this._throwSpin += (Math.Abs(this.hSpeed) + Math.Abs(this.vSpeed)) * 1f + 5f; } else { this._throwSpin -= (Math.Abs(this.hSpeed) + Math.Abs(this.vSpeed)) * 1f + 5f; } flag = true; } } if (!flag || flag2) { this._throwSpin %= 360f; if (this._throwSpin < 0f) { this._throwSpin += 360f; } if (flag2) { if (Math.Abs(this._throwSpin - 90f) < Math.Abs(this._throwSpin + 90f)) { this._throwSpin = Lerp.Float(this._throwSpin, 90f, 16f); } else { this._throwSpin = Lerp.Float(-90f, 0f, 16f); } } else if (this._throwSpin > 90f && this._throwSpin < 270f) { this._throwSpin = Lerp.Float(this._throwSpin, 180f, 14f); } else { if (this._throwSpin > 180f) { this._throwSpin -= 360f; } else if (this._throwSpin < -180f) { this._throwSpin += 360f; } this._throwSpin = Lerp.Float(this._throwSpin, 0f, 14f); } } } if (Math.Abs(this._angle) > 1f) { this._flood += 0.005f; if (this._flood > 1f) { this._flooded = true; this._started = false; } this._gasDripFrames++; if (this._gas > 0f && this._flooded && this._gasDripFrames > 2) { FluidData gas = Fluid.Gas; gas.amount = 0.003f; this._gas -= 0.005f; if (this._gas < 0f) { this._gas = 0f; } Level.Add(new Fluid(base.x, base.y, Vec2.Zero, gas, null, 1f)); this._gasDripFrames = 0; } if (this._gas <= 0f) { this._started = false; } } else { this._flood -= 0.008f; if (this._flood < 0f) { this._flood = 0f; } } if (base.duck != null) { base.duck.frictionMult = 1f; if (this._skipSpark > 0) { this._skipSpark++; if (this._skipSpark > 2) { this._skipSpark = 0; } } if (base.duck.sliding && this._throttle && this._skipSpark == 0) { if (Level.CheckLine<Block>(this.barrelStartPos + new Vec2(0f, 8f), base.barrelPosition + new Vec2(0f, 8f), null) != null) { this._skipSpark = 1; Vec2 value = this.position + base.barrelVector * 5f; for (int i = 0; i < 2; i++) { Level.Add(Spark.New(value.x, value.y, new Vec2((float)this.offDir * Rando.Float(0f, 2f), Rando.Float(0.5f, 1.5f)), 0.02f)); value += base.barrelVector * 2f; this._fireTrailWait -= 0.5f; if (this.souped && this._fireTrailWait <= 0f) { this._fireTrailWait = 1f; SmallFire smallFire = SmallFire.New(value.x, value.y, (float)this.offDir * Rando.Float(0f, 2f), Rando.Float(0.5f, 1.5f), false, null, true, null, false); smallFire.waitToHurt = Rando.Float(1f, 2f); smallFire.whoWait = (this.owner as Duck); Level.Add(smallFire); } } if (this.offDir > 0 && this.owner.hSpeed < (float)(this.offDir * 6) * num) { this.owner.hSpeed = (float)(this.offDir * 6) * num; } else if (this.offDir < 0 && this.owner.hSpeed > (float)(this.offDir * 6) * num) { this.owner.hSpeed = (float)(this.offDir * 6) * num; } } else if (this.offDir > 0 && this.owner.hSpeed < (float)(this.offDir * 3) * num) { this.owner.hSpeed = (float)(this.offDir * 3) * num; } else if (this.offDir < 0 && this.owner.hSpeed > (float)(this.offDir * 3) * num) { this.owner.hSpeed = (float)(this.offDir * 3) * num; } } if (this._pullState == -1) { if (!this._throttle) { this._animRot = MathHelper.Lerp(this._animRot, 0.3f, 0.2f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(-2f, 2f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(-3f, 4f), 0.23f); } else if (this._shing) { this._animRot = MathHelper.Lerp(this._animRot, -1.8f, 0.4f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(1f, 0f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f), 0.23f); if (this._animRot < -1.5f) { this._shing = false; } } else if (base.duck.crouch) { this._animRot = MathHelper.Lerp(this._animRot, 0.4f, 0.2f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(1f, 0f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f), 0.23f); } else if (base.duck.inputProfile.Down("UP")) { this._animRot = MathHelper.Lerp(this._animRot, -0.9f, 0.2f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(1f, 0f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f), 0.23f); } else { this._animRot = MathHelper.Lerp(this._animRot, 0f, 0.2f); this.handOffset = Lerp.Vec2Smooth(this.handOffset, new Vec2(1f, 0f), 0.25f); this._holdOffset = Lerp.Vec2Smooth(this._holdOffset, new Vec2(1f, 2f), 0.23f); } } } else if (!this._resetDuck && base.prevOwner != null) { PhysicsObject physicsObject = base.prevOwner as PhysicsObject; if (physicsObject != null) { physicsObject.frictionMult = 1f; } this._resetDuck = true; } if (this._skipDebris > 0) { this._skipDebris++; } if (this._skipDebris > 3) { this._skipDebris = 0; } this._struggling = false; if (this.owner != null && this._started && this._throttle && !this._shing) { (this.Offset(base.barrelOffset) - this.position).Normalize(); this.Offset(base.barrelOffset); IEnumerable<IAmADuck> enumerable = Level.CheckLineAll<IAmADuck>(this.barrelStartPos, base.barrelPosition); Block block3 = Level.CheckLine<Block>(this.barrelStartPos, base.barrelPosition, null); if (this.owner != null) { foreach (MaterialThing materialThing in Level.CheckLineAll<MaterialThing>(this.barrelStartPos, base.barrelPosition)) { if (materialThing.Hurt((materialThing is Door) ? 1.8f : 0.5f)) { if (base.duck != null && base.duck.sliding && materialThing is Door && (materialThing as Door)._jammed) { materialThing.Destroy(new DTImpale(this)); } else { this._struggling = true; if (base.duck != null) { base.duck.frictionMult = 4f; } if (this._skipDebris == 0) { this._skipDebris = 1; Vec2 value2 = Collision.LinePoint(this.barrelStartPos, base.barrelPosition, materialThing.rectangle); if (value2 != Vec2.Zero) { value2 += base.barrelVector * Rando.Float(0f, 3f); Vec2 vec = -base.barrelVector.Rotate(Rando.Float(-0.2f, 0.2f), Vec2.Zero); if (materialThing.physicsMaterial == PhysicsMaterial.Wood) { WoodDebris woodDebris = WoodDebris.New(value2.x, value2.y); woodDebris.hSpeed = vec.x * 3f; woodDebris.vSpeed = vec.y * 3f; Level.Add(woodDebris); } else if (materialThing.physicsMaterial == PhysicsMaterial.Metal) { Spark spark = Spark.New(value2.x, value2.y, Vec2.Zero, 0.02f); spark.hSpeed = vec.x * 3f; spark.vSpeed = vec.y * 3f; Level.Add(spark); } } } } } } } bool flag3 = false; if (block3 != null && !(block3 is Door)) { this.Shing(block3); if (block3 is Window) { block3.Destroy(new DTImpact(this)); } } else { foreach (Thing thing in Level.current.things[typeof(Sword)]) { Sword sword = (Sword)thing; if (sword.owner != null && sword.crouchStance && !sword.jabStance && Collision.LineIntersect(this.barrelStartPos, base.barrelPosition, sword.barrelStartPos, sword.barrelPosition)) { this.Shing(sword); sword.Shing(); sword.owner.hSpeed += (float)this.offDir * 3f; sword.owner.vSpeed -= 2f; base.duck.hSpeed += -(float)this.offDir * 3f; base.duck.vSpeed -= 2f; sword.duck.crippleTimer = 1f; base.duck.crippleTimer = 1f; flag3 = true; } } if (!flag3) { Thing ignore = null; if (base.duck != null) { ignore = base.duck.GetEquipment(typeof(Helmet)); } QuadLaserBullet quadLaserBullet = Level.CheckLine<QuadLaserBullet>(this.position, base.barrelPosition, null); if (quadLaserBullet != null) { this.Shing(quadLaserBullet); Vec2 travel = quadLaserBullet.travel; float length = travel.length; float num6 = 1f; if (this.offDir > 0 && travel.x < 0f) { num6 = 1.5f; } else if (this.offDir < 0 && travel.x > 0f) { num6 = 1.5f; } if (this.offDir > 0) { travel = new Vec2(length * num6, 0f); } else { travel = new Vec2(-length * num6, 0f); } quadLaserBullet.travel = travel; } else { Helmet helmet = Level.CheckLine<Helmet>(this.barrelStartPos, base.barrelPosition, ignore); if (helmet != null && helmet.equippedDuck != null) { this.Shing(helmet); helmet.owner.hSpeed += (float)this.offDir * 3f; helmet.owner.vSpeed -= 2f; helmet.duck.crippleTimer = 1f; helmet.Hurt(0.53f); flag3 = true; } else { if (base.duck != null) { ignore = base.duck.GetEquipment(typeof(ChestPlate)); } ChestPlate chestPlate = Level.CheckLine<ChestPlate>(this.barrelStartPos, base.barrelPosition, ignore); if (chestPlate != null && chestPlate.equippedDuck != null) { this.Shing(chestPlate); chestPlate.owner.hSpeed += (float)this.offDir * 3f; chestPlate.owner.vSpeed -= 2f; chestPlate.duck.crippleTimer = 1f; chestPlate.Hurt(0.53f); flag3 = true; } } } } } if (!flag3) { foreach (Thing thing2 in Level.current.things[typeof(Chainsaw)]) { Chainsaw chainsaw = (Chainsaw)thing2; if (chainsaw != this && chainsaw.owner != null && Collision.LineIntersect(this.barrelStartPos, base.barrelPosition, chainsaw.barrelStartPos, chainsaw.barrelPosition)) { this.Shing(chainsaw); chainsaw.Shing(this); chainsaw.owner.hSpeed += (float)this.offDir * 2f; chainsaw.owner.vSpeed -= 1.5f; base.duck.hSpeed += -(float)this.offDir * 2f; base.duck.vSpeed -= 1.5f; chainsaw.duck.crippleTimer = 1f; base.duck.crippleTimer = 1f; flag3 = true; if (Recorder.currentRecording != null) { Recorder.currentRecording.LogBonus(); } } } } if (!flag3) { foreach (IAmADuck amADuck in enumerable) { if (amADuck != base.duck) { MaterialThing materialThing2 = amADuck as MaterialThing; if (materialThing2 != null) { materialThing2.velocity += new Vec2((float)this.offDir * 0.8f, -0.8f); materialThing2.Destroy(new DTImpale(this)); if (base.duck != null) { base.duck._timeSinceChainKill = 0; } } } } } } } // Token: 0x0600230D RID: 8973 public override void Draw() { Chainsaw._playedShing = false; if (this._swordSwing.speed > 0f) { if (base.duck != null) { this._swordSwing.flipH = (base.duck.offDir <= 0); } this._swordSwing.alpha = 0.4f; this._swordSwing.position = this.position; this._swordSwing.depth = base.depth + 1; this._swordSwing.Draw(); } if (base.duck != null && (this._pullState == 1 || this._pullState == 2)) { Graphics.DrawLine(this.Offset(new Vec2(-2f, -2f)), base.duck.armPosition + new Vec2(this.handOffset.x * (float)this.offDir, this.handOffset.y), Color.White, 1f, base.duck.depth + 10 - 1); } base.Draw(); } // Token: 0x0600230E RID: 8974 public override void OnPressAction() { Duck duck = this.owner as Duck; if (duck.inputProfile.Down("STRAFE") && duck.inputProfile.Down("QUACK")) { this.souped = true; this._sprite.SetAnimation("empty"); } if (this.souped && new Random().Next(1, 11) == 9) { this.OnDestroybam(null); } if (!this._started) { if (this._pullState == -1) { this._pullState = 0; return; } if (this._pullState == 3) { this._pullState = 1; this.PullEngine(); } } } // Token: 0x0600230F RID: 8975 public override void Fire() { } // Token: 0x0600254F RID: 9551 protected bool OnDestroybam(DestroyType type = null) { if (!base.isServerForObject) { return false; } ATRCShrapnel shrap = new ATRCShrapnel(); shrap.MakeNetEffect(this.position, false); List<Bullet> firedBullets = new List<Bullet>(); for (int i = 0; i < 20; i++) { float dir = (float)i * 18f - 5f + Rando.Float(10f); shrap = new ATRCShrapnel(); shrap.range = 55f + Rando.Float(14f); Bullet bullet = new Bullet(base.x + (float)(Math.Cos((double)Maths.DegToRad(dir)) * 6.0), base.y - (float)(Math.Sin((double)Maths.DegToRad(dir)) * 6.0), shrap, dir, null, false, -1f, false, true); bullet.firedFrom = this; firedBullets.Add(bullet); Level.Add(bullet); } if (Network.isActive) { Send.Message(new NMFireGun(null, firedBullets, 0, false, 4, false), NetMessagePriority.ReliableOrdered, null); firedBullets.Clear(); } Level.Remove(this); return true; } // Token: 0x040021F9 RID: 8697 public StateBinding _angleOffsetBinding = new StateBinding("_hold", -1, false, false); // Token: 0x040021FA RID: 8698 public StateBinding _throwSpinBinding = new StateBinding("_throwSpin", -1, false, false); // Token: 0x040021FB RID: 8699 public StateBinding _gasBinding = new StateBinding("_gas", -1, false, false); // Token: 0x040021FC RID: 8700 public StateBinding _floodBinding = new StateBinding("_flood", -1, false, false); // Token: 0x040021FD RID: 8701 public StateBinding _chainsawStateBinding = new StateFlagBinding(new string[] { "_flooded", "_started", "_throttle" }); // Token: 0x040021FE RID: 8702 public EditorProperty<bool> souped = new EditorProperty<bool>(false, null, 0f, 1f, 0.1f, null, false, false); // Token: 0x040021FF RID: 8703 private float _hold; // Token: 0x04002200 RID: 8704 private bool _shing; // Token: 0x04002201 RID: 8705 private static bool _playedShing; // Token: 0x04002202 RID: 8706 public float _throwSpin; // Token: 0x04002203 RID: 8707 private int _framesExisting; // Token: 0x04002204 RID: 8708 private int _hitWait; // Token: 0x04002205 RID: 8709 private SpriteMap _swordSwing; // Token: 0x04002206 RID: 8710 private SpriteMap _sprite; // Token: 0x04002207 RID: 8711 private float _rotSway; // Token: 0x04002208 RID: 8712 public bool _started; // Token: 0x04002209 RID: 8713 private int _pullState = -1; // Token: 0x0400220A RID: 8714 private float _animRot; // Token: 0x0400220B RID: 8715 private float _upWait; // Token: 0x0400220C RID: 8716 private float _engineSpin; // Token: 0x0400220D RID: 8717 private float _bladeSpin; // Token: 0x0400220E RID: 8718 private float _engineResistance = 1f; // Token: 0x0400220F RID: 8719 private SinWave _idleWave = 0.6f; // Token: 0x04002210 RID: 8720 private SinWave _spinWave = 1f; // Token: 0x04002211 RID: 8721 private bool _puffClick; // Token: 0x04002212 RID: 8722 private float _warmUp; // Token: 0x04002213 RID: 8723 public bool _flooded; // Token: 0x04002214 RID: 8724 private int _gasDripFrames; // Token: 0x04002215 RID: 8725 public float _flood; // Token: 0x04002216 RID: 8726 private bool _releasePull; // Token: 0x04002217 RID: 8727 public float _gas = 1f; // Token: 0x04002218 RID: 8728 private bool _struggling; // Token: 0x04002219 RID: 8729 private bool _throttle; // Token: 0x0400221A RID: 8730 private float _throttleWait; // Token: 0x0400221B RID: 8731 private bool _releasedSincePull; // Token: 0x0400221C RID: 8732 private int _skipDebris; // Token: 0x0400221D RID: 8733 private bool _resetDuck; // Token: 0x0400221E RID: 8734 private int _skipSpark; // Token: 0x0400221F RID: 8735 private ConstantSound _sound = new ConstantSound("chainsawIdle", 0f, 0f, "chainsawIdleMulti"); // Token: 0x04002220 RID: 8736 private ConstantSound _bladeSound = new ConstantSound("chainsawBladeLoop", 0f, 0f, "chainsawBladeLoopMulti"); // Token: 0x04002221 RID: 8737 private ConstantSound _bladeSoundLow = new ConstantSound("chainsawBladeLoopLow", 0f, 0f, "chainsawBladeLoopLowMulti"); // Token: 0x04002222 RID: 8738 private bool _smokeFlipper; // Token: 0x04002223 RID: 8739 private float _fireTrailWait; // Token: 0x04002224 RID: 8740 private bool _skipSmoke; } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Linq; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Utilities.Properties; using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Common; using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Model; using Microsoft.WindowsAzure.Scheduler; using Microsoft.WindowsAzure.Scheduler.Models; using Microsoft.Azure.Commands.Common.Authentication; namespace Microsoft.WindowsAzure.Commands.Utilities.Scheduler { public partial class SchedulerMgmntClient { #region Create Jobs /// <summary> /// Populates ErrorAction values from the request /// </summary> /// <param name="jobRequest">Request values</param> /// <returns>Populated JobErrorAction object</returns> private JobErrorAction PopulateErrorAction(PSCreateJobParams jobRequest) { if (!string.IsNullOrEmpty(jobRequest.ErrorActionMethod) && jobRequest.ErrorActionUri != null) { JobErrorAction errorAction = new JobErrorAction { Request = new JobHttpRequest { Uri = jobRequest.ErrorActionUri, Method = jobRequest.ErrorActionMethod } }; if (jobRequest.ErrorActionHeaders != null) { errorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary(); } if (jobRequest.ErrorActionMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.ErrorActionMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) errorAction.Request.Body = jobRequest.ErrorActionBody; return errorAction; } if (!string.IsNullOrEmpty(jobRequest.ErrorActionSasToken) && !string.IsNullOrEmpty(jobRequest.ErrorActionStorageAccount) && !string.IsNullOrEmpty(jobRequest.ErrorActionQueueName)) { return new JobErrorAction { QueueMessage = new JobQueueMessage { QueueName = jobRequest.ErrorActionQueueName, StorageAccountName = jobRequest.ErrorActionStorageAccount, SasToken = jobRequest.ErrorActionSasToken, Message = jobRequest.ErrorActionQueueBody ?? "" } }; } return null; } /// <summary> /// Creates a new Http Scheduler job /// </summary> /// <param name="jobRequest">Request values</param> /// <param name="status">Status of create action</param> /// <returns>Created Http Scheduler job</returns> public PSJobDetail CreateHttpJob(PSCreateJobParams jobRequest, out string status) { if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri); JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters { Action = new JobAction { Request = new JobHttpRequest { Uri = jobRequest.Uri, Method = jobRequest.Method }, } }; if (jobRequest.Headers != null) { jobCreateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary(); } if (jobRequest.HttpAuthType.Equals("ClientCertificate", StringComparison.OrdinalIgnoreCase)) { if (jobRequest.ClientCertPfx != null && jobRequest.ClientCertPassword != null) { jobCreateParams.Action.Request.Authentication = new ClientCertAuthentication { Type = HttpAuthenticationType.ClientCertificate, Password = jobRequest.ClientCertPassword, Pfx = jobRequest.ClientCertPfx }; } else { throw new InvalidOperationException(Resources.SchedulerInvalidClientCertAuthRequest); } } if (jobRequest.HttpAuthType.Equals("None", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(jobRequest.ClientCertPfx) || !string.IsNullOrEmpty(jobRequest.ClientCertPassword)) { throw new InvalidOperationException(Resources.SchedulerInvalidNoneAuthRequest); } } if (jobRequest.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) jobCreateParams.Action.Request.Body = jobRequest.Body; //Populate job error action jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest); jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?); if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null) { jobCreateParams.Recurrence = new JobRecurrence(); jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?); if (!string.IsNullOrEmpty(jobRequest.Frequency)) jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency); jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?); jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?); } JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams); if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase)) schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled }); status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString(); return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()); } /// <summary> /// Creates a Storage Queue Scheduler job /// </summary> /// <param name="jobRequest">Request values</param> /// <param name="status">Status of create action</param> /// <returns>Created Storage Queue Scheduler job</returns> public PSJobDetail CreateStorageJob(PSCreateJobParams jobRequest, out string status) { if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri); JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters { Action = new JobAction { Type = JobActionType.StorageQueue, QueueMessage = new JobQueueMessage { Message = jobRequest.StorageQueueMessage ?? string.Empty, StorageAccountName = jobRequest.StorageAccount, QueueName = jobRequest.QueueName, SasToken = jobRequest.SasToken }, } }; //Populate job error action jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest); jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?); if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null) { jobCreateParams.Recurrence = new JobRecurrence(); jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?); if (!string.IsNullOrEmpty(jobRequest.Frequency)) jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency); jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?); jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?); } JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams); if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase)) schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled }); status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString(); return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()); } #endregion /// <summary> /// Updates given Http Scheduler job /// </summary> /// <param name="jobRequest">Request values</param> /// <param name="status">Status of uodate operation</param> /// <returns>Updated Http Scheduler job</returns> public PSJobDetail PatchHttpJob(PSCreateJobParams jobRequest, out string status) { if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri); //Get Existing job Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job; JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type); JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams); if (!string.IsNullOrEmpty(jobRequest.JobState)) schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled : JobState.Disabled }); status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString(); return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()); } /// <summary> /// If a scheduler job already exists, this will merge the existing job config values with the request /// </summary> /// <param name="job">Existing Scheduler job</param> /// <param name="jobRequest">Request values</param> /// <param name="type">Http or Storage</param> /// <returns>JobCreateOrUpdateParameters object to use when updating Scheduler job</returns> private JobCreateOrUpdateParameters PopulateExistingJobParams(Job job, PSCreateJobParams jobRequest, JobActionType type) { JobCreateOrUpdateParameters jobUpdateParams = new JobCreateOrUpdateParameters(); if (type.Equals(JobActionType.StorageQueue)) { if (jobRequest.IsStorageActionSet()) { jobUpdateParams.Action = new JobAction(); jobUpdateParams.Action.QueueMessage = new JobQueueMessage(); if (job.Action != null) { jobUpdateParams.Action.Type = job.Action.Type; if (job.Action.QueueMessage != null) { jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? job.Action.QueueMessage.Message : jobRequest.StorageQueueMessage; jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName ?? job.Action.QueueMessage.QueueName; jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken ?? job.Action.QueueMessage.SasToken; jobUpdateParams.Action.QueueMessage.StorageAccountName = job.Action.QueueMessage.StorageAccountName; } else if (job.Action.QueueMessage == null) { jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? string.Empty : jobRequest.StorageQueueMessage; jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName; jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken; jobUpdateParams.Action.QueueMessage.StorageAccountName = jobRequest.StorageAccount; } } else { jobUpdateParams.Action.QueueMessage.Message = string.IsNullOrEmpty(jobRequest.StorageQueueMessage) ? string.Empty : jobRequest.StorageQueueMessage; jobUpdateParams.Action.QueueMessage.QueueName = jobRequest.QueueName; jobUpdateParams.Action.QueueMessage.SasToken = jobRequest.SasToken; jobUpdateParams.Action.QueueMessage.StorageAccountName = jobRequest.StorageAccount; } } else { jobUpdateParams.Action = job.Action; } } else //If it is a HTTP job action type { if (jobRequest.IsActionSet()) { jobUpdateParams.Action = new JobAction(); jobUpdateParams.Action.Request = new JobHttpRequest(); if (job.Action != null) { jobUpdateParams.Action.Type = job.Action.Type; if (job.Action.Request != null) { jobUpdateParams.Action.Request.Uri = jobRequest.Uri ?? job.Action.Request.Uri; jobUpdateParams.Action.Request.Method = jobRequest.Method ?? job.Action.Request.Method; jobUpdateParams.Action.Request.Headers = jobRequest.Headers == null ? job.Action.Request.Headers : jobRequest.Headers.ToDictionary(); jobUpdateParams.Action.Request.Body = jobRequest.Body ?? job.Action.Request.Body; //Job has existing authentication if (job.Action.Request.Authentication != null) { if (!string.IsNullOrEmpty(jobRequest.HttpAuthType)) { jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams); } //the new request doesn't have any changes to auth, so preserve it else { jobUpdateParams.Action.Request.Authentication = job.Action.Request.Authentication; } } else if (job.Action.Request.Authentication == null) { jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams); } } else if (job.Action.Request == null) { jobUpdateParams.Action.Request.Uri = jobRequest.Uri; jobUpdateParams.Action.Request.Method = jobRequest.Method; jobUpdateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary(); jobUpdateParams.Action.Request.Body = jobRequest.Body; jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams); } } else { jobUpdateParams.Action.Request.Uri = jobRequest.Uri; jobUpdateParams.Action.Request.Method = jobRequest.Method; jobUpdateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary(); jobUpdateParams.Action.Request.Body = jobRequest.Body; jobUpdateParams.Action.Request.Authentication = SetHttpAuthentication(jobRequest, jobUpdateParams); } } else { jobUpdateParams.Action = job.Action; } } if (jobRequest.IsErrorActionSet()) { jobUpdateParams.Action.ErrorAction = new JobErrorAction(); jobUpdateParams.Action.ErrorAction.Request = new JobHttpRequest(); jobUpdateParams.Action.ErrorAction.QueueMessage = new JobQueueMessage(); if (job.Action.ErrorAction != null) { if (job.Action.ErrorAction.Request != null) { jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri ?? job.Action.ErrorAction.Request.Uri; jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod ?? job.Action.ErrorAction.Request.Method; jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders == null ? job.Action.ErrorAction.Request.Headers : jobRequest.Headers.ToDictionary(); jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody ?? job.Action.ErrorAction.Request.Body; } else if (job.Action.ErrorAction.Request == null) { jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri; jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod; jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary(); jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody; } if (job.Action.ErrorAction.QueueMessage != null) { jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody ?? job.Action.ErrorAction.QueueMessage.Message; jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName ?? job.Action.ErrorAction.QueueMessage.QueueName; jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken ?? job.Action.ErrorAction.QueueMessage.SasToken; jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount ?? job.Action.ErrorAction.QueueMessage.StorageAccountName; } else if (job.Action.ErrorAction.QueueMessage == null) { jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody; jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName; jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken; jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount; } } else if (job.Action.ErrorAction == null) { jobUpdateParams.Action.ErrorAction.Request.Uri = jobRequest.ErrorActionUri; jobUpdateParams.Action.ErrorAction.Request.Method = jobRequest.ErrorActionMethod; jobUpdateParams.Action.ErrorAction.Request.Headers = jobRequest.ErrorActionHeaders.ToDictionary(); jobUpdateParams.Action.ErrorAction.Request.Body = jobRequest.ErrorActionBody; jobUpdateParams.Action.ErrorAction.QueueMessage.Message = jobRequest.ErrorActionQueueBody; jobUpdateParams.Action.ErrorAction.QueueMessage.QueueName = jobRequest.ErrorActionQueueName; jobUpdateParams.Action.ErrorAction.QueueMessage.SasToken = jobRequest.ErrorActionSasToken; jobUpdateParams.Action.ErrorAction.QueueMessage.StorageAccountName = jobRequest.ErrorActionStorageAccount; } } else { jobUpdateParams.Action.ErrorAction = job.Action.ErrorAction; } if (jobRequest.IsRecurrenceSet()) { jobUpdateParams.Recurrence = new JobRecurrence(); if (job.Recurrence != null) { jobUpdateParams.Recurrence.Count = jobRequest.ExecutionCount ?? job.Recurrence.Count; jobUpdateParams.Recurrence.EndTime = jobRequest.EndTime ?? job.Recurrence.EndTime; jobUpdateParams.Recurrence.Frequency = string.IsNullOrEmpty(jobRequest.Frequency) ? job.Recurrence.Frequency : (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency); jobUpdateParams.Recurrence.Interval = jobRequest.Interval ?? job.Recurrence.Interval; jobUpdateParams.Recurrence.Schedule = SetRecurrenceSchedule(job.Recurrence.Schedule); } else if (job.Recurrence == null) { jobUpdateParams.Recurrence.Count = jobRequest.ExecutionCount; jobUpdateParams.Recurrence.EndTime = jobRequest.EndTime; jobUpdateParams.Recurrence.Frequency = string.IsNullOrEmpty(jobRequest.Frequency) ? default(JobRecurrenceFrequency) : (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency); jobUpdateParams.Recurrence.Interval = jobRequest.Interval; jobUpdateParams.Recurrence.Schedule = null; } } else { jobUpdateParams.Recurrence = job.Recurrence; if (jobUpdateParams.Recurrence != null) { jobUpdateParams.Recurrence.Schedule = SetRecurrenceSchedule(job.Recurrence.Schedule); } } jobUpdateParams.Action.RetryPolicy = job.Action.RetryPolicy; jobUpdateParams.StartTime = jobRequest.StartTime ?? job.StartTime; return jobUpdateParams; } private HttpAuthentication SetHttpAuthentication(PSCreateJobParams jobRequest, JobCreateOrUpdateParameters jobUpdateParams) { HttpAuthentication httpAuthentication = null; if (!string.IsNullOrEmpty(jobRequest.HttpAuthType)) { switch (jobRequest.HttpAuthType.ToLower()) { case "clientcertificate": if (jobRequest.ClientCertPfx != null && jobRequest.ClientCertPassword != null) { httpAuthentication = new ClientCertAuthentication { Type = HttpAuthenticationType.ClientCertificate, Password = jobRequest.ClientCertPassword, Pfx = jobRequest.ClientCertPfx }; } else { throw new InvalidOperationException(Resources.SchedulerInvalidClientCertAuthRequest); } break; case "activedirectoryoauth": if (jobRequest.Tenant != null && jobRequest.Audience != null && jobRequest.ClientId != null && jobRequest.Secret != null) { httpAuthentication = new AADOAuthAuthentication { Type = HttpAuthenticationType.ActiveDirectoryOAuth, Tenant = jobRequest.Tenant, Audience = jobRequest.Audience, ClientId = jobRequest.ClientId, Secret = jobRequest.Secret }; } else { throw new InvalidOperationException(Resources.SchedulerInvalidAADOAuthRequest); } break; case "basic": if (jobRequest.Username != null && jobRequest.Password != null) { httpAuthentication = new BasicAuthentication { Type = HttpAuthenticationType.Basic, Username = jobRequest.Username, Password = jobRequest.Password }; } else { throw new InvalidOperationException(Resources.SchedulerInvalidBasicAuthRequest); } break; case "none": if (!string.IsNullOrEmpty(jobRequest.ClientCertPfx) || !string.IsNullOrEmpty(jobRequest.ClientCertPassword) || !string.IsNullOrEmpty(jobRequest.Tenant) || !string.IsNullOrEmpty(jobRequest.Secret) || !string.IsNullOrEmpty(jobRequest.ClientId) || !string.IsNullOrEmpty(jobRequest.Audience) || !string.IsNullOrEmpty(jobRequest.Username) || !string.IsNullOrEmpty(jobRequest.Password)) { throw new InvalidOperationException(Resources.SchedulerInvalidNoneAuthRequest); } break; } } return httpAuthentication; } /// <summary> /// Existing bug in SDK where recurrence counts are set to 0 instead of null /// </summary> /// <param name="jobRecurrenceSchedule">The JobRecurrenceSchedule</param> /// <returns>The JobRecurrenceSchedule</returns> private JobRecurrenceSchedule SetRecurrenceSchedule(JobRecurrenceSchedule jobRecurrenceSchedule) { if (jobRecurrenceSchedule != null) { JobRecurrenceSchedule schedule = new JobRecurrenceSchedule(); schedule.Days = jobRecurrenceSchedule.Days.Count == 0 ? null : jobRecurrenceSchedule.Days; schedule.Hours = jobRecurrenceSchedule.Hours.Count == 0 ? null : jobRecurrenceSchedule.Hours; schedule.Minutes = jobRecurrenceSchedule.Minutes.Count == 0 ? null : jobRecurrenceSchedule.Minutes; schedule.MonthDays = jobRecurrenceSchedule.MonthDays.Count == 0 ? null : jobRecurrenceSchedule.MonthDays; schedule.MonthlyOccurrences = jobRecurrenceSchedule.MonthlyOccurrences.Count == 0 ? null : jobRecurrenceSchedule.MonthlyOccurrences; schedule.Months = jobRecurrenceSchedule.Months.Count == 0 ? null : jobRecurrenceSchedule.Months; return schedule; } else { return null; } } /// <summary> /// Updates given Storage Queue Scheduler job /// </summary> /// <param name="jobRequest">Request values</param> /// <param name="status">Status of uodate operation</param> /// <returns>Updated Storage Queue Scheduler job</returns> public PSJobDetail PatchStorageJob(PSCreateJobParams jobRequest, out string status) { if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase)) throw new Exception(Resources.SchedulerInvalidLocation); SchedulerClient schedulerClient = AzureSession.ClientFactory.CreateCustomClient<SchedulerClient>(jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri); //Get Existing job Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job; JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type); JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams); if (!string.IsNullOrEmpty(jobRequest.JobState)) schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled : JobState.Disabled }); status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString(); return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()); } } }
using System; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Zu.AsyncChromeDriver.Tests.Environment; using Zu.AsyncWebDriver; using Zu.AsyncWebDriver.Remote; using Zu.WebBrowser.AsyncInteractions; using Zu.WebBrowser.BasicTypes; namespace Zu.AsyncChromeDriver.Tests { [TestFixture] [Explicit ("NotImplemented")] public class AlertsTest : DriverTestFixture { [Test] public async Task ShouldBeAbleToOverrideTheWindowAlertMethod() { await driver.GoToUrl(CreateAlertPage("cheese")); await ((IJavaScriptExecutor)driver).ExecuteScript( "window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }"); await driver.FindElement(By.Id("alert")).Click(); } [Test] public async Task ShouldAllowUsersToAcceptAnAlertManually() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", await driver.Title()); } [Test] public async Task ShouldThrowArgumentNullExceptionWhenKeysNull() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); try { //Assert.That(async () => await alert.SendKeys(null), Throws.ArgumentNullException); await AssertEx.ThrowsAsync<ArgumentNullException>(async () => await alert.SendKeys(null)); } finally { await alert.Accept(); } } [Test] public async Task ShouldAllowUsersToAcceptAnAlertWithNoTextManually() { await driver.GoToUrl(CreateAlertPage("")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", await driver.Title()); } [Test] public async Task ShouldAllowUsersToDismissAnAlertManually() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Dismiss(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", await driver.Title()); } [Test] public async Task ShouldAllowAUserToAcceptAPrompt() { await driver.GoToUrl(CreatePromptPage(null)); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Prompt", await driver.Title()); } [Test] public async Task ShouldAllowAUserToDismissAPrompt() { await driver.GoToUrl(CreatePromptPage(null)); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Dismiss(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Prompt", await driver.Title()); } [Test] public async Task ShouldAllowAUserToSetTheValueOfAPrompt() { await driver.GoToUrl(CreatePromptPage(null)); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.SendKeys("cheese"); await alert.Accept(); string result = await driver.FindElement(By.Id("text")).Text(); Assert.AreEqual("cheese", result); } [Test] public async Task ShouldAllowTheUserToGetTheTextOfAnAlert() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); string value = await alert.Text(); await alert.Accept(); Assert.AreEqual("cheese", value); } [Test] public async Task ShouldAllowTheUserToGetTheTextOfAPrompt() { await driver.GoToUrl(CreatePromptPage(null)); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); string value = await alert.Text(); await alert.Accept(); Assert.AreEqual("Enter something", value); } [Test] public async Task AlertShouldNotAllowAdditionalCommandsIfDimissed() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Dismiss(); string text; //Assert.That(async () => text = await alert.Text(), Throws.InstanceOf<NoAlertPresentException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => text = await alert.Text(), exception => Assert.AreEqual("no such element", exception.Error)); } [Test] public async Task ShouldAllowUsersToAcceptAnAlertInAFrame() { string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>")); await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody($"<iframe src='{iframe}' name='iframeWithAlert'></iframe>"))); await driver.SwitchTo().Frame("iframeWithAlert"); await driver.FindElement(By.Id("alertInFrame")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", await driver.Title()); } [Test] public async Task ShouldAllowUsersToAcceptAnAlertInANestedFrame() { string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>")); string iframe2 = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody($"<iframe src='{iframe}' name='iframeWithAlert'></iframe>")); await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody($"<iframe src='{iframe2}' name='iframeWithIframe'></iframe>"))); await driver.SwitchTo().Frame("iframeWithIframe").SwitchTo().Frame("iframeWithAlert"); await driver.FindElement(By.Id("alertInFrame")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", await driver.Title()); } [Test] public async Task SwitchingToMissingAlertThrows() { await driver.GoToUrl(CreateAlertPage("cheese")); //Assert.That(async () => await AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await AlertToBePresent(), exception => Assert.AreEqual("no such element", exception.Error)); } [Test] public async Task SwitchingToMissingAlertInAClosedWindowThrows() { string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()); await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody($"<a id='open-new-window' href='{blank}' target='newwindow'>open new window</a>"))); string mainWindow = await driver.CurrentWindowHandle(); try { await driver.FindElement(By.Id("open-new-window")).Click(); await WaitFor(WindowHandleCountToBe(2), "Window count was not 2"); await WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'"); await driver.Close(); await WaitFor(WindowHandleCountToBe(1), "Window count was not 1"); try { await (await AlertToBePresent()).Accept(); Assert.Fail("Expected exception"); } catch (NoSuchWindowException) { // Expected } } finally { await driver.SwitchTo().Window(mainWindow); await WaitFor(ElementTextToEqual(await driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'"); } } [Test] public async Task PromptShouldUseDefaultValueIfNoKeysSent() { await driver.GoToUrl(CreatePromptPage("This is a default value")); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); IWebElement element = await driver.FindElement(By.Id("text")); await WaitFor(ElementTextToEqual(element, "This is a default value"), "Element text was not 'This is a default value'"); Assert.AreEqual("This is a default value", await element.Text()); } [Test] public async Task PromptShouldHaveNullValueIfDismissed() { await driver.GoToUrl(CreatePromptPage("This is a default value")); await driver.FindElement(By.Id("prompt")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Dismiss(); IWebElement element = await driver.FindElement(By.Id("text")); await WaitFor(ElementTextToEqual(element, "null"), "Element text was not 'null'"); Assert.AreEqual("null", await element.Text()); } [Test] public async Task HandlesTwoAlertsFromOneInteraction() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithScripts( "function setInnerText(id, value) {", " document.getElementById(id).innerHTML = '<p>' + value + '</p>';", "}", "function displayTwoPrompts() {", " setInnerText('text1', prompt('First'));", " setInnerText('text2', prompt('Second'));", "}") .WithBody( "<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>", "<div id='text1'></div>", "<div id='text2'></div>"))); await driver.FindElement(By.Id("double-prompt")).Click(); IAlert alert1 = await WaitFor(AlertToBePresent(), "No alert found"); await alert1.SendKeys("brie"); await alert1.Accept(); IAlert alert2 = await WaitFor(AlertToBePresent(), "No alert found"); await alert2.SendKeys("cheddar"); await alert2.Accept(); IWebElement element1 = await driver.FindElement(By.Id("text1")); await WaitFor(ElementTextToEqual(element1, "brie"), "Element text was not 'brie'"); Assert.AreEqual("brie", await element1.Text()); IWebElement element2 = await driver.FindElement(By.Id("text2")); await WaitFor(ElementTextToEqual(element2, "cheddar"), "Element text was not 'cheddar'"); Assert.AreEqual("cheddar", await element2.Text()); } [Test] public async Task ShouldHandleAlertOnPageLoad() { string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnLoad("javascript:alert(\"onload\")") .WithBody("<p>Page with onload event handler</p>")); await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)))); await driver.FindElement(By.Id("open-page-with-onload-alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); string value = await alert.Text(); await alert.Accept(); Assert.AreEqual("onload", value); IWebElement element = await driver.FindElement(By.TagName("p")); await WaitFor(ElementTextToEqual(element, "Page with onload event handler"), "Element text was not 'Page with onload event handler'"); } [Test] public async Task ShouldHandleAlertOnPageLoadUsingGet() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnLoad("javascript:alert(\"onload\")") .WithBody("<p>Page with onload event handler</p>"))); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); string value = await alert.Text(); await alert.Accept(); Assert.AreEqual("onload", value); await WaitFor(ElementTextToEqual(await driver.FindElement(By.TagName("p")), "Page with onload event handler"), "Could not find element with text 'Page with onload event handler'"); } [Test] public async Task CanQuitWhenAnAlertIsPresent() { await driver.GoToUrl(CreateAlertPage("cheese")); await driver.FindElement(By.Id("alert")).Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); EnvironmentManager.Instance.CloseCurrentDriver(); } [Test] public async Task ShouldHandleAlertOnFormSubmit() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts"). WithBody("<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>", "<input id='unused' type='submit' value='Submit'>", "</form>"))); IWebElement element = await driver.FindElement(By.Id("theForm")); await element.Submit(); IAlert alert = await driver.SwitchTo().Alert(); string text = await alert.Text(); await alert.Accept(); Assert.AreEqual("Tasty cheese", text); Assert.AreEqual("Testing Alerts", await driver.Title()); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public async Task ShouldHandleAlertOnPageBeforeUnload() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html")); IWebElement element = await driver.FindElement(By.Id("navigate")); await element.Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Dismiss(); Assert.That(await driver.GetUrl(), Does.Contain("pageWithOnBeforeUnloadMessage.html")); // Can't move forward or even quit the driver // until the alert is accepted. await element.Click(); alert = await WaitFor(AlertToBePresent(), "No alert found"); await alert.Accept(); await WaitFor(async () => await driver.GetUrl().Contains(alertsPage), "Browser URL does not contain " + alertsPage); Assert.That(await driver.GetUrl(), Does.Contain(alertsPage)); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] public async Task ShouldHandleAlertOnPageBeforeUnloadAlertAtQuit() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html")); IWebElement element = await driver.FindElement(By.Id("navigate")); await element.Click(); IAlert alert = await WaitFor(AlertToBePresent(), "No alert found"); await driver.Quit(); driver = null; } private Task<IAlert> AlertToBePresent() { return driver.SwitchTo().Alert(); } private string CreateAlertPage(string alertText) { return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody("<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>")); } private string CreatePromptPage(string defaultText) { return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Prompt") .WithScripts( "function setInnerText(id, value) {", " document.getElementById(id).innerHTML = '<p>' + value + '</p>';", "}", defaultText == null ? "function displayPrompt() { setInnerText('text', prompt('Enter something')); }" : "function displayPrompt() { setInnerText('text', prompt('Enter something', '" + defaultText + "')); }") .WithBody( "<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>", "<div id='text'>acceptor</div>")); } private async Task SetSimpleOnBeforeUnload(string returnText) { await ((IJavaScriptExecutor)driver).ExecuteScript( "var returnText = arguments[0]; window.onbeforeunload = function() { return returnText; }", new CancellationToken(), returnText); } private Func<Task<IWebElement>> ElementToBePresent(By locator) { return async () => { IWebElement foundElement = null; try { foundElement = await driver.FindElement(By.Id("open-page-with-onunload-alert")); } catch (NoSuchElementException) { } return foundElement; }; } private Func<Task<bool>> ElementTextToEqual(IWebElement element, string text) { return async () => await element.Text() == text; } private Func<Task<bool>> WindowWithName(string name) { return async () => { try { await driver.SwitchTo().Window(name); return true; } catch (NoSuchWindowException) { } return false; }; } private Func<Task<bool>> WindowHandleCountToBe(int count) { return async () => await driver.WindowHandles().Count() == count; } } }
using System; using System.Collections.Generic; using fNbt; using fNbt.Serialization; using TrueCraft.API.World; using TrueCraft.API; using TrueCraft.Core.Logic.Blocks; namespace TrueCraft.Core.World { public class Chunk : INbtSerializable, IChunk { public const int Width = 16, Height = 128, Depth = 16; [NbtIgnore] public DateTime LastAccessed { get; set; } [NbtIgnore] public bool IsModified { get; set; } [NbtIgnore] public byte[] Blocks { get; set; } [NbtIgnore] public NibbleArray Metadata { get; set; } [NbtIgnore] public NibbleArray BlockLight { get; set; } [NbtIgnore] public NibbleArray SkyLight { get; set; } public byte[] Biomes { get; set; } public int[] HeightMap { get; set; } [TagName("xPos")] public int X { get; set; } [TagName("zPos")] public int Z { get; set; } public Dictionary<Coordinates3D, NbtCompound> TileEntities { get; set; } public Coordinates2D Coordinates { get { return new Coordinates2D(X, Z); } set { X = value.X; Z = value.Z; } } public long LastUpdate { get; set; } public bool TerrainPopulated { get; set; } [NbtIgnore] public Region ParentRegion { get; set; } public Chunk() { TerrainPopulated = true; Biomes = new byte[Width * Depth]; HeightMap = new int[Width * Depth]; TileEntities = new Dictionary<Coordinates3D, NbtCompound>(); } public Chunk(Coordinates2D coordinates) : this() { X = coordinates.X; Z = coordinates.Z; const int size = Width * Height * Depth; Blocks = new byte[size]; Metadata = new NibbleArray(size); BlockLight = new NibbleArray(size); SkyLight = new NibbleArray(size); for (int i = 0; i < size; i++) SkyLight[i] = 0xFF; } public byte GetBlockID(Coordinates3D coordinates) { int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return Blocks[index]; } public byte GetMetadata(Coordinates3D coordinates) { int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return Metadata[index]; } public byte GetSkyLight(Coordinates3D coordinates) { int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return SkyLight[index]; } public byte GetBlockLight(Coordinates3D coordinates) { int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return BlockLight[index]; } /// <summary> /// Sets the block ID at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetBlockID(Coordinates3D coordinates, byte value) { IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); Blocks[index] = value; if (value == AirBlock.BlockID) Metadata[index] = 0x0; var oldHeight = GetHeight((byte)coordinates.X, (byte)coordinates.Z); if (value == AirBlock.BlockID) { if (oldHeight <= coordinates.Y) { // Shift height downwards while (coordinates.Y > 0) { coordinates.Y--; if (GetBlockID(coordinates) != 0) SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y); } } } else { if (oldHeight < coordinates.Y) SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y); } } /// <summary> /// Sets the metadata at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetMetadata(Coordinates3D coordinates, byte value) { IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); Metadata[index] = value; } /// <summary> /// Sets the sky light at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetSkyLight(Coordinates3D coordinates, byte value) { IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); SkyLight[index] = value; } /// <summary> /// Sets the block light at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetBlockLight(Coordinates3D coordinates, byte value) { IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); BlockLight[index] = value; } /// <summary> /// Gets the tile entity for the given coordinates. May return null. /// </summary> public NbtCompound GetTileEntity(Coordinates3D coordinates) { if (TileEntities.ContainsKey(coordinates)) return TileEntities[coordinates]; return null; } /// <summary> /// Sets the tile entity at the given coordinates to the given value. /// </summary> public void SetTileEntity(Coordinates3D coordinates, NbtCompound value) { if (value == null && TileEntities.ContainsKey(coordinates)) TileEntities.Remove(coordinates); else TileEntities[coordinates] = value; IsModified = true; } /// <summary> /// Gets the height of the specified column. /// </summary> public int GetHeight(byte x, byte z) { return HeightMap[(x * Width) + z]; } private void SetHeight(byte x, byte z, int value) { IsModified = true; HeightMap[(x * Width) + z] = value; } public void UpdateHeightMap() { for (byte x = 0; x < Chunk.Width; x++) { for (byte z = 0; z < Chunk.Depth; z++) { int y; for (y = Chunk.Height - 1; y >= 0; y--) { int index = y + (z * Height) + (x * Height * Width); if (Blocks[index] != 0) { SetHeight(x, z, y); break; } } if (y == 0) SetHeight(x, z, 0); } } } public NbtFile ToNbt() { var serializer = new NbtSerializer(typeof(Chunk)); var compound = serializer.Serialize(this, "Level") as NbtCompound; var file = new NbtFile(); file.RootTag.Add(compound); return file; } public static Chunk FromNbt(NbtFile nbt) { var serializer = new NbtSerializer(typeof(Chunk)); var chunk = (Chunk)serializer.Deserialize(nbt.RootTag["Level"]); return chunk; } public NbtTag Serialize(string tagName) { var chunk = new NbtCompound(tagName); var entities = new NbtList("Entities", NbtTagType.Compound); chunk.Add(entities); chunk.Add(new NbtInt("X", X)); chunk.Add(new NbtInt("Z", Z)); chunk.Add(new NbtByteArray("Blocks", Blocks)); chunk.Add(new NbtByteArray("Data", Metadata.Data)); chunk.Add(new NbtByteArray("SkyLight", SkyLight.Data)); chunk.Add(new NbtByteArray("BlockLight", BlockLight.Data)); var tiles = new NbtList("TileEntities", NbtTagType.Compound); foreach (var kvp in TileEntities) { var c = new NbtCompound(); c.Add(new NbtList("coordinates", new[] { new NbtInt(kvp.Key.X), new NbtInt(kvp.Key.Y), new NbtInt(kvp.Key.Z) })); c.Add(new NbtList("value", new[] { kvp.Value })); tiles.Add(c); } chunk.Add(tiles); // TODO: Entities return chunk; } public void Deserialize(NbtTag value) { var chunk = new Chunk(); var tag = (NbtCompound)value; Biomes = chunk.Biomes; HeightMap = chunk.HeightMap; LastUpdate = chunk.LastUpdate; TerrainPopulated = chunk.TerrainPopulated; X = tag["X"].IntValue; Z = tag["Z"].IntValue; Blocks = tag["Blocks"].ByteArrayValue; Metadata = new NibbleArray(); Metadata.Data = tag["Data"].ByteArrayValue; BlockLight = new NibbleArray(); BlockLight.Data = tag["BlockLight"].ByteArrayValue; SkyLight = new NibbleArray(); SkyLight.Data = tag["SkyLight"].ByteArrayValue; if (tag.Contains("TileEntities")) { foreach (var entity in tag["TileEntities"] as NbtList) { TileEntities[new Coordinates3D(entity["coordinates"][0].IntValue, entity["coordinates"][1].IntValue, entity["coordinates"][2].IntValue)] = entity["value"][0] as NbtCompound; } } // TODO: Entities } } }
// ------------------------------------------------------------------ // CaptureTest.cs // Sample application to show the DirectX.Capture class library. // // History: // 2003-Jan-25 BL - created // // Copyright (c) 2003 Brian Low // ------------------------------------------------------------------ using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using DirectX.Capture; using Microsoft.VisualBasic; using OpenCvSharp; namespace CaptureTest { public class CaptureTest : System.Windows.Forms.Form { private Capture capture = null; private Filters filters = new Filters(); private System.Windows.Forms.TextBox txtFilename; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.Button btnStop; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem7; private System.Windows.Forms.MainMenu mainMenu; private System.Windows.Forms.MenuItem mnuExit; private System.Windows.Forms.MenuItem mnuDevices; private System.Windows.Forms.MenuItem mnuVideoDevices; private System.Windows.Forms.MenuItem mnuAudioDevices; private System.Windows.Forms.MenuItem mnuVideoCompressors; private System.Windows.Forms.MenuItem mnuAudioCompressors; private System.Windows.Forms.MenuItem mnuVideoSources; private System.Windows.Forms.MenuItem mnuAudioSources; private System.Windows.Forms.Panel panelVideo; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.MenuItem mnuAudioChannels; private System.Windows.Forms.MenuItem mnuAudioSamplingRate; private System.Windows.Forms.MenuItem mnuAudioSampleSizes; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem mnuFrameSizes; private System.Windows.Forms.MenuItem mnuFrameRates; private System.Windows.Forms.Button btnCue; private System.Windows.Forms.MenuItem menuItem6; private System.Windows.Forms.MenuItem mnuPreview; private System.Windows.Forms.MenuItem menuItem8; private System.Windows.Forms.MenuItem mnuPropertyPages; private System.Windows.Forms.MenuItem mnuVideoCaps; private System.Windows.Forms.MenuItem mnuAudioCaps; private System.Windows.Forms.MenuItem mnuChannel; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem mnuInputType; private Button bCaptureFrame; private SplitContainer spMain; private IContainer components; public CaptureTest() { // // Required for Windows Form Designer support // InitializeComponent(); // Start with the first video/audio devices // Don't do this in the Release build in case the // first devices cause problems. capture = new Capture(filters.VideoInputDevices[0], filters.AudioInputDevices[0]); Load += new EventHandler(CaptureTest_Load); FormClosing += new FormClosingEventHandler(CaptureTest_FormClosing); // Update the main menu // Much of the interesting work of this sample occurs here try { updateMenu(); } catch { } } void CaptureTest_Load(object sender, EventArgs e) { capture.FrameCaptureComplete += new DirectX.Capture.Capture.FrameCapHandler(capture_FrameCaptureComplete); capture.PreviewWindow = panelVideo; mnuPreview.Checked = true; } void CaptureTest_FormClosing(object sender, FormClosingEventArgs e) { if (capture != null) { capture.Stop(); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.txtFilename = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.btnStart = new System.Windows.Forms.Button(); this.btnStop = new System.Windows.Forms.Button(); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.mnuExit = new System.Windows.Forms.MenuItem(); this.mnuDevices = new System.Windows.Forms.MenuItem(); this.mnuVideoDevices = new System.Windows.Forms.MenuItem(); this.mnuAudioDevices = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.mnuVideoCompressors = new System.Windows.Forms.MenuItem(); this.mnuAudioCompressors = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.mnuVideoSources = new System.Windows.Forms.MenuItem(); this.mnuFrameSizes = new System.Windows.Forms.MenuItem(); this.mnuFrameRates = new System.Windows.Forms.MenuItem(); this.mnuVideoCaps = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.mnuAudioSources = new System.Windows.Forms.MenuItem(); this.mnuAudioChannels = new System.Windows.Forms.MenuItem(); this.mnuAudioSamplingRate = new System.Windows.Forms.MenuItem(); this.mnuAudioSampleSizes = new System.Windows.Forms.MenuItem(); this.mnuAudioCaps = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.mnuChannel = new System.Windows.Forms.MenuItem(); this.mnuInputType = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.mnuPropertyPages = new System.Windows.Forms.MenuItem(); this.menuItem8 = new System.Windows.Forms.MenuItem(); this.mnuPreview = new System.Windows.Forms.MenuItem(); this.panelVideo = new System.Windows.Forms.Panel(); this.btnCue = new System.Windows.Forms.Button(); this.bCaptureFrame = new System.Windows.Forms.Button(); this.spMain = new System.Windows.Forms.SplitContainer(); this.spMain.Panel1.SuspendLayout(); this.spMain.SuspendLayout(); this.SuspendLayout(); // // txtFilename // this.txtFilename.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.txtFilename.Location = new System.Drawing.Point(72, 524); this.txtFilename.Name = "txtFilename"; this.txtFilename.Size = new System.Drawing.Size(192, 20); this.txtFilename.TabIndex = 0; this.txtFilename.Text = "c:\\test.avi"; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.Location = new System.Drawing.Point(8, 527); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(64, 16); this.label1.TabIndex = 1; this.label1.Text = "Filename:"; // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnStart.Location = new System.Drawing.Point(2, 484); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(63, 21); this.btnStart.TabIndex = 2; this.btnStart.Text = "Start"; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // btnStop // this.btnStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnStop.Location = new System.Drawing.Point(115, 484); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(62, 21); this.btnStop.TabIndex = 3; this.btnStop.Text = "Stop"; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.mnuDevices, this.menuItem7}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuExit}); this.menuItem1.Text = "File"; // // mnuExit // this.mnuExit.Index = 0; this.mnuExit.Text = "E&xit"; this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); // // mnuDevices // this.mnuDevices.Index = 1; this.mnuDevices.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuVideoDevices, this.mnuAudioDevices, this.menuItem4, this.mnuVideoCompressors, this.mnuAudioCompressors}); this.mnuDevices.Text = "Devices"; // // mnuVideoDevices // this.mnuVideoDevices.Index = 0; this.mnuVideoDevices.Text = "Video Devices"; // // mnuAudioDevices // this.mnuAudioDevices.Index = 1; this.mnuAudioDevices.Text = "Audio Devices"; // // menuItem4 // this.menuItem4.Index = 2; this.menuItem4.Text = "-"; // // mnuVideoCompressors // this.mnuVideoCompressors.Index = 3; this.mnuVideoCompressors.Text = "Video Compressors"; // // mnuAudioCompressors // this.mnuAudioCompressors.Index = 4; this.mnuAudioCompressors.Text = "Audio Compressors"; // // menuItem7 // this.menuItem7.Index = 2; this.menuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuVideoSources, this.mnuFrameSizes, this.mnuFrameRates, this.mnuVideoCaps, this.menuItem5, this.mnuAudioSources, this.mnuAudioChannels, this.mnuAudioSamplingRate, this.mnuAudioSampleSizes, this.mnuAudioCaps, this.menuItem3, this.mnuChannel, this.mnuInputType, this.menuItem6, this.mnuPropertyPages, this.menuItem8, this.mnuPreview}); this.menuItem7.Text = "Options"; // // mnuVideoSources // this.mnuVideoSources.Index = 0; this.mnuVideoSources.Text = "Video Sources"; // // mnuFrameSizes // this.mnuFrameSizes.Index = 1; this.mnuFrameSizes.Text = "Video Frame Size"; // // mnuFrameRates // this.mnuFrameRates.Index = 2; this.mnuFrameRates.Text = "Video Frame Rate"; this.mnuFrameRates.Click += new System.EventHandler(this.mnuFrameRates_Click); // // mnuVideoCaps // this.mnuVideoCaps.Index = 3; this.mnuVideoCaps.Text = "Video Capabilities..."; this.mnuVideoCaps.Click += new System.EventHandler(this.mnuVideoCaps_Click); // // menuItem5 // this.menuItem5.Index = 4; this.menuItem5.Text = "-"; // // mnuAudioSources // this.mnuAudioSources.Index = 5; this.mnuAudioSources.Text = "Audio Sources"; // // mnuAudioChannels // this.mnuAudioChannels.Index = 6; this.mnuAudioChannels.Text = "Audio Channels"; // // mnuAudioSamplingRate // this.mnuAudioSamplingRate.Index = 7; this.mnuAudioSamplingRate.Text = "Audio Sampling Rate"; // // mnuAudioSampleSizes // this.mnuAudioSampleSizes.Index = 8; this.mnuAudioSampleSizes.Text = "Audio Sample Size"; // // mnuAudioCaps // this.mnuAudioCaps.Index = 9; this.mnuAudioCaps.Text = "Audio Capabilities..."; this.mnuAudioCaps.Click += new System.EventHandler(this.mnuAudioCaps_Click); // // menuItem3 // this.menuItem3.Index = 10; this.menuItem3.Text = "-"; // // mnuChannel // this.mnuChannel.Index = 11; this.mnuChannel.Text = "TV Tuner Channel"; // // mnuInputType // this.mnuInputType.Index = 12; this.mnuInputType.Text = "TV Tuner Input Type"; this.mnuInputType.Click += new System.EventHandler(this.mnuInputType_Click); // // menuItem6 // this.menuItem6.Index = 13; this.menuItem6.Text = "-"; // // mnuPropertyPages // this.mnuPropertyPages.Index = 14; this.mnuPropertyPages.Text = "PropertyPages"; // // menuItem8 // this.menuItem8.Index = 15; this.menuItem8.Text = "-"; // // mnuPreview // this.mnuPreview.Index = 16; this.mnuPreview.Text = "Preview"; this.mnuPreview.Click += new System.EventHandler(this.mnuPreview_Click); // // panelVideo // this.panelVideo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panelVideo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panelVideo.Location = new System.Drawing.Point(0, 0); this.panelVideo.Name = "panelVideo"; this.panelVideo.Size = new System.Drawing.Size(177, 142); this.panelVideo.TabIndex = 6; // // btnCue // this.btnCue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCue.Location = new System.Drawing.Point(115, 457); this.btnCue.Name = "btnCue"; this.btnCue.Size = new System.Drawing.Size(62, 21); this.btnCue.TabIndex = 8; this.btnCue.Text = "Cue"; this.btnCue.Click += new System.EventHandler(this.btnCue_Click); // // bCaptureFrame // this.bCaptureFrame.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.bCaptureFrame.Location = new System.Drawing.Point(3, 457); this.bCaptureFrame.Name = "bCaptureFrame"; this.bCaptureFrame.Size = new System.Drawing.Size(63, 21); this.bCaptureFrame.TabIndex = 9; this.bCaptureFrame.Text = "Capture"; this.bCaptureFrame.UseVisualStyleBackColor = true; this.bCaptureFrame.Click += new System.EventHandler(this.bCaptureFrame_Click); // // spMain // this.spMain.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.spMain.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.spMain.Location = new System.Drawing.Point(10, 11); this.spMain.Name = "spMain"; // // spMain.Panel1 // this.spMain.Panel1.Controls.Add(this.panelVideo); this.spMain.Panel1.Controls.Add(this.btnStop); this.spMain.Panel1.Controls.Add(this.btnCue); this.spMain.Panel1.Controls.Add(this.btnStart); this.spMain.Panel1.Controls.Add(this.bCaptureFrame); this.spMain.Size = new System.Drawing.Size(1046, 508); this.spMain.SplitterDistance = 180; this.spMain.TabIndex = 10; // // CaptureTest // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(1066, 551); this.Controls.Add(this.spMain); this.Controls.Add(this.label1); this.Controls.Add(this.txtFilename); this.Menu = this.mainMenu; this.Name = "CaptureTest"; this.Text = "CaptureTest"; this.spMain.Panel1.ResumeLayout(false); this.spMain.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { AppDomain currentDomain = AppDomain.CurrentDomain; Application.Run(new CaptureTest()); } private void btnCue_Click(object sender, System.EventArgs e) { try { if (capture == null) throw new ApplicationException("Please select a video and/or audio device."); if (!capture.Cued) capture.Filename = txtFilename.Text; capture.Cue(); btnCue.Enabled = false; MessageBox.Show( string.Concat( "Ready to capture.\n\nUse Cue() before Start() to ", "do all the preparation work that needs to be done to start a ", "capture. Now, when you click Start the capture will begin faster ", "than if you had just clicked Start. Using Cue() is completely ", "optional. The downside to using Cue() is the preview is disabled until ", "the capture begins." ) ); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.ToString()); } } private void btnStart_Click(object sender, System.EventArgs e) { try { if (capture == null) throw new ApplicationException("Please select a video and/or audio device."); if (!capture.Cued) capture.Filename = txtFilename.Text; capture.Start(); btnCue.Enabled = false; btnStart.Enabled = false; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.ToString()); } } private void btnStop_Click(object sender, System.EventArgs e) { try { if (capture == null) throw new ApplicationException("Please select a video and/or audio device."); capture.Stop(); btnCue.Enabled = true; btnStart.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.ToString()); } } private void updateMenu() { MenuItem m; Filter f; Source s; Source current; PropertyPage p; Control oldPreviewWindow = null; // Disable preview to avoid additional flashes (optional) if (capture != null) { oldPreviewWindow = capture.PreviewWindow; capture.PreviewWindow = null; } // Load video devices Filter videoDevice = null; if (capture != null) videoDevice = capture.VideoDevice; mnuVideoDevices.MenuItems.Clear(); m = new MenuItem("(None)", new EventHandler(mnuVideoDevices_Click)); m.Checked = (videoDevice == null); mnuVideoDevices.MenuItems.Add(m); for (int c = 0; c < filters.VideoInputDevices.Count; c++) { f = filters.VideoInputDevices[c]; m = new MenuItem(f.Name, new EventHandler(mnuVideoDevices_Click)); m.Checked = (videoDevice == f); mnuVideoDevices.MenuItems.Add(m); } mnuVideoDevices.Enabled = (filters.VideoInputDevices.Count > 0); // Load audio devices Filter audioDevice = null; if (capture != null) audioDevice = capture.AudioDevice; mnuAudioDevices.MenuItems.Clear(); m = new MenuItem("(None)", new EventHandler(mnuAudioDevices_Click)); m.Checked = (audioDevice == null); mnuAudioDevices.MenuItems.Add(m); for (int c = 0; c < filters.AudioInputDevices.Count; c++) { f = filters.AudioInputDevices[c]; m = new MenuItem(f.Name, new EventHandler(mnuAudioDevices_Click)); m.Checked = (audioDevice == f); mnuAudioDevices.MenuItems.Add(m); } mnuAudioDevices.Enabled = (filters.AudioInputDevices.Count > 0); // Load video compressors try { mnuVideoCompressors.MenuItems.Clear(); m = new MenuItem("(None)", new EventHandler(mnuVideoCompressors_Click)); m.Checked = (capture.VideoCompressor == null); mnuVideoCompressors.MenuItems.Add(m); for (int c = 0; c < filters.VideoCompressors.Count; c++) { f = filters.VideoCompressors[c]; m = new MenuItem(f.Name, new EventHandler(mnuVideoCompressors_Click)); m.Checked = (capture.VideoCompressor == f); mnuVideoCompressors.MenuItems.Add(m); } mnuVideoCompressors.Enabled = ((capture.VideoDevice != null) && (filters.VideoCompressors.Count > 0)); } catch { mnuVideoCompressors.Enabled = false; } // Load audio compressors try { mnuAudioCompressors.MenuItems.Clear(); m = new MenuItem("(None)", new EventHandler(mnuAudioCompressors_Click)); m.Checked = (capture.AudioCompressor == null); mnuAudioCompressors.MenuItems.Add(m); for (int c = 0; c < filters.AudioCompressors.Count; c++) { f = filters.AudioCompressors[c]; m = new MenuItem(f.Name, new EventHandler(mnuAudioCompressors_Click)); m.Checked = (capture.AudioCompressor == f); mnuAudioCompressors.MenuItems.Add(m); } mnuAudioCompressors.Enabled = ((capture.AudioDevice != null) && (filters.AudioCompressors.Count > 0)); } catch { mnuAudioCompressors.Enabled = false; } // Load video sources try { mnuVideoSources.MenuItems.Clear(); current = capture.VideoSource; for (int c = 0; c < capture.VideoSources.Count; c++) { s = capture.VideoSources[c]; m = new MenuItem(s.Name, new EventHandler(mnuVideoSources_Click)); m.Checked = (current == s); mnuVideoSources.MenuItems.Add(m); } mnuVideoSources.Enabled = (capture.VideoSources.Count > 0); } catch { mnuVideoSources.Enabled = false; } // Load audio sources try { mnuAudioSources.MenuItems.Clear(); current = capture.AudioSource; for (int c = 0; c < capture.AudioSources.Count; c++) { s = capture.AudioSources[c]; m = new MenuItem(s.Name, new EventHandler(mnuAudioSources_Click)); m.Checked = (current == s); mnuAudioSources.MenuItems.Add(m); } mnuAudioSources.Enabled = (capture.AudioSources.Count > 0); } catch { mnuAudioSources.Enabled = false; } // Load frame rates try { mnuFrameRates.MenuItems.Clear(); int frameRate = (int)(capture.FrameRate * 1000); m = new MenuItem("15 fps", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 15000); mnuFrameRates.MenuItems.Add(m); m = new MenuItem("24 fps (Film)", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 24000); mnuFrameRates.MenuItems.Add(m); m = new MenuItem("25 fps (PAL)", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 25000); mnuFrameRates.MenuItems.Add(m); m = new MenuItem("29.997 fps (NTSC)", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 29997); mnuFrameRates.MenuItems.Add(m); m = new MenuItem("30 fps (~NTSC)", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 30000); mnuFrameRates.MenuItems.Add(m); m = new MenuItem("59.994 fps (2xNTSC)", new EventHandler(mnuFrameRates_Click)); m.Checked = (frameRate == 59994); mnuFrameRates.MenuItems.Add(m); mnuFrameRates.Enabled = true; } catch { mnuFrameRates.Enabled = false; } // Load frame sizes try { mnuFrameSizes.MenuItems.Clear(); Size frameSize = capture.FrameSize; m = new MenuItem("160 x 120", new EventHandler(mnuFrameSizes_Click)); m.Checked = (frameSize == new Size(160, 120)); mnuFrameSizes.MenuItems.Add(m); m = new MenuItem("320 x 240", new EventHandler(mnuFrameSizes_Click)); m.Checked = (frameSize == new Size(320, 240)); mnuFrameSizes.MenuItems.Add(m); m = new MenuItem("640 x 480", new EventHandler(mnuFrameSizes_Click)); m.Checked = (frameSize == new Size(640, 480)); mnuFrameSizes.MenuItems.Add(m); m = new MenuItem("1024 x 768", new EventHandler(mnuFrameSizes_Click)); m.Checked = (frameSize == new Size(1024, 768)); mnuFrameSizes.MenuItems.Add(m); mnuFrameSizes.Enabled = true; } catch { mnuFrameSizes.Enabled = false; } // Load audio channels try { mnuAudioChannels.MenuItems.Clear(); short audioChannels = capture.AudioChannels; m = new MenuItem("Mono", new EventHandler(mnuAudioChannels_Click)); m.Checked = (audioChannels == 1); mnuAudioChannels.MenuItems.Add(m); m = new MenuItem("Stereo", new EventHandler(mnuAudioChannels_Click)); m.Checked = (audioChannels == 2); mnuAudioChannels.MenuItems.Add(m); mnuAudioChannels.Enabled = true; } catch { mnuAudioChannels.Enabled = false; } // Load audio sampling rate try { mnuAudioSamplingRate.MenuItems.Clear(); int samplingRate = capture.AudioSamplingRate; m = new MenuItem("8 kHz", new EventHandler(mnuAudioSamplingRate_Click)); m.Checked = (samplingRate == 8000); mnuAudioSamplingRate.MenuItems.Add(m); m = new MenuItem("11.025 kHz", new EventHandler(mnuAudioSamplingRate_Click)); m.Checked = (capture.AudioSamplingRate == 11025); mnuAudioSamplingRate.MenuItems.Add(m); m = new MenuItem("22.05 kHz", new EventHandler(mnuAudioSamplingRate_Click)); m.Checked = (capture.AudioSamplingRate == 22050); mnuAudioSamplingRate.MenuItems.Add(m); m = new MenuItem("44.1 kHz", new EventHandler(mnuAudioSamplingRate_Click)); m.Checked = (capture.AudioSamplingRate == 44100); mnuAudioSamplingRate.MenuItems.Add(m); mnuAudioSamplingRate.Enabled = true; } catch { mnuAudioSamplingRate.Enabled = false; } // Load audio sample sizes try { mnuAudioSampleSizes.MenuItems.Clear(); short sampleSize = capture.AudioSampleSize; m = new MenuItem("8 bit", new EventHandler(mnuAudioSampleSizes_Click)); m.Checked = (sampleSize == 8); mnuAudioSampleSizes.MenuItems.Add(m); m = new MenuItem("16 bit", new EventHandler(mnuAudioSampleSizes_Click)); m.Checked = (sampleSize == 16); mnuAudioSampleSizes.MenuItems.Add(m); mnuAudioSampleSizes.Enabled = true; } catch { mnuAudioSampleSizes.Enabled = false; } // Load property pages try { mnuPropertyPages.MenuItems.Clear(); for (int c = 0; c < capture.PropertyPages.Count; c++) { p = capture.PropertyPages[c]; m = new MenuItem(p.Name + "...", new EventHandler(mnuPropertyPages_Click)); mnuPropertyPages.MenuItems.Add(m); } mnuPropertyPages.Enabled = (capture.PropertyPages.Count > 0); } catch { mnuPropertyPages.Enabled = false; } // Load TV Tuner channels try { mnuChannel.MenuItems.Clear(); int channel = capture.Tuner.Channel; for (int c = 1; c <= 25; c++) { m = new MenuItem(c.ToString(), new EventHandler(mnuChannel_Click)); m.Checked = (channel == c); mnuChannel.MenuItems.Add(m); } mnuChannel.Enabled = true; } catch { mnuChannel.Enabled = false; } // Load TV Tuner input types try { mnuInputType.MenuItems.Clear(); m = new MenuItem(TunerInputType.Cable.ToString(), new EventHandler(mnuInputType_Click)); m.Checked = (capture.Tuner.InputType == TunerInputType.Cable); mnuInputType.MenuItems.Add(m); m = new MenuItem(TunerInputType.Antenna.ToString(), new EventHandler(mnuInputType_Click)); m.Checked = (capture.Tuner.InputType == TunerInputType.Antenna); mnuInputType.MenuItems.Add(m); mnuInputType.Enabled = true; } catch { mnuInputType.Enabled = false; } // Enable/disable caps mnuVideoCaps.Enabled = ((capture != null) && (capture.VideoCaps != null)); mnuAudioCaps.Enabled = ((capture != null) && (capture.AudioCaps != null)); // Check Preview menu option mnuPreview.Checked = (oldPreviewWindow != null); mnuPreview.Enabled = (capture != null); // Reenable preview if it was enabled before if (capture != null) capture.PreviewWindow = oldPreviewWindow; } private void mnuVideoDevices_Click(object sender, System.EventArgs e) { try { // Get current devices and dispose of capture object // because the video and audio device can only be changed // by creating a new Capture object. Filter videoDevice = null; Filter audioDevice = null; if (capture != null) { videoDevice = capture.VideoDevice; audioDevice = capture.AudioDevice; capture.Dispose(); capture = null; } // Get new video device MenuItem m = sender as MenuItem; videoDevice = (m.Index > 0 ? filters.VideoInputDevices[m.Index - 1] : null); // Create capture object if ((videoDevice != null) || (audioDevice != null)) { capture = new Capture(videoDevice, audioDevice); capture.CaptureComplete += new EventHandler(OnCaptureComplete); } // Update the menu updateMenu(); } catch (Exception ex) { MessageBox.Show("Video device not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioDevices_Click(object sender, System.EventArgs e) { try { // Get current devices and dispose of capture object // because the video and audio device can only be changed // by creating a new Capture object. Filter videoDevice = null; Filter audioDevice = null; if (capture != null) { videoDevice = capture.VideoDevice; audioDevice = capture.AudioDevice; capture.Dispose(); capture = null; } // Get new audio device MenuItem m = sender as MenuItem; audioDevice = (m.Index > 0 ? filters.AudioInputDevices[m.Index - 1] : null); // Create capture object if ((videoDevice != null) || (audioDevice != null)) { capture = new Capture(videoDevice, audioDevice); capture.CaptureComplete += new EventHandler(OnCaptureComplete); } // Update the menu updateMenu(); } catch (Exception ex) { MessageBox.Show("Audio device not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuVideoCompressors_Click(object sender, System.EventArgs e) { try { // Change the video compressor // We subtract 1 from m.Index beacuse the first item is (None) MenuItem m = sender as MenuItem; capture.VideoCompressor = (m.Index > 0 ? filters.VideoCompressors[m.Index - 1] : null); updateMenu(); } catch (Exception ex) { MessageBox.Show("Video compressor not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioCompressors_Click(object sender, System.EventArgs e) { try { // Change the audio compressor // We subtract 1 from m.Index beacuse the first item is (None) MenuItem m = sender as MenuItem; capture.AudioCompressor = (m.Index > 0 ? filters.AudioCompressors[m.Index - 1] : null); updateMenu(); } catch (Exception ex) { MessageBox.Show("Audio compressor not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuVideoSources_Click(object sender, System.EventArgs e) { try { // Choose the video source // If the device only has one source, this menu item will be disabled MenuItem m = sender as MenuItem; capture.VideoSource = capture.VideoSources[m.Index]; updateMenu(); } catch (Exception ex) { MessageBox.Show("Unable to set video source. Please submit bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioSources_Click(object sender, System.EventArgs e) { try { // Choose the audio source // If the device only has one source, this menu item will be disabled MenuItem m = sender as MenuItem; capture.AudioSource = capture.AudioSources[m.Index]; updateMenu(); } catch (Exception ex) { MessageBox.Show("Unable to set audio source. Please submit bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuExit_Click(object sender, System.EventArgs e) { if (capture != null) capture.Stop(); Application.Exit(); } private void mnuFrameSizes_Click(object sender, System.EventArgs e) { try { // Disable preview to avoid additional flashes (optional) bool preview = (capture.PreviewWindow != null); capture.PreviewWindow = null; // Update the frame size MenuItem m = sender as MenuItem; string[] s = m.Text.Split('x'); Size size = new Size(int.Parse(s[0]), int.Parse(s[1])); capture.FrameSize = size; // Update the menu updateMenu(); // Restore previous preview setting capture.PreviewWindow = (preview ? panelVideo : null); } catch (Exception ex) { MessageBox.Show("Frame size not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuFrameRates_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; string[] s = m.Text.Split(' '); capture.FrameRate = double.Parse(s[0]); updateMenu(); } catch (Exception ex) { MessageBox.Show("Frame rate not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioChannels_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; capture.AudioChannels = (short)Math.Pow(2, m.Index); updateMenu(); } catch (Exception ex) { MessageBox.Show("Number of audio channels not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioSamplingRate_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; string[] s = m.Text.Split(' '); int samplingRate = (int)(double.Parse(s[0]) * 1000); capture.AudioSamplingRate = samplingRate; updateMenu(); } catch (Exception ex) { MessageBox.Show("Audio sampling rate not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioSampleSizes_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; string[] s = m.Text.Split(' '); short sampleSize = short.Parse(s[0]); capture.AudioSampleSize = sampleSize; updateMenu(); } catch (Exception ex) { MessageBox.Show("Audio sample size not supported.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuPreview_Click(object sender, System.EventArgs e) { try { if (capture.PreviewWindow == null) { capture.PreviewWindow = panelVideo; mnuPreview.Checked = true; } else { capture.PreviewWindow = null; mnuPreview.Checked = false; } } catch (Exception ex) { MessageBox.Show("Unable to enable/disable preview. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuPropertyPages_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; capture.PropertyPages[m.Index].Show(this); updateMenu(); } catch (Exception ex) { MessageBox.Show("Unable display property page. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuChannel_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; capture.Tuner.Channel = m.Index + 1; updateMenu(); } catch (Exception ex) { MessageBox.Show("Unable change channel. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuInputType_Click(object sender, System.EventArgs e) { try { MenuItem m = sender as MenuItem; capture.Tuner.InputType = (TunerInputType)m.Index; updateMenu(); } catch (Exception ex) { MessageBox.Show("Unable change tuner input type. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuVideoCaps_Click(object sender, System.EventArgs e) { try { string s; s = String.Format( "Video Device Capabilities\n" + "--------------------------------\n\n" + "Input Size:\t\t{0} x {1}\n" + "\n" + "Min Frame Size:\t\t{2} x {3}\n" + "Max Frame Size:\t\t{4} x {5}\n" + "Frame Size Granularity X:\t{6}\n" + "Frame Size Granularity Y:\t{7}\n" + "\n" + "Min Frame Rate:\t\t{8:0.000} fps\n" + "Max Frame Rate:\t\t{9:0.000} fps\n", capture.VideoCaps.InputSize.Width, capture.VideoCaps.InputSize.Height, capture.VideoCaps.MinFrameSize.Width, capture.VideoCaps.MinFrameSize.Height, capture.VideoCaps.MaxFrameSize.Width, capture.VideoCaps.MaxFrameSize.Height, capture.VideoCaps.FrameSizeGranularityX, capture.VideoCaps.FrameSizeGranularityY, capture.VideoCaps.MinFrameRate, capture.VideoCaps.MaxFrameRate); MessageBox.Show(s); } catch (Exception ex) { MessageBox.Show("Unable display video capabilities. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void mnuAudioCaps_Click(object sender, System.EventArgs e) { try { string s; s = String.Format( "Audio Device Capabilities\n" + "--------------------------------\n\n" + "Min Channels:\t\t{0}\n" + "Max Channels:\t\t{1}\n" + "Channels Granularity:\t{2}\n" + "\n" + "Min Sample Size:\t\t{3}\n" + "Max Sample Size:\t\t{4}\n" + "Sample Size Granularity:\t{5}\n" + "\n" + "Min Sampling Rate:\t\t{6}\n" + "Max Sampling Rate:\t\t{7}\n" + "Sampling Rate Granularity:\t{8}\n", capture.AudioCaps.MinimumChannels, capture.AudioCaps.MaximumChannels, capture.AudioCaps.ChannelsGranularity, capture.AudioCaps.MinimumSampleSize, capture.AudioCaps.MaximumSampleSize, capture.AudioCaps.SampleSizeGranularity, capture.AudioCaps.MinimumSamplingRate, capture.AudioCaps.MaximumSamplingRate, capture.AudioCaps.SamplingRateGranularity); MessageBox.Show(s); } catch (Exception ex) { MessageBox.Show("Unable display audio capabilities. Please submit a bug report.\n\n" + ex.Message + "\n\n" + ex.ToString()); } } private void OnCaptureComplete(object sender, EventArgs e) { // Demonstrate the Capture.CaptureComplete event. Debug.WriteLine("Capture complete."); } void capture_FrameCaptureComplete(PictureBox Frame) { //if (spMain.Panel2.Controls.Count < 1) { //Frame.Width = 500; //Frame.Height = 500; //spMain.Panel2.Controls.Add(Frame); //Frame.Dock = DockStyle.Fill; Recognize(Frame); } } void Recognize(PictureBox bb) { const double ScaleFactor = 2.5; const int MinNeighbors = 1; CvSize MinSize = new CvSize(30, 30); //CvCapture cap = CvCapture.FromCamera(1); CvHaarClassifierCascade cascade = CvHaarClassifierCascade.FromFile("haarcascade_eye.xml"); //IplImage img = cap.QueryFrame(); IplImage img = IplImage.FromBitmap(new Bitmap(bb.Image)); CvSeq<CvAvgComp> eyes = Cv.HaarDetectObjects(img, cascade, Cv.CreateMemStorage(), ScaleFactor, MinNeighbors, HaarDetectionType.DoCannyPruning, MinSize); foreach (CvAvgComp eye in eyes.AsParallel()) { img.DrawRect(eye.Rect, CvColor.Red); if (eye.Rect.Left > spMain.Panel2.Width / 2) { try { IplImage rightEyeImg1 = img.Clone(); Cv.SetImageROI(rightEyeImg1, eye.Rect); IplImage rightEyeImg2 = Cv.CreateImage(eye.Rect.Size, rightEyeImg1.Depth, rightEyeImg1.NChannels); Cv.Copy(rightEyeImg1, rightEyeImg2, null); Cv.ResetImageROI(rightEyeImg1); Bitmap rightEyeBm = BitmapConverter.ToBitmap(rightEyeImg2); //spMain.Panel2.Image = rightEyeBm; } catch { } } else { try { IplImage leftEyeImg1 = img.Clone(); Cv.SetImageROI(leftEyeImg1, eye.Rect); IplImage leftEyeImg2 = Cv.CreateImage(eye.Rect.Size, leftEyeImg1.Depth, leftEyeImg1.NChannels); Cv.Copy(leftEyeImg1, leftEyeImg2, null); Cv.ResetImageROI(leftEyeImg1); Bitmap leftEyeBm = BitmapConverter.ToBitmap(leftEyeImg2); //pctLeftEye.Image = leftEyeBm; } catch { } } } Bitmap bm = BitmapConverter.ToBitmap(img); bm.SetResolution(500, 500); //pctCvWindow.Image = bm; //PictureBox pb = new PictureBox(); //pb.Image = bm; //pb.Image = bm; bb.Image = bm; //spMain.Panel2.Controls.Clear(); if (spMain.Panel2.Controls.Count < 1) { spMain.Panel2.Controls.Add(bb); } bb.Dock = DockStyle.Fill; //pb.Image = bm; img = null; bm = null; } private void bCaptureFrame_Click(object sender, EventArgs e) { try { if (capture == null) throw new ApplicationException("Please select a video and/or audio device."); if (!capture.Cued) capture.Filename = txtFilename.Text; //capture.Cue(); //btnCue.Enabled = false; //MessageBox.Show("Ready to capture.\n\nUse Cue() before Start() to " + // "do all the preparation work that needs to be done to start a " + // "capture. Now, when you click Start the capture will begin faster " + // "than if you had just clicked Start. Using Cue() is completely " + // "optional. The downside to using Cue() is the preview is disabled until " + // "the capture begins."); capture.CaptureFrame(); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.ToString()); } } } }
using System; using RLToolkit; using RLToolkit.Extensions; using NUnit.Framework; namespace RLToolkit.UnitTests.Extensions { [TestFixture] public class ToggleButtonExclusiveSelectionGroupTest : TestHarness, ITestBase { #region Local Variables #endregion #region Interface Override public string ModuleName() { return "ToggleButtonExclusiveSelectionGroup"; } public override void SetFolderPaths() { localFolder = AppDomain.CurrentDomain.BaseDirectory; SetPaths (localFolder, ModuleName()); } public override void DataPrepare() { } #endregion #region Tests-AddRemove [Test] public void TBESG_AddRemove_Append_Normal() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); bool result = grp.Append(new Gtk.ToggleButton()); Assert.AreEqual(true, result, "ToggleButton Should be able to be added"); Assert.AreEqual(1, grp.GetCountButton(), "There should be 1 button in the group"); } [Test] public void TBESG_AddRemove_Append_Duplicate() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); bool result = grp.Append(toAdd); Assert.AreEqual(true, result, "ToggleButton Should be able to be added the first time"); result = grp.Append(toAdd); Assert.AreEqual(false, result, "ToggleButton Should not be able to be added the second time"); Assert.AreEqual(1, grp.GetCountButton(), "There should be 1 button in the group"); } [Test] public void TBESG_AddRemove_Append_Multiple() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd1 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); bool result = grp.Append(toAdd1); Assert.AreEqual(true, result, "ToggleButton1 Should be able to be added"); result = grp.Append(toAdd2); Assert.AreEqual(true, result, "ToggleButton2 Should not be able to be added"); Assert.AreEqual(2, grp.GetCountButton(), "There should be 2 buttons in the group"); } [Test] public void TBESG_AddRemove_Remove_Normal() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); bool result = grp.Append(toAdd); Assert.AreEqual(true, result, "ToggleButton1 Should be able to be added"); result = grp.Remove(toAdd); Assert.AreEqual(true, result, "ToggleButton Should be removed properly"); Assert.AreEqual(0, grp.GetCountButton(), "There should be no button in the group"); } [Test] public void TBESG_AddRemove_Remove_Number() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); bool result = grp.Append(toAdd); Assert.AreEqual(true, result, "ToggleButton1 Should be able to be added"); result = grp.Remove(0); Assert.AreEqual(true, result, "ToggleButton Should be removed properly"); Assert.AreEqual(0, grp.GetCountButton(), "There should be no button in the group"); } [Test] public void TBESG_AddRemove_Remove_NotExistant() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); bool result = grp.Append(toAdd); Assert.AreEqual(true, result, "ToggleButton1 Should be able to be added"); result = grp.Remove(toAdd2); Assert.AreEqual(false, result, "Invalid button to remove, shouldn't work"); Assert.AreEqual(1, grp.GetCountButton(), "There should be 1 button in the group"); } [Test] public void TBESG_AddRemove_Remove_NotExistant_Number() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); bool result = grp.Append(toAdd); Assert.AreEqual(true, result, "ToggleButton1 Should be able to be added"); result = grp.Remove(4); Assert.AreEqual(false, result, "Invalid button to remove, shouldn't work"); Assert.AreEqual(1, grp.GetCountButton(), "There should be 1 button in the group"); } [Test] public void TBESG_AddRemove_Remove_Invalid_Low() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); bool result = grp.Remove(-4); Assert.AreEqual(false, result, "Invalid button to remove, shouldn't work"); Assert.AreEqual(0, grp.GetCountButton(), "There should be no button in the group"); } [Test] public void TBESG_AddRemove_Remove_Invalid_High() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); bool result = grp.Remove(4); Assert.AreEqual(false, result, "Invalid button to remove, shouldn't work"); Assert.AreEqual(0, grp.GetCountButton(), "There should be no button in the group"); } [Test] public void TBESG_AddRemove_Remove_BigList() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd4 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd5 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); grp.Append(toAdd4); grp.Append(toAdd5); Assert.AreEqual(5, grp.GetCountButton(), "There should be 5 buttons in the group"); // remove the 3rd one bool result = grp.Remove(toAdd3); Assert.AreEqual(true, result, "3rd button removal should work"); Assert.AreEqual(4, grp.GetCountButton(), "There should be 4 buttons in the group"); // make sure the 3 is no longer there int pos = grp.FindInGroup(toAdd3); Assert.AreEqual(-1, pos, "The button should not be found anymore"); } [Test] public void TBESG_AddRemove_RemoveAll() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd4 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd5 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); grp.Append(toAdd4); grp.Append(toAdd5); Assert.AreEqual(5, grp.GetCountButton(), "There should be 5 buttons in the group"); grp.Select(toAdd3); Assert.AreEqual(true, toAdd3.Active, "Control 3 should be selected."); grp.RemoveAll(); Assert.AreEqual(0, grp.GetCountButton(), "There should be no button in the group"); Assert.AreEqual(false, toAdd3.Active, "Control 3 should no longer be selected."); } #endregion #region Tests-Select [Test] public void TBESG_Select_Normal() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(0); Assert.AreEqual(true, result, "Selection of index 0 should work after first test"); Assert.AreEqual(true, toAdd.Active, "control 1 should be active after first test"); Assert.AreEqual(false, toAdd3.Active, "control 3 should not be active after first test"); result = grp.Select(2); Assert.AreEqual(true, result, "Selection of index 2 should work after second test"); Assert.AreEqual(false, toAdd.Active, "control 1 should not be active after second test"); Assert.AreEqual(true, toAdd3.Active, "control 3 should be active after second test"); } [Test] public void TBESG_Select_WithControl() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(toAdd); Assert.AreEqual(true, result, "Selection of index 0 should work after first test"); Assert.AreEqual(true, toAdd.Active, "control 1 should be active after first test"); Assert.AreEqual(false, toAdd3.Active, "control 3 should not be active after first test"); result = grp.Select(toAdd3); Assert.AreEqual(true, result, "Selection of index 2 should work after second test"); Assert.AreEqual(false, toAdd.Active, "control 1 should not be active after second test"); Assert.AreEqual(true, toAdd3.Active, "control 3 should be active after second test"); } [Test] public void TBESG_Select_SameIndex() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(1); Assert.AreEqual(true, result, "Selection of index 1 should work"); result = grp.Select(1); Assert.AreEqual(false, result, "Selection of index 1 should not work twice since it's already selected"); } [Test] public void TBESG_Select_TooHigh() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(6); Assert.AreEqual(false, result, "Selection of index 6 is too high"); } [Test] public void TBESG_Select_TooLow() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(-5); Assert.AreEqual(false, result, "Selection of index -5 is too low"); } [Test] public void TBESG_Select_LikeUnselected() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(-1); Assert.AreEqual(false, result, "Selection of index -1 should not work"); } [Test] public void TBESG_Select_ControlNotExist() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); Gtk.ToggleButton toAddX = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(toAddX); Assert.AreEqual(false, result, "Selection of control X should not work after first test"); Assert.AreEqual(false, toAddX.Active, "control 3 should not be active after first test"); } #endregion #region Tests-Unselect [Test] public void TBESG_Unselect_Unselected() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Unselect(); Assert.AreEqual(false, result, "Nothing selected, should not be able to unselect"); } [Test] public void TBESG_Unselect_Normal() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); bool result = grp.Select(toAdd2); Assert.AreEqual(true, result, "Selection of index 1 should work"); Assert.AreEqual(true, toAdd2.Active, "control 2 should be active"); result = grp.Unselect(); Assert.AreEqual(true, result, "Unselection should be sucessful"); Assert.AreEqual(false, toAdd2.Active, "control 2 should no longer be active"); } #endregion #region Tests-FindInGroup [Test] public void TBESG_FindInGroup_Normal() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); int result = grp.FindInGroup(toAdd2); Assert.AreEqual(1, result, "The FindInGroup method should return the right control index"); } [Test] public void TBESG_FindInGroup_NotExist() { ToggleButtonExclusiveSelectionGroup grp = new ToggleButtonExclusiveSelectionGroup(); Gtk.ToggleButton toAdd = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd2 = new Gtk.ToggleButton(); Gtk.ToggleButton toAdd3 = new Gtk.ToggleButton(); Gtk.ToggleButton toAddX = new Gtk.ToggleButton(); grp.Append(toAdd); grp.Append(toAdd2); grp.Append(toAdd3); Assert.AreEqual(3, grp.GetCountButton(), "There should be 3 buttons in the group"); int result = grp.FindInGroup(toAddX); Assert.AreEqual(-1, result, "The FindInGroup method shouldn't find the control requested, returning -1"); } #endregion } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using ESRI.ArcGIS.Client; using ESRI.ArcLogistics.App.Commands; using ESRI.ArcLogistics.App.Controls; using ESRI.ArcLogistics.App.Geocode; using ESRI.ArcLogistics.App.Mapping; using ESRI.ArcLogistics.App.Tools; using ESRI.ArcLogistics.DomainObjects; using ESRI.ArcLogistics.Geocoding; using ESRI.ArcLogistics.Utility; using Xceed.Wpf.DataGrid; using ALGeometry = ESRI.ArcLogistics.Geometry; namespace ESRI.ArcLogistics.App.Pages { /// <summary> /// Class for helping to create geocodable items such as locations and orders. /// </summary> class GeocodablePage { #region constructors /// <summary> /// Create GeocodablePage. /// </summary> /// <param name="geocodableType">Geocodable type.</param> /// <param name="mapCtrl">Map from parent page.</param> /// <param name="candidateSelect">Control for selecting candidates.</param> /// <param name="controlsGrid">Grid, that contains map and candidateselect control.</param> /// <param name="geocodableGrid">Grid with geocodable items from parent page.</param> /// <param name="splitter">Splitter between map and candidateSelectControl.</param> /// <param name="parentLayer">Layer, that contains regions.</param> public GeocodablePage(Type geocodableType, MapControl mapCtrl, CandidateSelectControl candidateSelect, Grid controlsGrid, DataGridControlEx geocodableGrid, GridSplitter splitter, ObjectLayer parentLayer) { Debug.Assert(mapCtrl != null); Debug.Assert(candidateSelect != null); Debug.Assert(controlsGrid != null); Debug.Assert(geocodableGrid != null); Debug.Assert(splitter != null); Debug.Assert(parentLayer != null); _mapCtrl = mapCtrl; _candidateSelect = candidateSelect; _candidateSelect.Initialize(geocodableType); _controlsGrid = controlsGrid; _geocodableGrid = geocodableGrid; _splitter = splitter; _parentLayer = parentLayer; _geocodableType = geocodableType; _collapsed = new GridLength(0, GridUnitType.Star); _expanded = controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].Width; _collapsedMinWidth = 0; _expandedMinWidth = controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].MinWidth; _CollapseCandidateSelect(); // Subscribe to grid loaded event. _geocodableGrid.Loaded += new RoutedEventHandler(_GeocodableGridLoaded); } #endregion #region Public events /// <summary> /// Occurs when geocoding is started. /// </summary> public event EventHandler GeocodingStarted; /// <summary> /// Occurs when geocoding found match. /// </summary> public event EventHandler MatchFound; /// <summary> /// Occurs when geocoding found candidates. /// </summary> public event EventHandler CandidatesFound; /// <summary> /// Occurs when geocoding not found candidates. /// </summary> public event EventHandler CandidatesNotFound; #endregion #region Public members /// <summary> /// Is Page is in edited mode now. /// </summary> public bool IsInEditedMode { get; private set; } /// <summary> /// Is geocode in progress. /// </summary> public bool IsGeocodingInProcess { get; private set; } /// <summary> /// If geocoding is not successful - during geocoding process this property means best candidate to zoom. /// </summary> public AddressCandidate[] CandidatesToZoom { get; private set; } /// <summary> /// Is geocodable page used in fleet wizard, which means special logic. /// </summary> public bool ParentIsFleetWisard { get; set; } #endregion #region public Methods /// <summary> /// End geocoding. /// </summary> public void EndGeocoding() { _EndGeocoding(true); } /// <summary> /// React on creating new item. /// </summary> /// <param name="args">New item creating args.</param> public void OnCreatingNewItem(DataGridCreatingNewItemEventArgs args) { Debug.Assert(_parentLayer != null); Debug.Assert(args != null); _currentItem = (IGeocodable)args.NewItem; _currentItem.Address.PropertyChanged += new PropertyChangedEventHandler(_AddressPropertyChanged); Graphic graphic = _parentLayer.CreateGraphic(_currentItem); _parentLayer.MapLayer.Graphics.Add(graphic); _editStartedByGrid = true; _StartEdit(_currentItem); _editStartedByGrid = false; _SetAddressByPointToolEnabled(true); } /// <summary> /// React on commiting new item. /// </summary> /// <param name="args">New item commiting args.</param> /// <returns>Is commiting successful.</returns> public bool OnCommittingNewItem(DataGridCommittingNewItemEventArgs args) { Debug.Assert(_currentItem != null); Debug.Assert(args != null); bool commitingSuccessful = false; if (_isAddressChanged) { _StartGeocoding(_currentItem, true); if (!IsGeocodingInProcess) { _currentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); } } args.Handled = true; if (IsGeocodingInProcess) { args.Cancel = true; } else { commitingSuccessful = true; } _isNewItemJustCommited = true; return commitingSuccessful; } /// <summary> /// React on new item commited. /// </summary> public void OnNewItemCommitted() { Debug.Assert(_currentItem != null); _canceledByGrid = true; EditEnded(false); _currentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); _canceledByGrid = false; _SetAddressByPointToolEnabled(false); _currentItem = null; } /// <summary> /// React on cancelling new item. /// </summary> public void OnNewItemCancelling() { Debug.Assert(_parentLayer != null); // Supporting API issues. Needed in case of external new item creating canceling. if (_currentItem == null) return; _canceledByGrid = true; ObjectLayer.DeleteObject(_currentItem, _parentLayer.MapLayer); EditEnded(false); _currentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); if (IsGeocodingInProcess) { _EndGeocoding(false); } else { _currentItem = null; } _canceledByGrid = false; _SetAddressByPointToolEnabled(false); } /// <summary> /// React on cancelling edit. /// </summary> /// <param name="args">Datagrid item args.</param> public void OnEditCanceled(DataGridItemEventArgs args) { Debug.Assert(args != null); _canceledByGrid = true; if (IsGeocodingInProcess) { _EndGeocoding(false); } IGeocodable geocodable = args.Item as IGeocodable; geocodable.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); _currentItem = null; _isAddressChanged = false; EditEnded(false); _canceledByGrid = false; } /// <summary> /// React on beginning edit. /// </summary> /// <param name="args">Beginning edit args.</param> public void OnBeginningEdit(DataGridItemCancelEventArgs args) { Debug.Assert(args != null); // if geocoding in process and try to edit not geocoding geocodable object - than cancel it IGeocodable current = (IGeocodable)args.Item; // in case of deleting edited - cancel beginning edit if ((IsGeocodingInProcess && current != _currentItem)) { args.Cancel = true; } else { _currentItem = args.Item as IGeocodable; _currentItem.Address.PropertyChanged += new PropertyChangedEventHandler(_AddressPropertyChanged); _editStartedByGrid = true; _StartEdit(_currentItem); _editStartedByGrid = false; } } /// <summary> /// React on commiting edit. /// </summary> /// <param name="args">Commiting event args.</param> /// <param name="canStartGeocoding">Flag for accepting geocoding start.</param> public void OnCommittingEdit(DataGridItemCancelEventArgs args, bool canStartGeocoding) { Debug.Assert(args != null); _canceledByGrid = true; IGeocodable geocodable = (IGeocodable)args.Item; if (geocodable != _currentItem) { args.Cancel = true; } if (_isAddressChanged && canStartGeocoding) { _StartGeocoding(_currentItem, true); if (!IsGeocodingInProcess) { _currentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); } } EditEnded(false); _canceledByGrid = false; if (!IsGeocodingInProcess) { _currentItem = null; } } /// <summary> /// React on project closed. /// </summary> public void OnProjectClosed() { if (IsGeocodingInProcess) { _EndGeocoding(true); } if (IsInEditedMode) { EditEnded(false); } } /// <summary> /// Do regeocoding. /// </summary> /// <param name="geocodable">Geocodable to regeocode.</param> public void StartGeocoding(IGeocodable geocodable) { Debug.Assert(geocodable != null); _currentItem = geocodable; _StartGeocoding(geocodable, false); } /// <summary> /// React on selection changed. /// </summary> /// <param name="selectedItems">Selected items list.</param> public void OnSelectionChanged(IList selectedItems) { Debug.Assert(selectedItems != null); // Do not hide hint in case of new item was committed and selection is not set yet. if (selectedItems.Count > 0 && !_isNewItemJustCommited) _mapCtrl.HideZoomToCandidatePopup(); _isNewItemJustCommited = false; if (IsGeocodingInProcess) { _EndGeocoding(false); } // Address by point tool enabled in case of geocodable object selected or geocodable // object creating in progress. bool isAddressByPointToolEnabled = _currentItem != null || (selectedItems.Count == 1 && selectedItems[0] is IGeocodable); _SetAddressByPointToolEnabled(isAddressByPointToolEnabled); if (_mapCtrl.CurrentTool == _addressByPointTool) { _mapCtrl.CurrentTool = null; } } /// <summary> /// End edit. /// </summary> /// <param name="commit">Is in case of editing in grid try to commit changes.</param> public void EditEnded(bool commit) { Debug.Assert(_mapCtrl != null); Debug.Assert(_parentLayer != null); if (_isReccurent) return; // NOTE : workaround - sometimes Xceed data grid returns incorrect value of property IsBeingEdited // and that case we have to use the same property of Insertion Row. bool isGridBeingEdited = (_geocodableGrid.IsBeingEdited || (_geocodableGrid.InsertionRow != null && _geocodableGrid.InsertionRow.IsVisible && _geocodableGrid.InsertionRow.IsBeingEdited)); bool setEditFinished = true; if (isGridBeingEdited && !_canceledByGrid) { _isReccurent = true; // If command from map to commit was come, than try to end edit and commit // otherwise cancel edit. if (commit) { try { // If item is in insertion row - commit it. if (_geocodableGrid.InsertionRow != null) { _geocodableGrid.InsertionRow.EndEdit(); } _geocodableGrid.EndEdit(); } catch { // Do not need to finish editing on map. Editing in grid was not finished. setEditFinished = false; // NOTE : Eat exception. Exception occurs if geocoding in progress. } } else { // If item is in Insertion row - clear it. if (_geocodableGrid.InsertionRow != null) { _geocodableGrid.InsertionRow.CancelEdit(); } else { _geocodableGrid.CancelEdit(); } } _isReccurent = false; } if (setEditFinished) { IsInEditedMode = false; if (_mapCtrl.IsInEditedMode) { _isReccurent = true; _mapCtrl.EditEnded(); _isReccurent = false; } } _parentLayer.Selectable = true; _isAddressChanged = false; } #endregion #region Private Static Methods /// <summary> /// Checks that distance between specified points is less than or equal to the specified /// maximum distance. /// </summary> /// <param name="first">The first point to be checked.</param> /// <param name="second">The second point to be checked.</param> /// <param name="maxDistance">The maximum distance in meters.</param> /// <returns>True if and only if the distance between two points does not exceed /// <paramref name="maxDistance"/>.</returns> private static bool _CheckDistance( ALGeometry.Point first, ALGeometry.Point second, double maxDistance) { var longitude1 = _Normalize(first.X); var latitude1 = _Normalize(first.Y); var longitude2 = _Normalize(second.X); var latitude2 = _Normalize(second.Y); var radius = DistCalc.GetExtentRadius(longitude1, latitude1, maxDistance); // Simple Euclidean geometry should be ok for small distances. var distance = Math.Sqrt(_Sqr(longitude2 - longitude1) + _Sqr(latitude2 - latitude1)); return distance < radius; } /// <summary> /// Computes square of the specified value. /// </summary> /// <param name="x">The value to compute square for.</param> /// <returns>A square of the specified value.</returns> private static double _Sqr(double x) { return x * x; } /// <summary> /// Normalizes the specified WGS 84 coordinate value. /// </summary> /// <param name="coordinate">The coordinate value to be normalized.</param> /// <returns>A new coordinate value which is equal to the specified one to a period of /// 360 degrees and falls into [0, 360] range.</returns> private static double _Normalize(double coordinate) { const double period = 360.0; var result = Math.IEEERemainder(coordinate, period); if (result < 0.0) { result += period; } return result; } #endregion #region Private Methods /// <summary> /// Occurs when parent grid is loaded. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _GeocodableGridLoaded(object sender, RoutedEventArgs e) { // Do not initialize tools and candidates layers // if geocoder or map is not initialized. if (_mapCtrl.Map.IsInitialized() && App.Current.InternalGeocoder.IsInitialized()) { _InitGeocodingTools(); // When tools was activated - unsubscribe from grid loaded event. _geocodableGrid.Loaded -= new RoutedEventHandler(_GeocodableGridLoaded); } } /// <summary> /// Init geocoding tools. /// </summary> private void _InitGeocodingTools() { _CreateCandidatesLayer(); // Init tool. _addressByPointTool = new AddressByPointTool(); _addressByPointTool.SetGeocodableType(_geocodableType); _mapCtrl.AddTool(_addressByPointTool, _CanActivateTool); // If geocodable object is order then add handler, which disable selecting // objects from all map layers, when tool is active. if (_geocodableType == typeof(Order)) _addressByPointTool.ActivatedChanged += new EventHandler (_AddressByPointToolActivatedChanged); _InitEventHandlers(); } /// <summary> /// Creates all common event handlers. /// </summary> private void _InitEventHandlers() { Debug.Assert(_mapCtrl != null); Debug.Assert(_candidateSelect != null); Debug.Assert(_addressByPointTool != null); _mapCtrl.CanSelectCallback = _CanSelect; _mapCtrl.StartEditGeocodableCallback = _StartEdit; _mapCtrl.EndEditGeocodableCallback = EditEnded; _mapCtrl.IsGeocodingInProgressCallback = _IsGeocodingInProgress; _candidateSelect.CandidateApplied += new EventHandler(_CandidateApplied); _candidateSelect.CandidateLeaved += new EventHandler(_CandidateLeaved); _candidateSelect.CandidatePositionApplied += new EventHandler(_CandidatePositionApplied); _addressByPointTool.OnComplete += new EventHandler(_AddressByPointToolOnComplete); } /// <summary> /// Can select callback. /// </summary> /// <param name="item">Item to check.</param> /// <returns>Is item can be selected.</returns> private bool _CanSelect(object item) { return true; } /// <summary> /// Can address by point tool be activated. /// </summary> /// <returns>Is tool can be activated.</returns> private bool _CanActivateTool() { return true; } /// <summary> /// Make request to geocode server and process result. /// </summary> /// <param name="systemPoint">Clicked point coords.</param> private void _DoReverseGeocode(System.Windows.Point systemPoint) { object[] args = new object[3]; args[0] = systemPoint; IGeocodable geocodable; if (_currentItem != null) { geocodable = _currentItem; } else { geocodable = (IGeocodable)_geocodableGrid.SelectedItems[0]; } args[1] = geocodable; AddressByPointCmd addressByPointCmd = new AddressByPointCmd(); addressByPointCmd.Execute(args); if (MatchFound != null) MatchFound(this, EventArgs.Empty); _SaveToLocalAddressNameStorage(geocodable, null); // If responce was not received than message not need to be shown. bool isResponceReceived = (bool)args[addressByPointCmd.IsResponceReceivedIndex]; if (_IsAddressFieldsEmpty(geocodable.Address) && isResponceReceived) { _ShowReverseGeocodingErrorMessage(geocodable); } App.Current.Project.Save(); } /// <summary> /// If address is empty show message. /// </summary> /// <param name="geocodable">Geocodable item.</param> private void _ShowReverseGeocodingErrorMessage(IGeocodable geocodable) { string name = string.Empty; string formatStr = string.Empty; // Extract name and format string. Order order = geocodable as Order; Location location = geocodable as Location; if (order != null) { name = order.Name; formatStr = (string)App.Current.FindResource(ORDER_FAR_FROM_ROAD_RESOURCE_NAME); } else if (location != null) { name = location.Name; formatStr = (string)App.Current.FindResource(LOCATION_FAR_FROM_ROAD_RESOURCE_NAME); } else { // Geocodable object must be order or location. Debug.Assert(false); } if (!string.IsNullOrEmpty(formatStr)) { // Show error. string message = string.Format(formatStr, name); App.Current.Messenger.AddError(message); } } /// <summary> /// Is all fields of address is empty. /// </summary> /// <param name="address">Address to check.</param> /// <returns>Is all fields of address is empty.</returns> private bool _IsAddressFieldsEmpty(Address address) { Debug.Assert(address != null); bool isAddressEmpty = true; foreach (var addressPart in EnumHelpers.GetValues<AddressPart>()) { if (!string.IsNullOrEmpty(address[addressPart])) { isAddressEmpty = false; break; } } return isAddressEmpty; } /// <summary> /// Show candidate selection window. /// </summary> private void _ExpandCandidateSelect() { Debug.Assert(_controlsGrid != null); Debug.Assert(_candidateSelect != null); Debug.Assert(_splitter != null); _controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].MinWidth = _expandedMinWidth; _controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].Width = _expanded; _candidateSelect.Visibility = Visibility.Visible; _splitter.Visibility = Visibility.Visible; } /// <summary> /// Hide candidate selection window. /// </summary> private void _CollapseCandidateSelect() { Debug.Assert(_controlsGrid != null); Debug.Assert(_candidateSelect != null); Debug.Assert(_splitter != null); // Do nothing if "Did you mean" already collapsed. if (_controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].MinWidth == _collapsedMinWidth) return; if (_controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].ActualWidth != 0) { _expanded = _controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].Width; } _controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].MinWidth = _collapsedMinWidth; _controlsGrid.ColumnDefinitions[SELECTORGRIDINDEX].Width = _collapsed; _candidateSelect.Visibility = Visibility.Collapsed; _splitter.Visibility = Visibility.Collapsed; } /// <summary> /// Start geocoding. /// </summary> /// <param name="geocodable">Item to geocode.</param> /// <param name="useLocalAsPrimary">Is item just created.</param> private void _StartGeocoding(IGeocodable geocodable, bool useLocalAsPrimary) { CandidatesToZoom = null; _mapCtrl.HideZoomToCandidatePopup(); // Do not need to start geocoding if geocodable object is far from road. Geocode will be failed. string farFromRoadMatchMethod = (string)App.Current.FindResource(MANUALLY_EDITED_XY_FAR_FROM_NEAREST_ROAD_RESOURCE_NAME); if (geocodable.Address.MatchMethod != null && geocodable.Address.MatchMethod.Equals(farFromRoadMatchMethod, StringComparison.OrdinalIgnoreCase)) { return; } // If try to geocode with edited address fields during another geocoding process. if (IsGeocodingInProcess) { _candidateSelect.CandidateChanged -= new EventHandler(_CandidateChanged); _Clear(); _candidateSelect.CandidateChanged += new EventHandler(_CandidateChanged); } IsGeocodingInProcess = true; if (GeocodingStarted != null) { GeocodingStarted(this, EventArgs.Empty); } List<AddressCandidate> candidates = GeocodeHelpers.DoGeocode(geocodable, useLocalAsPrimary, true); var minimumMatchScore = App.Current.Geocoder.MinimumMatchScore; _ProcessGeocodingResults(geocodable, candidates, minimumMatchScore); _isAddressChanged = false; } /// <summary> /// Filters out candidates with the same address and nearby locations. /// </summary> /// <param name="candidates">The collection of candidates to be filtered.</param> /// <param name="minimumMatchScore">Specifies the minimum score value at which candidate /// will be treated as matched.</param> /// <returns>A filtered collection of candidates.</returns> private IEnumerable<AddressCandidate> _FilterSameCandidates( IEnumerable<AddressCandidate> candidates, int minimumMatchScore) { Debug.Assert(candidates != null); Debug.Assert(candidates.All(candidate => candidate != null)); var sameCandidates = new Dictionary<string, List<AddressCandidate>>( StringComparer.OrdinalIgnoreCase); var distinctCandidates = new List<AddressCandidate>(); foreach (var candidate in candidates) { var fullAddress = candidate.Address.FullAddress ?? string.Empty; if (!sameCandidates.ContainsKey(fullAddress)) { sameCandidates[fullAddress] = new List<AddressCandidate>(); } var existingCandidates = sameCandidates[fullAddress]; var sameCandidate = existingCandidates.FirstOrDefault( existingCandidate => _CheckDistance( existingCandidate.GeoLocation, candidate.GeoLocation, MAX_CANDIDATES_DISTANCE)); var isDuplicate = sameCandidate != null && (sameCandidate.Score >= candidate.Score || sameCandidate.Score >= minimumMatchScore); if (isDuplicate) { continue; } sameCandidates[fullAddress].Add(candidate); distinctCandidates.Add(candidate); } return distinctCandidates; } /// <summary> /// Validates and fixes candidates with incorrect locations. /// </summary> /// <param name="candidates">The reference to the collection of address candidates to /// be validated and fixed.</param> /// <param name="geocodable">The reference to the geocodable object used for retrieving /// candidates collection.</param> /// <returns>A reference to the collection of address candidates with fixed /// locations.</returns> private IEnumerable<AddressCandidate> _GetValidLocations( IEnumerable<AddressCandidate> candidates, IGeocodable geocodable) { Debug.Assert(candidates != null); Debug.Assert(candidates.All(candidate => candidate != null)); Debug.Assert(geocodable != null); List<int> incorrectCandidates = new List<int>(); try { var streetsGeocoder = App.Current.StreetsGeocoder; var locationValidator = new LocationValidator(streetsGeocoder); incorrectCandidates = locationValidator .FindIncorrectLocations(candidates) .ToList(); } catch (Exception ex) { if (GeocodeHelpers.MustThrowException(ex)) { throw; } } if (!incorrectCandidates.Any()) { return candidates; } // Get incorrect address candidates. List<AddressCandidate> allCandidates = candidates.ToList(); var invalidAddressCandidates = incorrectCandidates .Select(index => allCandidates[index]) .ToList(); // Get all candidates which is not invalid. var result = candidates .Except(invalidAddressCandidates) .ToList(); return result; } /// <summary> /// Processes geocoding candidates. /// </summary> /// <param name="allCandidates">The reference to a collection of all geocoding /// candidates.</param> /// <param name="geocodable">The reference to an object to be geocoded.</param> /// <param name="minimumMatchScore">Specifies the minimum score value at which candidate /// will be treated as matched.</param> private void _ProcessGeocodingCandidates( IEnumerable<AddressCandidate> allCandidates, IGeocodable geocodable, int minimumMatchScore) { Debug.Assert(allCandidates != null); Debug.Assert(allCandidates.All(candidate => candidate != null)); Debug.Assert(geocodable != null); var candidates = GeocodeHelpers.SortCandidatesByPrimaryLocators( App.Current.Geocoder, allCandidates); if (!candidates.Any()) { _ProcessCandidatesNotFound(App.Current.Geocoder, geocodable, allCandidates.ToList()); return; } candidates = _GetValidLocations(candidates, geocodable).ToList(); var distinctCandidates = _FilterSameCandidates(candidates, minimumMatchScore).ToList(); var matchedCandidates = distinctCandidates .Where(candidate => candidate.Score >= minimumMatchScore) .ToList(); if (matchedCandidates.Count == 1) { _ProcessMatchFound(geocodable, matchedCandidates.First()); } else if (matchedCandidates.Count > 0) { // Find candidates with 100% score. var maxScoreCandidates = matchedCandidates .Where(candidate => candidate.Score == 100) .ToList(); if (maxScoreCandidates.Count == 1) // If found ONE candidate with 100% score, then choose it. _ProcessMatchFound(geocodable, maxScoreCandidates.First()); else // If not found 100% candidates or found more than ONE, show candidates. _ProcessCandidatesFound(matchedCandidates); } else { var topCandidates = distinctCandidates .OrderByDescending(candidate => candidate.Score) .Take(MAX_CANDIDATE_COUNT) .ToList(); if (topCandidates.Count > 0) _ProcessCandidatesFound(topCandidates); else _ProcessCandidatesNotFound(App.Current.Geocoder, geocodable, allCandidates); } } /// <summary> /// Process geocoding result. /// </summary> /// <param name="geocodable">Item to geocode.</param> /// <param name="allCandidates">Candidates list from all locators, include not primary.</param> /// <param name="minimumMatchScore">Specifies the minimum score value at which candidate /// will be treated as matched.</param> private void _ProcessGeocodingResults( IGeocodable geocodable, List<AddressCandidate> allCandidates, int minimumMatchScore) { _ProcessGeocodingCandidates(allCandidates, geocodable, minimumMatchScore); if (IsGeocodingInProcess) { _ExpandCandidateSelect(); _SetMapviewToCandidates(); _mapCtrl.SetEditingMapLayersOpacity(true); // React on map size changing only if map is initialized. if (_mapCtrl.Map.IsInitialized()) _mapCtrl.map.SizeChanged += new SizeChangedEventHandler(_MapSizeChanged); } else { // In case of we have geocode candidates at start, but with newly address data we haven't. _CollapseCandidateSelect(); // Current item can be not null only in case of geocoding in progress or editing in progress. if (!_geocodableGrid.IsItemBeingEdited) _currentItem = null; } } /// <summary> /// End geocoding with match found. Save candidate position to edited item. /// </summary> /// <param name="geocodable">Item to geocode.</param> /// <param name="candidate">Matched candidate.</param> private void _ProcessMatchFound(IGeocodable geocodable, AddressCandidate candidate) { string manuallyEditedXY = (string)Application.Current.FindResource("ManuallyEditedXY"); if (string.Equals(candidate.Address.MatchMethod, manuallyEditedXY)) { geocodable.GeoLocation = new ESRI.ArcLogistics.Geometry.Point(candidate.GeoLocation.X, candidate.GeoLocation.Y); ; candidate.Address.CopyTo(geocodable.Address); } else { GeocodeHelpers.SetCandidate(geocodable, candidate); } if (MatchFound != null) MatchFound(this, EventArgs.Empty); IsGeocodingInProcess = false; } /// <summary> /// Show "Did you mean" dialog. /// </summary> /// <param name="candidates">Candidates for current geocoded items.</param> private void _ProcessCandidatesFound(List<AddressCandidate> candidates) { _candidates = candidates; // In case of candidate array. IsGeocodingInProcess = true; // Show candidates on map layer. _candidatesLayer.Collection = _candidates; _candidateSelect.CandidateChanged += new EventHandler(_CandidateChanged); _candidateSelect.AddCandidates(_candidates); _parentLayer.Selectable = false; if (CandidatesFound != null) CandidatesFound(this, EventArgs.Empty); } /// <summary> /// Finish geocoding and try to zoom near. /// </summary> /// <param name="geocoder">Geocoder which found candidates.</param> /// <param name="geocodable">Item to geocode.</param> /// <param name="allCandidates">All candidates, returned for current geocoded item.</param> private void _ProcessCandidatesNotFound(IGeocoder geocoder, IGeocodable geocodable, IEnumerable<AddressCandidate> allCandidates) { // Set candidates to zoom. var candidatesFromNotPrimaryLocators = GeocodeHelpers.GetBestCandidatesFromNotPrimaryLocators(geocoder, geocodable, allCandidates); CandidatesToZoom = candidatesFromNotPrimaryLocators.ToArray(); if (CandidatesNotFound != null) CandidatesNotFound(this, EventArgs.Empty); AddressCandidate zoomedCandidate = null; // Zoom to candidates from not primary locators. if (CandidatesToZoom != null && CandidatesToZoom.Length > 0) { MapExtentHelpers.ZoomToCandidates(_mapCtrl, CandidatesToZoom); zoomedCandidate = CandidatesToZoom[0]; } // Show popup on map if not in fleet wizard. if (!ParentIsFleetWisard) _mapCtrl.ShowZoomToCandidatePopup(geocodable, CandidatesToZoom); IsGeocodingInProcess = false; } /// <summary> /// Save manual order geocoding results to local storage. /// </summary> /// <param name="geocodable">Geocoding object.</param> /// <param name="oldAddress">Address before geocoding.</param> private void _SaveToLocalAddressNameStorage(IGeocodable geocodable, Address oldAddress) { // Do nothing in case of geocodable object is location. Order order = geocodable as Order; if (order != null) { NameAddressRecord nameAddressRecord = CommonHelpers.CreateNameAddressPair(order, oldAddress); // Do save in local storage. App.Current.NameAddressStorage.InsertOrUpdate(nameAddressRecord, App.Current.Geocoder.AddressFormat); } } /// <summary> /// End geocoding. /// </summary> /// <param name="needToCancelEdit">Is need to cancel edit. Is used because /// on "cancelling new item" call "cancelling new item" again.</param> private void _EndGeocoding(bool needToCancelEdit) { Debug.Assert(_mapCtrl != null); Debug.Assert(IsGeocodingInProcess); _mapCtrl.IgnoreSizeChanged = true; // Workaround - see method comment. CommonHelpers.FillAddressWithSameValues(_currentItem.Address); _mapCtrl.SetEditingMapLayersOpacity(false); IsGeocodingInProcess = false; _isAddressChanged = false; _parentLayer.Selectable = true; _Clear(); _CollapseCandidateSelect(); if (_currentItem != null) { _currentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged); } if (App.Current.Project != null) { App.Current.Project.Save(); } // End edit in data grid. if (needToCancelEdit && !_canceledByGrid && _geocodableGrid.IsItemBeingEdited) { _EndEditInGrid(); } _currentItem = null; } /// <summary> /// Start edit. /// </summary> /// <param name="item">Item to edit.</param> private void _StartEdit(object item) { Debug.Assert(_mapCtrl != null); Debug.Assert(_parentLayer != null); if (_isReccurent) return; _isReccurent = true; if (!_editStartedByGrid) { try { // Do not make bring item to view because datagrid control may be null in case of unassigned orders context // not opened in visible views. _geocodableGrid.BringItemIntoView(item); Debug.Assert(_itemToEdit == null); _itemToEdit = item; _mapCtrl.Dispatcher.BeginInvoke(new Action(_StartEditInGrid), DispatcherPriority.Input, null); _editStartedByGrid = true; } catch (Exception ex) { Debug.Assert(false); Logger.Warning(ex); } } if (!IsInEditedMode) { IsInEditedMode = true; _mapCtrl.StartEdit(item); _parentLayer.Selectable = false; } _isReccurent = false; } /// <summary> /// Start edit in grid. /// </summary> private void _StartEditInGrid() { Debug.Assert(_itemToEdit != null); try { _geocodableGrid.BeginEdit(_itemToEdit); } catch (Exception ex) { Logger.Error(ex); } _editStartedByGrid = false; _itemToEdit = null; } /// <summary> /// Method end edits in the data grid. /// </summary> private void _EndEditInGrid() { if (_geocodableGrid.IsBeingEdited) { try { // End edit in the data grid. _geocodableGrid.EndEdit(); } catch (Exception ex) { Logger.Error(ex); } } else { // End edit in the Insertion Row. if (_geocodableGrid.InsertionRow.IsBeingEdited) { try { _geocodableGrid.InsertionRow.EndEdit(); } catch (Exception ex) { Logger.Error(ex); } } else { // Do nothing: nothing was edited. } } } /// <summary> /// Create candidates layer. /// </summary> private void _CreateCandidatesLayer() { Debug.Assert(_mapCtrl != null); List<AddressCandidate> coll = new List<AddressCandidate>(); _candidatesLayer = new ObjectLayer(coll, typeof(AddressCandidate), false); _mapCtrl.AddLayer(_candidatesLayer); _candidatesLayer.Selectable = true; _candidatesLayer.SelectedItems.CollectionChanged += new NotifyCollectionChangedEventHandler(_SelectedItemsCollectionChanged); _candidatesLayer.SingleSelection = true; _candidatesLayer.ConstantOpacity = true; } /// <summary> /// React on candidate change in list /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CandidateChanged(object sender, EventArgs e) { Debug.Assert(_mapCtrl != null); Debug.Assert(_candidateSelect != null); Debug.Assert(_candidates != null); Debug.Assert(_candidatesLayer != null); if (_inCollectionChanged) return; AddressCandidate candidate = _candidateSelect.GetCandidate(); Debug.Assert(candidate != null); List<ESRI.ArcLogistics.Geometry.Point> points = new List<ESRI.ArcLogistics.Geometry.Point>(); points.Add(candidate.GeoLocation); MapExtentHelpers.SetExtentOnCollection(_mapCtrl, points); // Find selected candidate index. int candidateIndex = -1; for (int index = 0; index < _candidates.Count; index++) { if (_candidates[index] == candidate) { candidateIndex = index; break; } } // select candidate on map Debug.Assert(candidateIndex >= 0); ObservableCollection<object> selected = _candidatesLayer.SelectedItems; selected.CollectionChanged -= new NotifyCollectionChangedEventHandler(_SelectedItemsCollectionChanged); if (selected.Count > 0) { selected.Clear(); } selected.Add(candidate); selected.CollectionChanged += new NotifyCollectionChangedEventHandler(_SelectedItemsCollectionChanged); } /// <summary> /// Set map view to candidates /// </summary> private void _SetMapviewToCandidates() { Debug.Assert(_mapCtrl != null); Debug.Assert(_candidates != null); List<ESRI.ArcLogistics.Geometry.Point> points = new List<ESRI.ArcLogistics.Geometry.Point>(); // add location to extent foreach (AddressCandidate candidate in _candidates) { points.Add(candidate.GeoLocation); } _mapCtrl.IgnoreSizeChanged = true; MapExtentHelpers.SetExtentOnCollection(_mapCtrl, points); } /// <summary> /// End geocoding. Clear all data. /// </summary> private void _Clear() { _candidateSelect.CandidateChanged -= new EventHandler(_CandidateChanged); IsGeocodingInProcess = false; // Candidates layers are null if geocoder // or map is not initialized. if (_mapCtrl.Map.IsInitialized() && App.Current.InternalGeocoder.IsInitialized()) { _candidateSelect.ClearList(); _candidatesLayer.Collection = null; } CandidatesToZoom = null; } /// <summary> /// Is geocoding in progress. /// </summary> private bool _IsGeocodingInProgress() { return IsGeocodingInProcess; } /// <summary> /// Method set value to AddressByPointTool if it is exists. /// </summary> /// <param name="value">Value to set.</param> private void _SetAddressByPointToolEnabled(bool value) { if (_addressByPointTool != null) _addressByPointTool.IsEnabled = value; } #endregion #region Private event handlers /// <summary> /// Changing routes, orders, stop layers selectable /// property depending on tool activation. /// </summary> /// <param name="sender">AddressByPointTool.</param> /// <param name="e">Ignored.</param> private void _AddressByPointToolActivatedChanged(object sender, EventArgs e) { // If tool was activated - make all layers non selectable. // If tool was disactivated - make layers selectable back. bool canSelectLayers = !(sender as AddressByPointTool).IsActivated; // Mark layers with stop,route and orders as selectable/non-selectable. foreach (var layer in _mapCtrl.ObjectLayers.Where(x => x.LayerType == typeof(Route) || x.LayerType == typeof(Stop) || x.LayerType == typeof(Order))) layer.Selectable = canSelectLayers; } /// <summary> /// React on reverse geocoding complete. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _AddressByPointToolOnComplete(object sender, EventArgs e) { Debug.Assert(_mapCtrl != null); Debug.Assert(_addressByPointTool != null); ESRI.ArcLogistics.Geometry.Point point = new ESRI.ArcLogistics.Geometry.Point( _addressByPointTool.X.Value, _addressByPointTool.Y.Value); // Project point from Web Mercator to WGS84 if spatial reference of map is Web Mercator if (_mapCtrl.Map.SpatialReferenceID.HasValue) { point = WebMercatorUtil.ProjectPointFromWebMercator(point, _mapCtrl.Map.SpatialReferenceID.Value); } System.Windows.Point systemPoint = new System.Windows.Point(point.X, point.Y); if (_geocodableGrid.SelectedItems.Count == 1 || _currentItem != null) { if (IsGeocodingInProcess) { _EndGeocoding(false); } _DoReverseGeocode(systemPoint); _mapCtrl.map.UpdateLayout(); _isAddressChanged = false; } else { Debug.Assert(false); } _mapCtrl.HideZoomToCandidatePopup(); } /// <summary> /// React on map size changed. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _MapSizeChanged(object sender, SizeChangedEventArgs e) { Debug.Assert(_mapCtrl != null); _mapCtrl.map.SizeChanged -= new SizeChangedEventHandler(_MapSizeChanged); _SetMapviewToCandidates(); } /// <summary> /// React on change selection on map control. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Debug.Assert(_candidatesLayer != null); Debug.Assert(_candidateSelect != null); Debug.Assert(_candidatesLayer.SelectedItems.Count < 2); if (_candidatesLayer.SelectedItems.Count == 1) { AddressCandidate candidate = (AddressCandidate)_candidatesLayer.SelectedItems[0]; // Select candidate at list. _inCollectionChanged = true; _candidateSelect.SelectCandidate(candidate); _inCollectionChanged = false; } else { _candidateSelect.SelectCandidate(null); } } /// <summary> /// React on address changed in grid. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Address property changed event args.</param> private void _AddressPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != Address.PropertyNameMatchMethod) { _isAddressChanged = true; } } /// <summary> /// React on candidate applied. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CandidateApplied(object sender, EventArgs e) { Debug.Assert(_currentItem != null); Debug.Assert(_candidateSelect != null); AddressCandidate candidate = _candidateSelect.GetCandidate(); Debug.Assert(candidate != null); Address oldAddress = (Address)_currentItem.Address.Clone(); string manuallyEditedXY = (string)Application.Current.FindResource("ManuallyEditedXY"); if (string.Equals(candidate.Address.MatchMethod, manuallyEditedXY)) { _currentItem.GeoLocation = new ESRI.ArcLogistics.Geometry.Point(candidate.GeoLocation.X, candidate.GeoLocation.Y); ; candidate.Address.CopyTo(_currentItem.Address); } else { // Update address values from candidate. GeocodeHelpers.SetCandidate(_currentItem, candidate); candidate.Address.CopyTo(_currentItem.Address); if (!GeocodeHelpers.IsParsed(_currentItem.Address) && App.Current.Geocoder.AddressFormat != AddressFormat.SingleField) { GeocodeHelpers.ParseAndFillAddress(_currentItem.Address); } } _SaveToLocalAddressNameStorage(_currentItem, oldAddress); _EndGeocoding(true); if (MatchFound != null) MatchFound(this, EventArgs.Empty); } /// <summary> /// React on candidate position applied. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CandidatePositionApplied(object sender, EventArgs e) { Debug.Assert(_currentItem != null); Debug.Assert(_candidateSelect != null); AddressCandidate candidate = _candidateSelect.GetCandidate(); // Candidate is empty in case of double click on scroll bar. if (candidate != null) { GeocodeHelpers.SetCandidate(_currentItem, candidate); _SaveToLocalAddressNameStorage(_currentItem, null); _EndGeocoding(true); if (MatchFound != null) MatchFound(this, EventArgs.Empty); } } /// <summary> /// React on candidate not selected. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _CandidateLeaved(object sender, EventArgs e) { _EndGeocoding(true); if (CandidatesNotFound != null) CandidatesNotFound(this, EventArgs.Empty); } #endregion #region constants /// <summary> /// Index of selector grid. /// </summary> private const int SELECTORGRIDINDEX = 1; /// <summary> /// Match method for not geocoded items resource name. /// </summary> private const string MANUALLY_EDITED_XY_FAR_FROM_NEAREST_ROAD_RESOURCE_NAME = "ManuallyEditedXYFarFromNearestRoad"; /// <summary> /// Message about order far from road resource name. /// </summary> private const string ORDER_FAR_FROM_ROAD_RESOURCE_NAME = "OrderNotFoundOnNetworkViolationMessage"; /// <summary> /// Message about order far from road resource name. /// </summary> private const string LOCATION_FAR_FROM_ROAD_RESOURCE_NAME = "LocationNotFoundOnNetworkViolationMessage"; /// <summary> /// The maximum number of candidates to let user select from when no candidate has good /// enough match score. /// </summary> private const int MAX_CANDIDATE_COUNT = 10; /// <summary> /// The maximum distance in meters between two candidate points when candidates could be /// treated as a single candidate. /// </summary> /// <remarks>We use Euclidean metrics to check distance, which is adequate for relatively /// small distances only (like 200 meters). Change distance algorithm to a more precise /// one before increasing the maximum distance value.</remarks> private const double MAX_CANDIDATES_DISTANCE = 200.0; #endregion #region Private Fields /// <summary> /// Current geocodable item. /// </summary> private IGeocodable _currentItem; /// <summary> /// Grid length of collapsed candidate control. /// </summary> private GridLength _collapsed; /// <summary> /// Grid length of visible candidate control. /// </summary> private GridLength _expanded; /// <summary> /// Minimal width of candidate control in collapsed state. /// </summary> private double _collapsedMinWidth; /// <summary> /// Minimal width of candidate control in visible state. /// </summary> private double _expandedMinWidth; /// <summary> /// Map control. /// </summary> private MapControl _mapCtrl; /// <summary> /// Candidate select control. /// </summary> private CandidateSelectControl _candidateSelect; /// <summary> /// Parent grid of candidate select control. /// </summary> private Grid _controlsGrid; /// <summary> /// Splitter between map and candidate select control. /// </summary> private GridSplitter _splitter; /// <summary> /// Layer, which shows candidates. /// </summary> private ObjectLayer _candidatesLayer; /// <summary> /// Layer, which contains geocodable objects. /// </summary> private ObjectLayer _parentLayer; /// <summary> /// Candidate collection. /// </summary> private List<AddressCandidate> _candidates; /// <summary> /// Flag, which indicates about changes in address fields of current item. /// </summary> private bool _isAddressChanged; /// <summary> /// Flag, which indicates "in candidate collection changed" state. /// </summary> private bool _inCollectionChanged; /// <summary> /// Tool for reverse geocoding. /// </summary> private AddressByPointTool _addressByPointTool; /// <summary> /// Is in reccurent edit. /// </summary> private bool _isReccurent; /// <summary> /// Flag, which indicates that edit was started by grid. /// </summary> private bool _editStartedByGrid; /// <summary> /// Flag, which indicates cancelling by grid. /// </summary> private bool _canceledByGrid; /// <summary> /// Item for postponed editing. /// </summary> private object _itemToEdit; /// <summary> /// Datagrid control with geocodable /// </summary> private DataGridControlEx _geocodableGrid; /// <summary> /// Flag to store hint visibility, which need to be showed after selection changed. /// </summary> private bool _isNewItemJustCommited; /// <summary> /// Geocodable type. /// </summary> private Type _geocodableType; #endregion } }
using J2N.Text; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using WritableArrayAttribute = YAF.Lucene.Net.Support.WritableArrayAttribute; namespace YAF.Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents <see cref="T:char[]"/>, as a slice (offset + Length) into an existing <see cref="T:char[]"/>. /// The <see cref="Chars"/> property should never be <c>null</c>; use /// <see cref="EMPTY_CHARS"/> if necessary. /// <para/> /// @lucene.internal /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public sealed class CharsRef : IComparable<CharsRef>, ICharSequence #if FEATURE_CLONEABLE , System.ICloneable #endif { /// <summary> /// An empty character array for convenience </summary> public static readonly char[] EMPTY_CHARS = new char[0]; bool ICharSequence.HasValue => true; /// <summary> /// The contents of the <see cref="CharsRef"/>. Should never be <c>null</c>. /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public char[] Chars { get { return chars; } set { if (value == null) { throw new ArgumentNullException("Chars cannot be null"); } chars = value; } } private char[] chars; /// <summary> /// Offset of first valid character. </summary> public int Offset { get; internal set; } /// <summary> /// Length of used characters. </summary> public int Length { get; set; } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized an empty array zero-Length /// </summary> public CharsRef() : this(EMPTY_CHARS, 0, 0) { } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with an array of the given /// <paramref name="capacity"/>. /// </summary> public CharsRef(int capacity) { chars = new char[capacity]; } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with the given <paramref name="chars"/>, /// <paramref name="offset"/> and <paramref name="length"/>. /// </summary> public CharsRef(char[] chars, int offset, int length) { this.chars = chars; this.Offset = offset; this.Length = length; Debug.Assert(IsValid()); } /// <summary> /// Creates a new <see cref="CharsRef"/> initialized with the given <see cref="string"/> character /// array. /// </summary> public CharsRef(string @string) { this.chars = @string.ToCharArray(); this.Offset = 0; this.Length = chars.Length; } /// <summary> /// Returns a shallow clone of this instance (the underlying characters are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref="DeepCopyOf(CharsRef)"/> public object Clone() { return new CharsRef(chars, Offset, Length); } public override int GetHashCode() { const int prime = 31; int result = 0; int end = Offset + Length; for (int i = Offset; i < end; i++) { result = prime * result + chars[i]; } return result; } public override bool Equals(object other) { if (other == null) { return false; } if (other is CharsRef) { return this.CharsEquals(((CharsRef)other)); } return false; } public bool CharsEquals(CharsRef other) { if (Length == other.Length) { int otherUpto = other.Offset; char[] otherChars = other.chars; int end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (chars[upto] != otherChars[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Signed <see cref="int"/> order comparison </summary> public int CompareTo(CharsRef other) { if (this == other) { return 0; } char[] aChars = this.chars; int aUpto = this.Offset; char[] bChars = other.chars; int bUpto = other.Offset; int aStop = aUpto + Math.Min(this.Length, other.Length); while (aUpto < aStop) { int aInt = aChars[aUpto++]; int bInt = bChars[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.Length - other.Length; } /// <summary> /// Copies the given <see cref="CharsRef"/> referenced content into this instance. /// </summary> /// <param name="other"> /// The <see cref="CharsRef"/> to copy. </param> public void CopyChars(CharsRef other) { CopyChars(other.chars, other.Offset, other.Length); } /// <summary> /// Used to grow the reference array. /// <para/> /// In general this should not be used as it does not take the offset into account. /// <para/> /// @lucene.internal /// </summary> public void Grow(int newLength) { Debug.Assert(Offset == 0); if (chars.Length < newLength) { chars = ArrayUtil.Grow(chars, newLength); } } /// <summary> /// Copies the given array into this <see cref="CharsRef"/>. /// </summary> public void CopyChars(char[] otherChars, int otherOffset, int otherLength) { if (Chars.Length - Offset < otherLength) { chars = new char[otherLength]; Offset = 0; } Array.Copy(otherChars, otherOffset, chars, Offset, otherLength); Length = otherLength; } /// <summary> /// Appends the given array to this <see cref="CharsRef"/>. /// </summary> public void Append(char[] otherChars, int otherOffset, int otherLength) { int newLen = Length + otherLength; if (chars.Length - Offset < newLen) { var newChars = new char[newLen]; Array.Copy(chars, Offset, newChars, 0, Length); Offset = 0; chars = newChars; } Array.Copy(otherChars, otherOffset, chars, Length + Offset, otherLength); Length = newLen; } public override string ToString() { return new string(chars, Offset, Length); } // LUCENENET NOTE: Length field made into property already //public char CharAt(int index) //{ // // NOTE: must do a real check here to meet the specs of CharSequence // if (index < 0 || index >= Length) // { // throw new System.IndexOutOfRangeException(); // } // return Chars[Offset + index]; //} // LUCENENET specific - added to .NETify public char this[int index] { get { // NOTE: must do a real check here to meet the specs of CharSequence if (index < 0 || index >= Length) { throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Changed exception type to ArgumentOutOfRangeException } return chars[Offset + index]; } } public ICharSequence Subsequence(int startIndex, int length) { // NOTE: must do a real check here to meet the specs of CharSequence //if (start < 0 || end > Length || start > end) //{ // throw new System.IndexOutOfRangeException(); //} // LUCENENET specific - changed semantics from start/end to startIndex/length to match .NET // From Apache Harmony String class if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (startIndex + length > Length) throw new ArgumentOutOfRangeException("", $"{nameof(startIndex)} + {nameof(length)} > {nameof(Length)}"); return new CharsRef(chars, Offset + startIndex, length); } /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] private static readonly IComparer<CharsRef> utf16SortedAsUTF8SortOrder = new Utf16SortedAsUTF8Comparer(); /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] public static IComparer<CharsRef> UTF16SortedAsUTF8Comparer { get { return utf16SortedAsUTF8SortOrder; } } /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] private class Utf16SortedAsUTF8Comparer : IComparer<CharsRef> { // Only singleton internal Utf16SortedAsUTF8Comparer() { } public virtual int Compare(CharsRef a, CharsRef b) { if (a == b) { return 0; } char[] aChars = a.Chars; int aUpto = a.Offset; char[] bChars = b.Chars; int bUpto = b.Offset; int aStop = aUpto + Math.Min(a.Length, b.Length); while (aUpto < aStop) { char aChar = aChars[aUpto++]; char bChar = bChars[bUpto++]; if (aChar != bChar) { // http://icu-project.org/docs/papers/utf16_code_point_order.html /* aChar != bChar, fix up each one if they're both in or above the surrogate range, then compare them */ if (aChar >= 0xd800 && bChar >= 0xd800) {//LUCENE TO-DO possible truncation or is char 16bit? if (aChar >= 0xe000) { aChar -= (char)0x800; } else { aChar += (char)0x2000; } if (bChar >= 0xe000) { bChar -= (char)0x800; } else { bChar += (char)0x2000; } } /* now aChar and bChar are in code point order */ return (int)aChar - (int)bChar; // int must be 32 bits wide } } // One is a prefix of the other, or, they are equal: return a.Length - b.Length; } } /// <summary> /// Creates a new <see cref="CharsRef"/> that points to a copy of the chars from /// <paramref name="other"/>. /// <para/> /// The returned <see cref="CharsRef"/> will have a Length of <c>other.Length</c> /// and an offset of zero. /// </summary> public static CharsRef DeepCopyOf(CharsRef other) { CharsRef clone = new CharsRef(); clone.CopyChars(other); return clone; } /// <summary> /// Performs internal consistency checks. /// Always returns true (or throws <see cref="InvalidOperationException"/>) /// </summary> public bool IsValid() { if (Chars == null) { throw new InvalidOperationException("chars is null"); } if (Length < 0) { throw new InvalidOperationException("Length is negative: " + Length); } if (Length > Chars.Length) { throw new InvalidOperationException("Length is out of bounds: " + Length + ",chars.Length=" + Chars.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > Chars.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",chars.Length=" + Chars.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+Length is negative: offset=" + Offset + ",Length=" + Length); } if (Offset + Length > Chars.Length) { throw new InvalidOperationException("offset+Length out of bounds: offset=" + Offset + ",Length=" + Length + ",chars.Length=" + Chars.Length); } return true; } } }
using System; using System.Data; using System.Data.Odbc; using ByteFX.Data.MySqlClient; using ByteFX.Data; using System.Collections; using JCSLA; using System.Net; namespace QED.Business { public class Servers : BusinessCollectionBase { #region Instance Data #endregion const string _table = "servers"; MySqlDBLayer _dbLayer; #region Collection Members public Server Add(Server obj) { obj.BusinessCollection = this; List.Add(obj); return obj; } public bool Contains(Server obj) { foreach(Server child in List) { if (obj.Equals(child)){ return true; } } return false; } public Server this[int id] { get{ return (Server) List[id]; } } public Server item(int id) { foreach(Server obj in List) { if (obj.Id == id) return obj; } return null; } #endregion #region DB Access and ctors public Servers() { } public void Update() { foreach (Server obj in List) { obj.Update(); } } public void LoadAll() { using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){ using(MySqlDataReader dr = MySqlDBLayer.LoadAll(conn, _table)){ Server server; while(dr.Read()) { server = new Server(dr); server.BusinessCollection = this; List.Add(server); } } } } #endregion #region Business Members #endregion #region System.Object overrides public override string ToString(){ return this.ToString(); } #endregion } public class Server : BusinessBase { #region Instance Data string _table = "servers"; int _id = -1; MySqlDBLayer _dbLayer; BusinessCollectionBase _businessCollection; string _dnsName = ""; string _desc = ""; bool _privateDB = false; #endregion #region DB Access / ctors public override string Table { get { return _table; } } public override object Conn { get { return Connections.Inst.item("QED_DB").MySqlConnection; } } private void Setup() { if (_dbLayer == null) { _dbLayer = new MySqlDBLayer(this); } } public override void SetId(int id) { /* This function is public for technical reasons. It is intended to be used only by the db * layer*/ _id = id; } public override BusinessCollectionBase BusinessCollection { get{ return _businessCollection; } set { _businessCollection = value; } } public Server() { Setup(); base.MarkNew(); } public Server(int id) { Setup(); this.Load(id); } public Server(MySqlDataReader dr) { this.Load(dr); } public void Load(int id) { SetId(id); using(MySqlConnection conn = (MySqlConnection) this.Conn){ conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + this.Table + " WHERE ID = @ID", conn); cmd.Parameters.Add("@Id", this.Id); using(MySqlDataReader dr = cmd.ExecuteReader()){ if (dr.HasRows) { dr.Read(); this.Load(dr); }else{ throw new Exception("Server " + id + " doesn't exist."); } } } } public void Load(MySqlDataReader dr) { Setup(); SetId(Convert.ToInt32(dr["Id"])); this._desc = Convert.ToString(dr["desc_"]); this._dnsName = Convert.ToString(dr["dnsName"]); MarkOld(); } public override void Update(){ _dbLayer.Update(); } public override Hashtable ParamHash { get { Hashtable paramHash = new Hashtable(); paramHash.Add("@Desc_", this.Desc); paramHash.Add("@DNSName", this.DNSName); return paramHash; } } #endregion #region Business Properties public override int Id{ get{ return _id; } } public string DNSName{ get{ return _dnsName; } set{ _dnsName = value; } } public string Desc{ get{ return _desc; } set{ _desc = value; } } public bool PrivateDB{ get { return _privateDB; } set { _privateDB = value; } } #endregion #region Validation Management public override bool IsValid { get { return (this.BrokenRules.Count == 0); } } public override BrokenRules BrokenRules { get { BrokenRules br = new BrokenRules(); return br; } } #endregion #region System.Object overrides public override string ToString(){ return this.ToString(); } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Reflection; namespace Gallio.Common.Reflection.Impl { /// <summary> /// The static reflection policy base class is intended to assist with the implementation /// of custom reflection policies defined over static metadata. /// </summary> /// <remarks> /// <para> /// It flattens out the code element hierarchy to ease implementation of new policies. /// It provides a mechanism for handling generic type substitutions to ensure a consistent and /// correct implementation of generic type and generic method instantiations. /// </para> /// <para> /// Reflection policy subclasses should not perform generic type substitutions themselves. /// The rest of the infrastructure will take care of these details automatically. However /// <see cref="StaticDeclaredTypeWrapper"/> and <see cref="StaticMethodWrapper"/> objects /// should be created with the type substitutions of the declaring type extended with /// generic type arguments. /// </para> /// </remarks> public abstract class StaticReflectionPolicy : BaseReflectionPolicy { private KeyedMemoizer<ITypeInfo, AttributeUsageAttribute> attributeUsageMemoizer = new KeyedMemoizer<ITypeInfo, AttributeUsageAttribute>(); #region Wrapper Comparisons /// <summary> /// Determines if two wrappers represent the same object. /// </summary> /// <param name="a">The first wrapper, not null.</param> /// <param name="b">The second wrapper, not null.</param> /// <returns>True if both wrapper represent the same object.</returns> protected internal virtual bool Equals(StaticWrapper a, StaticWrapper b) { return a.Handle.Equals(b.Handle); } /// <summary> /// Gets a hashcode for a wrapper. /// </summary> /// <param name="wrapper">The wrapper, not null.</param> /// <returns>The wrapper's hash code.</returns> protected internal virtual int GetHashCode(StaticWrapper wrapper) { return wrapper.Handle.GetHashCode(); } #endregion #region Assemblies /// <summary> /// Gets the custom attributes of an assembly. /// </summary> /// <param name="assembly">The assembly, not null.</param> /// <returns>The attributes.</returns> protected internal abstract IEnumerable<StaticAttributeWrapper> GetAssemblyCustomAttributes(StaticAssemblyWrapper assembly); /// <summary> /// Gets the name of an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <returns>The assembly name.</returns> protected internal abstract AssemblyName GetAssemblyName(StaticAssemblyWrapper assembly); /// <summary> /// Gets the path of an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <returns>The assembly path.</returns> protected internal abstract string GetAssemblyPath(StaticAssemblyWrapper assembly); /// <summary> /// Gets the references of an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <returns>The assembly references.</returns> protected internal abstract IList<AssemblyName> GetAssemblyReferences(StaticAssemblyWrapper assembly); /// <summary> /// Gets the public types exported by an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <returns>The types.</returns> protected internal abstract IList<StaticDeclaredTypeWrapper> GetAssemblyExportedTypes(StaticAssemblyWrapper assembly); /// <summary> /// Gets all types contained in an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <returns>The types.</returns> protected internal abstract IList<StaticDeclaredTypeWrapper> GetAssemblyTypes(StaticAssemblyWrapper assembly); /// <summary> /// Gets the specified named type within an assembly. /// </summary> /// <param name="assembly">The assembly wrapper, not null.</param> /// <param name="typeName">The type name, not null.</param> /// <returns>The type, or null if none.</returns> protected internal abstract StaticDeclaredTypeWrapper GetAssemblyType(StaticAssemblyWrapper assembly, string typeName); #endregion #region Custom Attributes /// <summary> /// Gets the constructor of an attribute. /// </summary> /// <param name="attribute">The attribute, not null.</param> /// <returns>The constructor.</returns> protected internal abstract StaticConstructorWrapper GetAttributeConstructor(StaticAttributeWrapper attribute); /// <summary> /// Gets the constructor arguments of an attribute. /// </summary> /// <param name="attribute">The attribute, not null.</param> /// <returns>The constructor argument values.</returns> protected internal abstract ConstantValue[] GetAttributeConstructorArguments(StaticAttributeWrapper attribute); /// <summary> /// Gets the field arguments of an attribute. /// </summary> /// <param name="attribute">The attribute, not null.</param> /// <returns>The field argument values.</returns> protected internal abstract IEnumerable<KeyValuePair<StaticFieldWrapper, ConstantValue>> GetAttributeFieldArguments(StaticAttributeWrapper attribute); /// <summary> /// Gets the property arguments of an attribute. /// </summary> /// <param name="attribute">The attribute, not null.</param> /// <returns>The property argument values.</returns> protected internal abstract IEnumerable<KeyValuePair<StaticPropertyWrapper, ConstantValue>> GetAttributePropertyArguments(StaticAttributeWrapper attribute); #endregion #region Member /// <summary> /// Gets the custom attributes of a member. /// </summary> /// <param name="member">The member, not null.</param> /// <returns>The custom attributes.</returns> protected internal abstract IEnumerable<StaticAttributeWrapper> GetMemberCustomAttributes(StaticMemberWrapper member); /// <summary> /// Gets the short name of a member. /// In the case of a generic type, should exclude the generic parameter count /// part of the name. eg. "`1" /// </summary> /// <param name="member">The member, not null.</param> /// <returns>The member's name.</returns> protected internal abstract string GetMemberName(StaticMemberWrapper member); /// <summary> /// Gets the source code location of a member. /// </summary> /// <param name="member">The member, not null.</param> /// <returns>The source code location, or <see cref="CodeLocation.Unknown" /> if not available.</returns> protected internal abstract CodeLocation GetMemberSourceLocation(StaticMemberWrapper member); #endregion #region Events /// <summary> /// Gets the attributes of an event. /// </summary> /// <param name="event">The event, not null.</param> /// <returns>The event attributes.</returns> protected internal abstract EventAttributes GetEventAttributes(StaticEventWrapper @event); /// <summary> /// Gets the add method of an event, or null if none. /// </summary> /// <param name="event">The event, not null.</param> /// <returns>The add method, or null if none.</returns> protected internal abstract StaticMethodWrapper GetEventAddMethod(StaticEventWrapper @event); /// <summary> /// Gets the raise method of an event, or null if none. /// </summary> /// <param name="event">The event, not null.</param> /// <returns>The raise method, or null if none.</returns> protected internal abstract StaticMethodWrapper GetEventRaiseMethod(StaticEventWrapper @event); /// <summary> /// Gets the remove method of an event, or null if none. /// </summary> /// <param name="event">The event, not null.</param> /// <returns>The remove method, or null if none.</returns> protected internal abstract StaticMethodWrapper GetEventRemoveMethod(StaticEventWrapper @event); /// <summary> /// Gets the event handler type of an event. /// </summary> /// <param name="event">The event, not null.</param> /// <returns>The event handler type.</returns> protected internal abstract StaticTypeWrapper GetEventHandlerType(StaticEventWrapper @event); #endregion #region Fields /// <summary> /// Gets the attributes of a field. /// </summary> /// <param name="field">The field, not null.</param> /// <returns>The field attributes.</returns> protected internal abstract FieldAttributes GetFieldAttributes(StaticFieldWrapper field); /// <summary> /// Gets the field type. /// </summary> /// <param name="field">The field, not null.</param> /// <returns>The field type.</returns> protected internal abstract StaticTypeWrapper GetFieldType(StaticFieldWrapper field); #endregion #region Properties /// <summary> /// Gets the attributes of a property. /// </summary> /// <param name="property">The property, not null.</param> /// <returns>The property attributes.</returns> protected internal abstract PropertyAttributes GetPropertyAttributes(StaticPropertyWrapper property); /// <summary> /// Gets the property type. /// </summary> /// <param name="property">The property, not null.</param> /// <returns>The property type.</returns> protected internal abstract StaticTypeWrapper GetPropertyType(StaticPropertyWrapper property); /// <summary> /// Gets the get method of a property, or null if none. /// </summary> /// <param name="property">The property, not null.</param> /// <returns>The get method, or null if none.</returns> protected internal abstract StaticMethodWrapper GetPropertyGetMethod(StaticPropertyWrapper property); /// <summary> /// Gets the set method of a property, or null if none. /// </summary> /// <param name="property">The property, not null.</param> /// <returns>The set method, or null if none.</returns> protected internal abstract StaticMethodWrapper GetPropertySetMethod(StaticPropertyWrapper property); #endregion #region Functions /// <summary> /// Gets the attributes of a function. /// </summary> /// <param name="function">The function, not null.</param> /// <returns>The function attributes.</returns> protected internal abstract MethodAttributes GetFunctionAttributes(StaticFunctionWrapper function); /// <summary> /// Gets the calling conventions of a function. /// </summary> /// <param name="function">The function, not null.</param> /// <returns>The function calling conventions.</returns> protected internal abstract CallingConventions GetFunctionCallingConvention(StaticFunctionWrapper function); /// <summary> /// Gets the parameters of a function. /// </summary> /// <param name="function">The function, not null.</param> /// <returns>The parameters.</returns> protected internal abstract IList<StaticParameterWrapper> GetFunctionParameters(StaticFunctionWrapper function); #endregion #region Constructors #endregion #region Methods /// <summary> /// Gets the generic parameters of a method. /// </summary> /// <param name="method">The method, not null.</param> /// <returns>The generic parameters.</returns> protected internal abstract IList<StaticGenericParameterWrapper> GetMethodGenericParameters(StaticMethodWrapper method); /// <summary> /// Gets the return parameter of a method. /// </summary> /// <param name="method">The method, not null.</param> /// <returns>The return parameter.</returns> protected internal abstract StaticParameterWrapper GetMethodReturnParameter(StaticMethodWrapper method); #endregion #region Parameters /// <summary> /// Gets the attributes of a parameter. /// </summary> /// <param name="parameter">The parameter, not null.</param> /// <returns>The parameter attributes.</returns> protected internal abstract ParameterAttributes GetParameterAttributes(StaticParameterWrapper parameter); /// <summary> /// Gets the custom attributes of a parameter. /// </summary> /// <param name="parameter">The parameter, not null.</param> /// <returns>The custom attributes.</returns> protected internal abstract IEnumerable<StaticAttributeWrapper> GetParameterCustomAttributes(StaticParameterWrapper parameter); /// <summary> /// Gets the name of a parameter. /// </summary> /// <param name="parameter">The parameter, not null.</param> /// <returns>The parameter's name.</returns> protected internal abstract string GetParameterName(StaticParameterWrapper parameter); /// <summary> /// Gets the parameter's position, or -1 if the parameter is a return value. /// </summary> /// <param name="parameter">The parameter, not null.</param> /// <returns>The parameter's position.</returns> protected internal abstract int GetParameterPosition(StaticParameterWrapper parameter); /// <summary> /// Gets the parameter type. /// </summary> /// <param name="parameter">The parameter, not null.</param> /// <returns>The parameter type.</returns> protected internal abstract StaticTypeWrapper GetParameterType(StaticParameterWrapper parameter); #endregion #region Declared Types /// <summary> /// Gets the attributes of a type. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type attributes.</returns> protected internal abstract TypeAttributes GetTypeAttributes(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the assembly that contains a type. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's assembly.</returns> protected internal abstract StaticAssemblyWrapper GetTypeAssembly(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the namespace that contains a type. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's namespace, or an empty string if it has none.</returns> protected internal abstract string GetTypeNamespace(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the base type of atype. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The base type.</returns> protected internal abstract StaticDeclaredTypeWrapper GetTypeBaseType(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the interfaces directly implemented by a type. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's interfaces.</returns> protected internal abstract IList<StaticDeclaredTypeWrapper> GetTypeInterfaces(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the generic parameters of a type, including all generic parameters /// of its declaring types if it is nested enumerated from outside in. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's generic parameters.</returns> protected internal abstract IList<StaticGenericParameterWrapper> GetTypeGenericParameters(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the constructors of a type. /// Only includes declared methods, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's constructors.</returns> protected internal abstract IEnumerable<StaticConstructorWrapper> GetTypeConstructors(StaticDeclaredTypeWrapper type); /// <summary> /// Gets the methods of a type including accessor methods for properties and events. /// Only includes declared methods, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <param name="reflectedType">The reflected type, not null.</param> /// <returns>The type's methods.</returns> protected internal abstract IEnumerable<StaticMethodWrapper> GetTypeMethods(StaticDeclaredTypeWrapper type, StaticDeclaredTypeWrapper reflectedType); /// <summary> /// Gets the properties of a type. /// Only includes declared methods, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <param name="reflectedType">The reflected type, not null.</param> /// <returns>The type's properties.</returns> protected internal abstract IEnumerable<StaticPropertyWrapper> GetTypeProperties(StaticDeclaredTypeWrapper type, StaticDeclaredTypeWrapper reflectedType); /// <summary> /// Gets the fields of a type. /// Only includes declared methods, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <param name="reflectedType">The reflected type, not null.</param> /// <returns>The type's fields.</returns> protected internal abstract IEnumerable<StaticFieldWrapper> GetTypeFields(StaticDeclaredTypeWrapper type, StaticDeclaredTypeWrapper reflectedType); /// <summary> /// Gets the events of a type. /// Only includes declared methods, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <param name="reflectedType">The reflected type, not null.</param> /// <returns>The type's events.</returns> protected internal abstract IEnumerable<StaticEventWrapper> GetTypeEvents(StaticDeclaredTypeWrapper type, StaticDeclaredTypeWrapper reflectedType); /// <summary> /// Gets the nested types of a type. /// Only includes declared nested types, not inherited ones. /// </summary> /// <param name="type">The type, not null.</param> /// <returns>The type's nested types.</returns> protected internal abstract IEnumerable<StaticTypeWrapper> GetTypeNestedTypes(StaticDeclaredTypeWrapper type); #endregion #region Generic Parameters /// <summary> /// Gets the attributes of a generic parameter. /// </summary> /// <param name="genericParameter">The generic parameter, not null.</param> /// <returns>The generic parameter attributes.</returns> protected internal abstract GenericParameterAttributes GetGenericParameterAttributes(StaticGenericParameterWrapper genericParameter); /// <summary> /// Gets the generic parameter position. /// </summary> /// <param name="genericParameter">The generic parameter, not null.</param> /// <returns>The generic parameter position.</returns> protected internal abstract int GetGenericParameterPosition(StaticGenericParameterWrapper genericParameter); /// <summary> /// Gets the generic parameter constraints. /// </summary> /// <param name="genericParameter">The generic parameter, not null.</param> /// <returns>The generic parameter constraints.</returns> protected internal abstract IList<StaticTypeWrapper> GetGenericParameterConstraints(StaticGenericParameterWrapper genericParameter); #endregion #region Internal Helpers internal AttributeUsageAttribute GetAttributeUsage(ITypeInfo attributeType) { return attributeUsageMemoizer.Memoize(attributeType, () => { if (attributeType.FullName == @"System.AttributeUsageAttribute") { // Note: Avoid indefinite recursion when determining whether AttributeUsageAttribute itself is inheritable. return new AttributeUsageAttribute(AttributeTargets.Class) { Inherited = true }; } Type resolvedAttributeType = attributeType.Resolve(false); if (! Reflector.IsUnresolved(resolvedAttributeType)) { // We use the resolved type when possible primarily because ReSharper's Metadata reflection // policy cannot resolve types in System and mscorlib which causes problems ironically when // trying to resolve AttributeUsageAttribute itself. However this is also a useful optimization // in the case where the type can be resolved. -- Jeff. var attributeUsages = (AttributeUsageAttribute[]) resolvedAttributeType.GetCustomAttributes( typeof(AttributeUsageAttribute), true); if (attributeUsages.Length != 0) return attributeUsages[0]; } else { try { var attributeUsage = AttributeUtils.GetAttribute<AttributeUsageAttribute>(attributeType, true); if (attributeUsage != null) return attributeUsage; } catch (TargetParameterCountException) { // This is a hack to work around the fact that ReSharper does not correctly handle // attribute parameters with enum values. In particular, this affects the first // parameter of AttributeUsageAttribute. -- Jeff. return new AttributeUsageAttribute(AttributeTargets.All) { Inherited = true, AllowMultiple = true }; } } return new AttributeUsageAttribute(AttributeTargets.All) { Inherited = true }; }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests { public static partial class SignedCmsTests { [Fact] public static void CmsSignerKeyIsNullByDefault() { CmsSigner cmsSigner = new CmsSigner(); Assert.Null(cmsSigner.PrivateKey); } [Fact] public static void CmsSignerKeyIsNullByDefaultWhenCertificateIsPassed() { using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert); Assert.Null(cmsSigner.PrivateKey); } } [Fact] public static void CmsSignerConstructorWithKeySetsProperty() { using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) using (RSA key = cert.GetRSAPrivateKey()) { CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); Assert.Same(key, cmsSigner.PrivateKey); } } [Fact] public static void SingUsingExplicitKeySetWithProperty() { using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) using (X509Certificate2 pubCert = new X509Certificate2(cert.RawData)) using (RSA key = cert.GetRSAPrivateKey()) { byte[] content = { 1, 2, 3, 4, 19 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo); CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, pubCert); cmsSigner.PrivateKey = key; cms.ComputeSignature(cmsSigner); cms.CheckSignature(true); Assert.Equal(1, cms.SignerInfos.Count); Assert.Equal(pubCert, cms.SignerInfos[0].Certificate); } } [Fact] public static void SignCmsUsingExplicitRSAKey() { using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) using (RSA key = cert.GetRSAPrivateKey()) { VerifyWithExplicitPrivateKey(cert, key); } } [Fact] public static void SignCmsUsingExplicitDSAKey() { using (X509Certificate2 cert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) using (DSA key = cert.GetDSAPrivateKey()) { VerifyWithExplicitPrivateKey(cert, key); } } [Fact] public static void SignCmsUsingExplicitECDsaKey() { using (X509Certificate2 cert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) using (ECDsa key = cert.GetECDsaPrivateKey()) { VerifyWithExplicitPrivateKey(cert, key); } } [Fact] public static void SignCmsUsingExplicitECDsaP521Key() { using (X509Certificate2 cert = Certificates.ECDsaP521Win.TryGetCertificateWithPrivateKey()) using (ECDsa key = cert.GetECDsaPrivateKey()) { VerifyWithExplicitPrivateKey(cert, key); } } [Fact] public static void CounterSignCmsUsingExplicitRSAKeyForFirstSignerAndDSAForCounterSignature() { using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) using (RSA key = cert.GetRSAPrivateKey()) using (X509Certificate2 counterSignerCert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) using (DSA counterSignerKey = counterSignerCert.GetDSAPrivateKey()) { VerifyCounterSignatureWithExplicitPrivateKey(cert, key, counterSignerCert, counterSignerKey); } } [Fact] public static void CounterSignCmsUsingExplicitDSAKeyForFirstSignerAndECDsaForCounterSignature() { using (X509Certificate2 cert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) using (DSA key = cert.GetDSAPrivateKey()) using (X509Certificate2 counterSignerCert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) using (ECDsa counterSignerKey = counterSignerCert.GetECDsaPrivateKey()) { VerifyCounterSignatureWithExplicitPrivateKey(cert, key, counterSignerCert, counterSignerKey); } } [Fact] public static void CounterSignCmsUsingExplicitECDsaKeyForFirstSignerAndRSAForCounterSignature() { using (X509Certificate2 cert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) using (ECDsa key = cert.GetECDsaPrivateKey()) using (X509Certificate2 counterSignerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) using (RSA counterSignerKey = counterSignerCert.GetRSAPrivateKey()) { VerifyCounterSignatureWithExplicitPrivateKey(cert, key, counterSignerCert, counterSignerKey); } } [Fact] public static void SignCmsUsingRSACertAndECDsaKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.GetCertificate()) using (ECDsa key = ECDsa.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] public static void SignCmsUsingDSACertAndECDsaKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.Dsa1024.GetCertificate()) using (ECDsa key = ECDsa.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); signer.IncludeOption = X509IncludeOption.EndCertOnly; signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] public static void SignCmsUsingEDCSaCertAndRSAaKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.ECDsaP256Win.GetCertificate()) using (RSA key = RSA.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] public static void SignCmsUsingRSACertWithNotMatchingKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.GetCertificate()) using (RSA key = RSA.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // Creating DSA keys is not supported on OSX public static void SignCmsUsingDSACertWithNotMatchingKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.Dsa1024.GetCertificate()) using (DSA key = DSA.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); signer.IncludeOption = X509IncludeOption.EndCertOnly; signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] public static void SignCmsUsingECDsaCertWithNotMatchingKeyThrows() { byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo, detached: false); using (X509Certificate2 cert = Certificates.ECDsaP256Win.GetCertificate()) using (ECDsa key = ECDsa.Create()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert, key); Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer)); } } [Fact] public static void AddCertificate() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); int numOfCerts = cms.Certificates.Count; using (X509Certificate2 newCert = Certificates.RSAKeyTransfer1.GetCertificate()) { cms.AddCertificate(newCert); Assert.Equal(numOfCerts + 1, cms.Certificates.Count); Assert.True(cms.Certificates.Contains(newCert)); cms.CheckSignature(true); } } [Fact] public static void AddCertificateWithPrivateKey() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); int numOfCerts = cms.Certificates.Count; using (X509Certificate2 newCert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { Assert.True(newCert.HasPrivateKey); cms.AddCertificate(newCert); Assert.Equal(numOfCerts + 1, cms.Certificates.Count); X509Certificate2 addedCert = cms.Certificates.OfType<X509Certificate2>().Where((cert) => cert.Equals(newCert)).Single(); Assert.False(addedCert.HasPrivateKey); Assert.Equal(newCert, addedCert); cms.CheckSignature(true); } } [Fact] public static void RemoveCertificate() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); var expectedCerts = new HashSet<X509Certificate2>(cms.Certificates.OfType<X509Certificate2>()); using (X509Certificate2 cert1 = Certificates.RSAKeyTransfer1.GetCertificate()) using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.GetCertificate()) { Assert.NotEqual(cert1, cert2); cms.AddCertificate(cert1); cms.AddCertificate(cert2); expectedCerts.Add(cert2); cms.RemoveCertificate(cert1); Assert.Equal(expectedCerts.Count, cms.Certificates.Count); foreach (X509Certificate2 documentCert in cms.Certificates) { Assert.True(expectedCerts.Contains(documentCert)); } } } [Fact] public static void RemoveNonExistingCertificate() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); using (X509Certificate2 certToRemove = Certificates.RSAKeyTransfer1.GetCertificate()) { Assert.Throws<CryptographicException>(() => cms.RemoveCertificate(certToRemove)); } } [Fact] public static void RemoveAllCertsAddBackSignerCert() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); SignerInfo signerInfoBeforeRemoval = cms.SignerInfos[0]; X509Certificate2 signerCert = signerInfoBeforeRemoval.Certificate; while (cms.Certificates.Count > 0) { cms.RemoveCertificate(cms.Certificates[0]); } // Signer info should be gone Assert.Throws<CryptographicException>(() => cms.CheckSignature(true)); Assert.Null(cms.SignerInfos[0].Certificate); Assert.NotNull(signerInfoBeforeRemoval.Certificate); cms.AddCertificate(signerCert); cms.CheckSignature(true); Assert.Equal(1, cms.Certificates.Count); } [Fact] public static void AddExistingCertificate() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); using (X509Certificate2 newCert = Certificates.RSAKeyTransfer1.GetCertificate()) { cms.AddCertificate(newCert); Assert.Throws<CryptographicException>(() => cms.AddCertificate(newCert)); } } [Fact] public static void AddAttributeToIndefiniteLengthContent() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.IndefiniteLengthContentDocument); cms.SignerInfos[0].AddUnsignedAttribute(new Pkcs9DocumentDescription("Indefinite length test")); byte[] encoded = cms.Encode(); cms = new SignedCms(); cms.Decode(encoded); // It should sort first, because it's smaller. Assert.Equal(Oids.DocumentDescription, cms.SignerInfos[0].UnsignedAttributes[0].Oid.Value); } private static void VerifyWithExplicitPrivateKey(X509Certificate2 cert, AsymmetricAlgorithm key) { using (var pubCert = new X509Certificate2(cert.RawData)) { Assert.False(pubCert.HasPrivateKey); byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo); CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, pubCert, key) { IncludeOption = X509IncludeOption.EndCertOnly, DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1) }; cms.ComputeSignature(signer); cms.CheckSignature(true); Assert.Equal(1, cms.SignerInfos.Count); Assert.Equal(pubCert, cms.SignerInfos[0].Certificate); } } private static void VerifyCounterSignatureWithExplicitPrivateKey(X509Certificate2 cert, AsymmetricAlgorithm key, X509Certificate2 counterSignerCert, AsymmetricAlgorithm counterSignerKey) { Assert.NotNull(key); Assert.NotNull(counterSignerKey); using (var pubCert = new X509Certificate2(cert.RawData)) using (var counterSignerPubCert = new X509Certificate2(counterSignerCert.RawData)) { Assert.False(pubCert.HasPrivateKey); byte[] content = { 9, 8, 7, 6, 5 }; ContentInfo contentInfo = new ContentInfo(content); SignedCms cms = new SignedCms(contentInfo); CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, pubCert, key) { IncludeOption = X509IncludeOption.EndCertOnly, DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1) }; CmsSigner cmsCounterSigner = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, counterSignerPubCert, counterSignerKey) { IncludeOption = X509IncludeOption.EndCertOnly, DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1) }; cms.ComputeSignature(cmsSigner); Assert.Equal(1, cms.SignerInfos.Count); Assert.Equal(pubCert, cms.SignerInfos[0].Certificate); cms.SignerInfos[0].ComputeCounterSignature(cmsCounterSigner); cms.CheckSignature(true); Assert.Equal(1, cms.SignerInfos[0].CounterSignerInfos.Count); Assert.Equal(counterSignerPubCert, cms.SignerInfos[0].CounterSignerInfos[0].Certificate); } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if WCF_SUPPORTED namespace NLog.LogReceiverService { using System.ServiceModel.Description; using System; using System.ComponentModel; using System.Net; using System.ServiceModel; using System.ServiceModel.Channels; /// <summary> /// Abstract base class for the WcfLogReceiverXXXWay classes. It can only be /// used internally (see internal constructor). It passes off any Channel usage /// to the inheriting class. /// </summary> /// <typeparam name="TService">Type of the WCF service.</typeparam> public abstract class WcfLogReceiverClientBase<TService> : ClientBase<TService>, IWcfLogReceiverClient where TService : class { /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> protected WcfLogReceiverClientBase() : base() { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName) : base(endpointConfigurationName) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } /// <summary> /// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class. /// </summary> /// <param name="binding">The binding.</param> /// <param name="remoteAddress">The remote address.</param> protected WcfLogReceiverClientBase(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } /// <summary> /// Occurs when the log message processing has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> ProcessLogMessagesCompleted; /// <summary> /// Occurs when Open operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> OpenCompleted; /// <summary> /// Occurs when Close operation has completed. /// </summary> public event EventHandler<AsyncCompletedEventArgs> CloseCompleted; #if !NET4_0 && !NET3_5 && !NETSTANDARD /// <summary> /// Gets or sets the cookie container. /// </summary> /// <value>The cookie container.</value> public CookieContainer CookieContainer { get { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); return httpCookieContainerManager?.CookieContainer; } set { var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>(); if (httpCookieContainerManager != null) { httpCookieContainerManager.CookieContainer = value; } else { throw new InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpCookieContainerBindingElement."); } } } #endif /// <summary> /// Opens the client asynchronously. /// </summary> public void OpenAsync() { OpenAsync(null); } /// <summary> /// Opens the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void OpenAsync(object userState) { InvokeAsync(OnBeginOpen, null, OnEndOpen, OnOpenCompleted, userState); } /// <summary> /// Closes the client asynchronously. /// </summary> public void CloseAsync() { CloseAsync(null); } /// <summary> /// Closes the client asynchronously. /// </summary> /// <param name="userState">User-specific state.</param> public void CloseAsync(object userState) { InvokeAsync(OnBeginClose, null, OnEndClose, OnCloseCompleted, userState); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> public void ProcessLogMessagesAsync(NLogEvents events) { ProcessLogMessagesAsync(events, null); } /// <summary> /// Processes the log messages asynchronously. /// </summary> /// <param name="events">The events to send.</param> /// <param name="userState">User-specific state.</param> public void ProcessLogMessagesAsync(NLogEvents events, object userState) { InvokeAsync( OnBeginProcessLogMessages, new object[] { events }, OnEndProcessLogMessages, OnProcessLogMessagesCompleted, userState); } /// <summary> /// Begins processing of log messages. /// </summary> /// <param name="events">The events to send.</param> /// <param name="callback">The callback.</param> /// <param name="asyncState">Asynchronous state.</param> /// <returns> /// IAsyncResult value which can be passed to <see cref="ILogReceiverOneWayClient.EndProcessLogMessages"/>. /// </returns> public abstract IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState); /// <summary> /// Ends asynchronous processing of log messages. /// </summary> /// <param name="result">The result.</param> public abstract void EndProcessLogMessages(IAsyncResult result); private IAsyncResult OnBeginProcessLogMessages(object[] inValues, AsyncCallback callback, object asyncState) { var events = (NLogEvents)inValues[0]; return BeginProcessLogMessages(events, callback, asyncState); } private object[] OnEndProcessLogMessages(IAsyncResult result) { EndProcessLogMessages(result); return null; } private void OnProcessLogMessagesCompleted(object state) { if (ProcessLogMessagesCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; ProcessLogMessagesCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginOpen(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginOpen(callback, asyncState); } private object[] OnEndOpen(IAsyncResult result) { ((ICommunicationObject)this).EndOpen(result); return null; } private void OnOpenCompleted(object state) { if (OpenCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; OpenCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } private IAsyncResult OnBeginClose(object[] inValues, AsyncCallback callback, object asyncState) { return ((ICommunicationObject)this).BeginClose(callback, asyncState); } private object[] OnEndClose(IAsyncResult result) { ((ICommunicationObject)this).EndClose(result); return null; } private void OnCloseCompleted(object state) { if (CloseCompleted != null) { var e = (InvokeAsyncCompletedEventArgs)state; CloseCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } } } #endif
using J2N.Threading.Atomic; using Lucene.Net.Index; using Lucene.Net.Util.Fst; using System; using System.Collections.Generic; using System.IO; namespace Lucene.Net.Codecs.Lucene42 { /* * 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 BinaryDocValues = Lucene.Net.Index.BinaryDocValues; using BlockPackedReader = Lucene.Net.Util.Packed.BlockPackedReader; using ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput; using BytesRef = Lucene.Net.Util.BytesRef; using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using DocValues = Lucene.Net.Index.DocValues; using DocValuesType = Lucene.Net.Index.DocValuesType; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using IBits = Lucene.Net.Util.IBits; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using Int32sRef = Lucene.Net.Util.Int32sRef; using IOUtils = Lucene.Net.Util.IOUtils; using MonotonicBlockPackedReader = Lucene.Net.Util.Packed.MonotonicBlockPackedReader; using NumericDocValues = Lucene.Net.Index.NumericDocValues; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using PagedBytes = Lucene.Net.Util.PagedBytes; using PositiveInt32Outputs = Lucene.Net.Util.Fst.PositiveInt32Outputs; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using SegmentReadState = Lucene.Net.Index.SegmentReadState; using SortedDocValues = Lucene.Net.Index.SortedDocValues; using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues; using TermsEnum = Lucene.Net.Index.TermsEnum; using Util = Lucene.Net.Util.Fst.Util; /// <summary> /// Reader for <see cref="Lucene42DocValuesFormat"/>. /// </summary> internal class Lucene42DocValuesProducer : DocValuesProducer { // metadata maps (just file pointers and minimal stuff) private readonly IDictionary<int, NumericEntry> numerics; private readonly IDictionary<int, BinaryEntry> binaries; private readonly IDictionary<int, FSTEntry> fsts; private readonly IndexInput data; private readonly int version; // ram instances we have already loaded private readonly IDictionary<int, NumericDocValues> numericInstances = new Dictionary<int, NumericDocValues>(); private readonly IDictionary<int, BinaryDocValues> binaryInstances = new Dictionary<int, BinaryDocValues>(); private readonly IDictionary<int, FST<long?>> fstInstances = new Dictionary<int, FST<long?>>(); private readonly int maxDoc; private readonly AtomicInt64 ramBytesUsed; internal const sbyte NUMBER = 0; internal const sbyte BYTES = 1; internal const sbyte FST = 2; internal const int BLOCK_SIZE = 4096; internal const sbyte DELTA_COMPRESSED = 0; internal const sbyte TABLE_COMPRESSED = 1; internal const sbyte UNCOMPRESSED = 2; internal const sbyte GCD_COMPRESSED = 3; internal const int VERSION_START = 0; internal const int VERSION_GCD_COMPRESSION = 1; internal const int VERSION_CHECKSUM = 2; internal const int VERSION_CURRENT = VERSION_CHECKSUM; internal Lucene42DocValuesProducer(SegmentReadState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension) { maxDoc = state.SegmentInfo.DocCount; string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension); // read in the entries from the metadata file. ChecksumIndexInput @in = state.Directory.OpenChecksumInput(metaName, state.Context); bool success = false; ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOfInstance(this.GetType())); try { version = CodecUtil.CheckHeader(@in, metaCodec, VERSION_START, VERSION_CURRENT); numerics = new Dictionary<int, NumericEntry>(); binaries = new Dictionary<int, BinaryEntry>(); fsts = new Dictionary<int, FSTEntry>(); ReadFields(@in, state.FieldInfos); if (version >= VERSION_CHECKSUM) { CodecUtil.CheckFooter(@in); } else { #pragma warning disable 612, 618 CodecUtil.CheckEOF(@in); #pragma warning restore 612, 618 } success = true; } finally { if (success) { IOUtils.Dispose(@in); } else { IOUtils.DisposeWhileHandlingException(@in); } } success = false; try { string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension); data = state.Directory.OpenInput(dataName, state.Context); int version2 = CodecUtil.CheckHeader(data, dataCodec, VERSION_START, VERSION_CURRENT); if (version != version2) { throw new CorruptIndexException("Format versions mismatch"); } success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(this.data); } } } private void ReadFields(IndexInput meta, FieldInfos infos) { int fieldNumber = meta.ReadVInt32(); while (fieldNumber != -1) { // check should be: infos.fieldInfo(fieldNumber) != null, which incorporates negative check // but docvalues updates are currently buggy here (loading extra stuff, etc): LUCENE-5616 if (fieldNumber < 0) { // trickier to validate more: because we re-use for norms, because we use multiple entries // for "composite" types like sortedset, etc. throw new CorruptIndexException("Invalid field number: " + fieldNumber + ", input=" + meta); } int fieldType = meta.ReadByte(); if (fieldType == NUMBER) { var entry = new NumericEntry(); entry.Offset = meta.ReadInt64(); entry.Format = (sbyte)meta.ReadByte(); switch (entry.Format) { case DELTA_COMPRESSED: case TABLE_COMPRESSED: case GCD_COMPRESSED: case UNCOMPRESSED: break; default: throw new CorruptIndexException("Unknown format: " + entry.Format + ", input=" + meta); } if (entry.Format != UNCOMPRESSED) { entry.PackedInt32sVersion = meta.ReadVInt32(); } numerics[fieldNumber] = entry; } else if (fieldType == BYTES) { BinaryEntry entry = new BinaryEntry(); entry.Offset = meta.ReadInt64(); entry.NumBytes = meta.ReadInt64(); entry.MinLength = meta.ReadVInt32(); entry.MaxLength = meta.ReadVInt32(); if (entry.MinLength != entry.MaxLength) { entry.PackedInt32sVersion = meta.ReadVInt32(); entry.BlockSize = meta.ReadVInt32(); } binaries[fieldNumber] = entry; } else if (fieldType == FST) { FSTEntry entry = new FSTEntry(); entry.Offset = meta.ReadInt64(); entry.NumOrds = meta.ReadVInt64(); fsts[fieldNumber] = entry; } else { throw new CorruptIndexException("invalid entry type: " + fieldType + ", input=" + meta); } fieldNumber = meta.ReadVInt32(); } } public override NumericDocValues GetNumeric(FieldInfo field) { lock (this) { NumericDocValues instance; if (!numericInstances.TryGetValue(field.Number, out instance) || instance == null) { instance = LoadNumeric(field); numericInstances[field.Number] = instance; } return instance; } } public override long RamBytesUsed() => ramBytesUsed; public override void CheckIntegrity() { if (version >= VERSION_CHECKSUM) { CodecUtil.ChecksumEntireFile(data); } } private NumericDocValues LoadNumeric(FieldInfo field) { NumericEntry entry = numerics[field.Number]; data.Seek(entry.Offset); switch (entry.Format) { case TABLE_COMPRESSED: int size = data.ReadVInt32(); if (size > 256) { throw new CorruptIndexException("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + data); } var decode = new long[size]; for (int i = 0; i < decode.Length; i++) { decode[i] = data.ReadInt64(); } int formatID = data.ReadVInt32(); int bitsPerValue = data.ReadVInt32(); PackedInt32s.Reader ordsReader = PackedInt32s.GetReaderNoHeader(data, PackedInt32s.Format.ById(formatID), entry.PackedInt32sVersion, maxDoc, bitsPerValue); ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(decode) + ordsReader.RamBytesUsed()); return new NumericDocValuesAnonymousInnerClassHelper(decode, ordsReader); case DELTA_COMPRESSED: int blockSize = data.ReadVInt32(); var reader = new BlockPackedReader(data, entry.PackedInt32sVersion, blockSize, maxDoc, false); ramBytesUsed.AddAndGet(reader.RamBytesUsed()); return reader; case UNCOMPRESSED: byte[] bytes = new byte[maxDoc]; data.ReadBytes(bytes, 0, bytes.Length); ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(bytes)); return new NumericDocValuesAnonymousInnerClassHelper2(this, bytes); case GCD_COMPRESSED: long min = data.ReadInt64(); long mult = data.ReadInt64(); int quotientBlockSize = data.ReadVInt32(); BlockPackedReader quotientReader = new BlockPackedReader(data, entry.PackedInt32sVersion, quotientBlockSize, maxDoc, false); ramBytesUsed.AddAndGet(quotientReader.RamBytesUsed()); return new NumericDocValuesAnonymousInnerClassHelper3(min, mult, quotientReader); default: throw new InvalidOperationException(); } } private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues { private readonly long[] decode; private readonly PackedInt32s.Reader ordsReader; public NumericDocValuesAnonymousInnerClassHelper(long[] decode, PackedInt32s.Reader ordsReader) { this.decode = decode; this.ordsReader = ordsReader; } public override long Get(int docID) { return decode[(int)ordsReader.Get(docID)]; } } private class NumericDocValuesAnonymousInnerClassHelper2 : NumericDocValues { private readonly byte[] bytes; public NumericDocValuesAnonymousInnerClassHelper2(Lucene42DocValuesProducer outerInstance, byte[] bytes) { this.bytes = bytes; } public override long Get(int docID) { return (sbyte)bytes[docID]; } } private class NumericDocValuesAnonymousInnerClassHelper3 : NumericDocValues { private readonly long min; private readonly long mult; private readonly BlockPackedReader quotientReader; public NumericDocValuesAnonymousInnerClassHelper3(long min, long mult, BlockPackedReader quotientReader) { this.min = min; this.mult = mult; this.quotientReader = quotientReader; } public override long Get(int docID) { return min + mult * quotientReader.Get(docID); } } public override BinaryDocValues GetBinary(FieldInfo field) { lock (this) { BinaryDocValues instance; if (!binaryInstances.TryGetValue(field.Number, out instance) || instance == null) { instance = LoadBinary(field); binaryInstances[field.Number] = instance; } return instance; } } private BinaryDocValues LoadBinary(FieldInfo field) { BinaryEntry entry = binaries[field.Number]; data.Seek(entry.Offset); PagedBytes bytes = new PagedBytes(16); bytes.Copy(data, entry.NumBytes); PagedBytes.Reader bytesReader = bytes.Freeze(true); if (entry.MinLength == entry.MaxLength) { int fixedLength = entry.MinLength; ramBytesUsed.AddAndGet(bytes.RamBytesUsed()); return new BinaryDocValuesAnonymousInnerClassHelper(bytesReader, fixedLength); } else { MonotonicBlockPackedReader addresses = new MonotonicBlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, maxDoc, false); ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + addresses.RamBytesUsed()); return new BinaryDocValuesAnonymousInnerClassHelper2(bytesReader, addresses); } } private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues { private readonly PagedBytes.Reader bytesReader; private readonly int fixedLength; public BinaryDocValuesAnonymousInnerClassHelper(PagedBytes.Reader bytesReader, int fixedLength) { this.bytesReader = bytesReader; this.fixedLength = fixedLength; } public override void Get(int docID, BytesRef result) { bytesReader.FillSlice(result, fixedLength * (long)docID, fixedLength); } } private class BinaryDocValuesAnonymousInnerClassHelper2 : BinaryDocValues { private readonly PagedBytes.Reader bytesReader; private readonly MonotonicBlockPackedReader addresses; public BinaryDocValuesAnonymousInnerClassHelper2(PagedBytes.Reader bytesReader, MonotonicBlockPackedReader addresses) { this.bytesReader = bytesReader; this.addresses = addresses; } public override void Get(int docID, BytesRef result) { long startAddress = docID == 0 ? 0 : addresses.Get(docID - 1); long endAddress = addresses.Get(docID); bytesReader.FillSlice(result, startAddress, (int)(endAddress - startAddress)); } } public override SortedDocValues GetSorted(FieldInfo field) { FSTEntry entry = fsts[field.Number]; FST<long?> instance; lock (this) { if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null) { data.Seek(entry.Offset); instance = new FST<long?>(data, PositiveInt32Outputs.Singleton); ramBytesUsed.AddAndGet(instance.GetSizeInBytes()); fstInstances[field.Number] = instance; } } var docToOrd = GetNumeric(field); var fst = instance; // per-thread resources var @in = fst.GetBytesReader(); var firstArc = new FST.Arc<long?>(); var scratchArc = new FST.Arc<long?>(); var scratchInts = new Int32sRef(); var fstEnum = new BytesRefFSTEnum<long?>(fst); return new SortedDocValuesAnonymousInnerClassHelper(entry, docToOrd, fst, @in, firstArc, scratchArc, scratchInts, fstEnum); } private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues { private readonly FSTEntry entry; private readonly NumericDocValues docToOrd; private readonly FST<long?> fst; private readonly FST.BytesReader @in; private readonly FST.Arc<long?> firstArc; private readonly FST.Arc<long?> scratchArc; private readonly Int32sRef scratchInts; private readonly BytesRefFSTEnum<long?> fstEnum; public SortedDocValuesAnonymousInnerClassHelper(FSTEntry entry, NumericDocValues docToOrd, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum) { this.entry = entry; this.docToOrd = docToOrd; this.fst = fst; this.@in = @in; this.firstArc = firstArc; this.scratchArc = scratchArc; this.scratchInts = scratchInts; this.fstEnum = fstEnum; } public override int GetOrd(int docID) { return (int)docToOrd.Get(docID); } public override void LookupOrd(int ord, BytesRef result) { try { @in.Position = 0; fst.GetFirstArc(firstArc); Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts); result.Bytes = new byte[output.Length]; result.Offset = 0; result.Length = 0; Util.ToBytesRef(output, result); } catch (IOException bogus) { throw new Exception(bogus.ToString(), bogus); } } public override int LookupTerm(BytesRef key) { try { BytesRefFSTEnum.InputOutput<long?> o = fstEnum.SeekCeil(key); if (o == null) { return -ValueCount - 1; } else if (o.Input.Equals(key)) { return (int)o.Output.GetValueOrDefault(); } else { return (int)-o.Output.GetValueOrDefault() - 1; } } catch (IOException bogus) { throw new Exception(bogus.ToString(), bogus); } } public override int ValueCount => (int)entry.NumOrds; public override TermsEnum GetTermsEnum() { return new FSTTermsEnum(fst); } } public override SortedSetDocValues GetSortedSet(FieldInfo field) { FSTEntry entry = fsts[field.Number]; if (entry.NumOrds == 0) { return DocValues.EMPTY_SORTED_SET; // empty FST! } FST<long?> instance; lock (this) { if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null) { data.Seek(entry.Offset); instance = new FST<long?>(data, PositiveInt32Outputs.Singleton); ramBytesUsed.AddAndGet(instance.GetSizeInBytes()); fstInstances[field.Number] = instance; } } BinaryDocValues docToOrds = GetBinary(field); FST<long?> fst = instance; // per-thread resources var @in = fst.GetBytesReader(); var firstArc = new FST.Arc<long?>(); var scratchArc = new FST.Arc<long?>(); var scratchInts = new Int32sRef(); var fstEnum = new BytesRefFSTEnum<long?>(fst); var @ref = new BytesRef(); var input = new ByteArrayDataInput(); return new SortedSetDocValuesAnonymousInnerClassHelper(entry, docToOrds, fst, @in, firstArc, scratchArc, scratchInts, fstEnum, @ref, input); } private class SortedSetDocValuesAnonymousInnerClassHelper : SortedSetDocValues { private readonly FSTEntry entry; private readonly BinaryDocValues docToOrds; private readonly FST<long?> fst; private readonly FST.BytesReader @in; private readonly FST.Arc<long?> firstArc; private readonly FST.Arc<long?> scratchArc; private readonly Int32sRef scratchInts; private readonly BytesRefFSTEnum<long?> fstEnum; private readonly BytesRef @ref; private readonly ByteArrayDataInput input; public SortedSetDocValuesAnonymousInnerClassHelper(FSTEntry entry, BinaryDocValues docToOrds, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum, BytesRef @ref, ByteArrayDataInput input) { this.entry = entry; this.docToOrds = docToOrds; this.fst = fst; this.@in = @in; this.firstArc = firstArc; this.scratchArc = scratchArc; this.scratchInts = scratchInts; this.fstEnum = fstEnum; this.@ref = @ref; this.input = input; } private long currentOrd; public override long NextOrd() { if (input.Eof) { return NO_MORE_ORDS; } else { currentOrd += input.ReadVInt64(); return currentOrd; } } public override void SetDocument(int docID) { docToOrds.Get(docID, @ref); input.Reset(@ref.Bytes, @ref.Offset, @ref.Length); currentOrd = 0; } public override void LookupOrd(long ord, BytesRef result) { try { @in.Position = 0; fst.GetFirstArc(firstArc); Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts); result.Bytes = new byte[output.Length]; result.Offset = 0; result.Length = 0; Lucene.Net.Util.Fst.Util.ToBytesRef(output, result); } catch (IOException bogus) { throw new Exception(bogus.ToString(), bogus); } } public override long LookupTerm(BytesRef key) { try { var o = fstEnum.SeekCeil(key); if (o == null) { return -ValueCount - 1; } else if (o.Input.Equals(key)) { return (int)o.Output.GetValueOrDefault(); } else { return -o.Output.GetValueOrDefault() - 1; } } catch (IOException bogus) { throw new Exception(bogus.ToString(), bogus); } } public override long ValueCount => entry.NumOrds; public override TermsEnum GetTermsEnum() { return new FSTTermsEnum(fst); } } public override IBits GetDocsWithField(FieldInfo field) { if (field.DocValuesType == DocValuesType.SORTED_SET) { return DocValues.DocsWithValue(GetSortedSet(field), maxDoc); } else { return new Lucene.Net.Util.Bits.MatchAllBits(maxDoc); } } protected override void Dispose(bool disposing) { if (disposing) { data.Dispose(); } } internal class NumericEntry { internal long Offset { get; set; } internal sbyte Format { get; set; } /// <summary> /// NOTE: This was packedIntsVersion (field) in Lucene /// </summary> internal int PackedInt32sVersion { get; set; } } internal class BinaryEntry { internal long Offset { get; set; } internal long NumBytes { get; set; } internal int MinLength { get; set; } internal int MaxLength { get; set; } /// <summary> /// NOTE: This was packedIntsVersion (field) in Lucene /// </summary> internal int PackedInt32sVersion { get; set; } internal int BlockSize { get; set; } } internal class FSTEntry { internal long Offset { get; set; } internal long NumOrds { get; set; } } // exposes FSTEnum directly as a TermsEnum: avoids binary-search next() internal class FSTTermsEnum : TermsEnum { internal readonly BytesRefFSTEnum<long?> @in; // this is all for the complicated seek(ord)... // maybe we should add a FSTEnum that supports this operation? internal readonly FST<long?> fst; internal readonly FST.BytesReader bytesReader; internal readonly FST.Arc<long?> firstArc = new FST.Arc<long?>(); internal readonly FST.Arc<long?> scratchArc = new FST.Arc<long?>(); internal readonly Int32sRef scratchInts = new Int32sRef(); internal readonly BytesRef scratchBytes = new BytesRef(); internal FSTTermsEnum(FST<long?> fst) { this.fst = fst; @in = new BytesRefFSTEnum<long?>(fst); bytesReader = fst.GetBytesReader(); } public override bool MoveNext() => @in.MoveNext(); [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (MoveNext()) return @in.Current.Input; return null; } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; public override SeekStatus SeekCeil(BytesRef text) { if (@in.SeekCeil(text) == null) { return SeekStatus.END; } else if (Term.Equals(text)) { // TODO: add SeekStatus to FSTEnum like in https://issues.apache.org/jira/browse/LUCENE-3729 // to remove this comparision? return SeekStatus.FOUND; } else { return SeekStatus.NOT_FOUND; } } public override bool SeekExact(BytesRef text) { if (@in.SeekExact(text) == null) { return false; } else { return true; } } public override void SeekExact(long ord) { // TODO: would be better to make this simpler and faster. // but we dont want to introduce a bug that corrupts our enum state! bytesReader.Position = 0; fst.GetFirstArc(firstArc); Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, bytesReader, firstArc, scratchArc, scratchInts); scratchBytes.Bytes = new byte[output.Length]; scratchBytes.Offset = 0; scratchBytes.Length = 0; Lucene.Net.Util.Fst.Util.ToBytesRef(output, scratchBytes); // TODO: we could do this lazily, better to try to push into FSTEnum though? @in.SeekExact(scratchBytes); } public override BytesRef Term => @in.Current.Input; public override long Ord => @in.Current.Output.GetValueOrDefault(); public override int DocFreq => throw new NotSupportedException(); public override long TotalTermFreq => throw new NotSupportedException(); public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { throw new NotSupportedException(); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { throw new NotSupportedException(); } } } }
using System.Collections.Generic; using System.Xml.Linq; namespace WixSharp { /// <summary> /// Defines WiX Feature. /// <para> /// All installable WiX components belong to one or more features. By default, if no <see cref="Feature"/>s are defined by user, Wix# creates "Complete" /// feature, which contains all installable components. /// </para> /// </summary> /// <example> /// <list type="bullet"> /// /// <item> /// <description>The example of defining <see cref="Feature"/>s explicitly: /// <code> /// Feature binaries = new Feature("My Product Binaries"); /// Feature docs = new Feature("My Product Documentation"); /// /// var project = /// new Project("My Product", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// new File(binaries, @"AppFiles\MyApp.exe", /// ... /// </code> /// </description> /// </item> /// /// <item> /// <description>The example of defining nested features . /// <code> /// Feature binaries = new Feature("My Product Binaries"); /// Feature docs = new Feature("My Product Documentation"); /// Feature docViewers = new Feature("Documentation viewers"); /// docs.Children.Add(docViewers); /// ... /// </code> /// </description> /// </item> /// /// <item> /// <description>The example of defining "Complete" <see cref="Feature"/> implicitly. /// Note <see cref="File"/> constructor does not use <see cref="Feature"/> argument. /// <code> /// var project = /// new Project("My Product", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// new File(@"AppFiles\MyApp.exe", /// ... /// </code> /// </description> /// </item> /// </list> /// </example> public partial class Feature : WixEntity { /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class. /// </summary> public Feature() { } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> public Feature(string name) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> public Feature(string name, string description) : this(name) { Description = description; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> public Feature(string name, bool isEnabled) : this(name) { IsEnabled = isEnabled; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> public Feature(string name, string description, bool isEnabled) : this(name) { Description = description; IsEnabled = isEnabled; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> public Feature(string name, string description, bool isEnabled, bool allowChange) : this(name, description, isEnabled) { AllowChange = allowChange; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> public Feature(string name, bool isEnabled, bool allowChange) : this(name, isEnabled) { AllowChange = allowChange; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="configurableDir">The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog.</param> public Feature(string name, string description, string configurableDir) : this(name, description) { ConfigurableDir = configurableDir; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> /// <param name="configurableDir">The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog.</param> public Feature(string name, string description, bool isEnabled, bool allowChange, string configurableDir) : this(name, description, isEnabled) { AllowChange = allowChange; ConfigurableDir = configurableDir; } /// <summary> /// <para> /// Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input. /// </para> /// The default value is <c>true</c>. /// </summary> public bool IsEnabled = true; /// <summary> /// <para> /// Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent. /// </para> /// <para>This property is translated into WiX Feature.Absent attribute.</para> /// The default value is <c>true</c>. /// </summary> public bool AllowChange = true; /// <summary> /// The feature description. /// </summary> public string Description = ""; /// <summary> /// The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog. /// </summary> public string ConfigurableDir = ""; internal Feature Parent; /// <summary> /// Child <see cref="Feature"/>. To be added in the nested Features scenarios. /// </summary> public List<Feature> Children = new List<Feature>(); /// <summary> /// Adds the specified nested features. /// </summary> /// <param name="features">The features.</param> /// <returns></returns> public Feature Add(params Feature[] features) { Children.AddRange(features); return this; } /// <summary> /// Defines the installation <see cref="Condition"/>, which is to be checked during the installation to /// determine if the feature should be installed on the target system. /// </summary> public FeatureCondition Condition = null; /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return Name; } internal XElement ToXml() { var element = new XElement("Feature"); element.SetAttribute("Id", Id) .SetAttribute("Title", Name) .SetAttribute("Absent", AllowChange ? "allow" : "disallow") .SetAttribute("Level", IsEnabled ? "1" : "2") .SetAttribute("Description", Description) .SetAttribute("ConfigurableDirectory", ConfigurableDir) .AddAttributes(Attributes); if (Condition != null) element.Add( //intentionally leaving out AddAttributes(...) as Level is the only valid attribute on */Feature/Condition new XElement("Condition", new XAttribute("Level", Condition.Level), new XCData(Condition.ToCData()))); return element; } } }
// 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.IO; using System.Net.Sockets; using System.Threading.Tasks; using Xunit; namespace System.Net.NameResolution.Tests { public class GetHostEntryTest { [Fact] public async Task Dns_GetHostEntryAsync_IPAddress_Ok() { IPAddress localIPAddress = await TestSettings.GetLocalIPAddress(); await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(localIPAddress)); } [ActiveIssue(37362, TestPlatforms.OSX)] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(32797)] [InlineData("")] [InlineData(TestSettings.LocalHost)] public async Task Dns_GetHostEntry_HostString_Ok(string hostName) { try { await TestGetHostEntryAsync(() => Task.FromResult(Dns.GetHostEntry(hostName))); } catch (Exception ex) when (hostName == "") { // Additional data for debugging sporadic CI failures #24355 string actualHostName = Dns.GetHostName(); string etcHosts = ""; Exception getHostEntryException = null; Exception etcHostsException = null; try { Dns.GetHostEntry(actualHostName); } catch (Exception e2) { getHostEntryException = e2; } try { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { etcHosts = File.ReadAllText("/etc/hosts"); } } catch (Exception e2) { etcHostsException = e2; } throw new Exception( $"Failed for empty hostname.{Environment.NewLine}" + $"Dns.GetHostName() == {actualHostName}{Environment.NewLine}" + $"{nameof(getHostEntryException)}=={getHostEntryException}{Environment.NewLine}" + $"{nameof(etcHostsException)}=={etcHostsException}{Environment.NewLine}" + $"/etc/host =={Environment.NewLine}{etcHosts}", ex); } } [ActiveIssue(37362, TestPlatforms.OSX)] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(32797)] [InlineData("")] [InlineData(TestSettings.LocalHost)] public async Task Dns_GetHostEntryAsync_HostString_Ok(string hostName) => await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(hostName)); [Fact] public async Task Dns_GetHostEntryAsync_IPString_Ok() => await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalIPString)); private static async Task TestGetHostEntryAsync(Func<Task<IPHostEntry>> getHostEntryFunc) { Task<IPHostEntry> hostEntryTask1 = getHostEntryFunc(); Task<IPHostEntry> hostEntryTask2 = getHostEntryFunc(); await TestSettings.WhenAllOrAnyFailedWithTimeout(hostEntryTask1, hostEntryTask2); IPAddress[] list1 = hostEntryTask1.Result.AddressList; IPAddress[] list2 = hostEntryTask2.Result.AddressList; Assert.NotNull(list1); Assert.NotNull(list2); Assert.Equal<IPAddress>(list1, list2); } [Fact] public async Task Dns_GetHostEntry_NullStringHost_Fail() { Assert.Throws<ArgumentNullException>(() => Dns.GetHostEntry((string)null)); await Assert.ThrowsAsync<ArgumentNullException>(() => Dns.GetHostEntryAsync((string)null)); await Assert.ThrowsAsync<ArgumentNullException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, (string)null, null)); } [Fact] public async Task Dns_GetHostEntryAsync_NullIPAddressHost_Fail() { Assert.Throws<ArgumentNullException>(() => Dns.GetHostEntry((IPAddress)null)); await Assert.ThrowsAsync<ArgumentNullException>(() => Dns.GetHostEntryAsync((IPAddress)null)); await Assert.ThrowsAsync<ArgumentNullException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, (IPAddress)null, null)); } public static IEnumerable<object[]> GetInvalidAddresses() { yield return new object[] { IPAddress.Any }; yield return new object[] { IPAddress.IPv6Any }; yield return new object[] { IPAddress.IPv6None }; } [Theory] [MemberData(nameof(GetInvalidAddresses))] public async Task Dns_GetHostEntry_AnyIPAddress_Fail(IPAddress address) { Assert.Throws<ArgumentException>(() => Dns.GetHostEntry(address)); Assert.Throws<ArgumentException>(() => Dns.GetHostEntry(address.ToString())); await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(address)); await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(address.ToString())); await Assert.ThrowsAsync<ArgumentException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address, null)); await Assert.ThrowsAsync<ArgumentException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address.ToString(), null)); } [Fact] public async Task DnsGetHostEntry_MachineName_AllVariationsMatch() { IPHostEntry syncResult = Dns.GetHostEntry(TestSettings.LocalHost); IPHostEntry apmResult = Dns.EndGetHostEntry(Dns.BeginGetHostEntry(TestSettings.LocalHost, null, null)); IPHostEntry asyncResult = await Dns.GetHostEntryAsync(TestSettings.LocalHost); Assert.Equal(syncResult.HostName, apmResult.HostName); Assert.Equal(syncResult.HostName, asyncResult.HostName); Assert.Equal(syncResult.AddressList, apmResult.AddressList); Assert.Equal(syncResult.AddressList, asyncResult.AddressList); } [Fact] public async Task DnsGetHostEntry_Loopback_AllVariationsMatch() { IPHostEntry syncResult = Dns.GetHostEntry(IPAddress.Loopback); IPHostEntry apmResult = Dns.EndGetHostEntry(Dns.BeginGetHostEntry(IPAddress.Loopback, null, null)); IPHostEntry asyncResult = await Dns.GetHostEntryAsync(IPAddress.Loopback); Assert.Equal(syncResult.HostName, apmResult.HostName); Assert.Equal(syncResult.HostName, asyncResult.HostName); Assert.Equal(syncResult.AddressList, apmResult.AddressList); Assert.Equal(syncResult.AddressList, asyncResult.AddressList); } [Theory] [InlineData("BadName")] // unknown name [InlineData("0.0.1.1")] // unknown address [InlineData("Test-\u65B0-Unicode")] // unknown unicode name [InlineData("xn--test--unicode-0b01a")] // unknown punicode name [InlineData("Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualllllllly.I.Will.Get.To.The.Eeeee" + "eeeeend.Almost.There.Are.We.Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualll" + "llllly.I.Will.Get.To.The.Eeeeeeeeeend.Almost.There.Are")] // very long name but not too long public async Task DnsGetHostEntry_BadName_ThrowsSocketException(string hostNameOrAddress) { Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(hostNameOrAddress)); await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(hostNameOrAddress)); await Assert.ThrowsAnyAsync<SocketException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, hostNameOrAddress, null)); } [Theory] [InlineData("Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualllllllly.I.Will.Get.To.The.Eeeee" + "eeeeend.Almost.There.Are.We.Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualll" + "llllly.I.Will.Get.To.The.Eeeeeeeeeend.Almost.There.Aret")] public async Task DnsGetHostEntry_BadName_ThrowsArgumentOutOfRangeException(string hostNameOrAddress) { Assert.ThrowsAny<ArgumentOutOfRangeException>(() => Dns.GetHostEntry(hostNameOrAddress)); await Assert.ThrowsAnyAsync<ArgumentOutOfRangeException>(() => Dns.GetHostEntryAsync(hostNameOrAddress)); await Assert.ThrowsAnyAsync<ArgumentOutOfRangeException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, hostNameOrAddress, null)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public async Task DnsGetHostEntry_LocalHost_ReturnsFqdnAndLoopbackIPs(int mode) { IPHostEntry entry = mode switch { 0 => Dns.GetHostEntry("localhost"), 1 => await Dns.GetHostEntryAsync("localhost"), _ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, "localhost", null) }; Assert.NotNull(entry.HostName); Assert.True(entry.HostName.Length > 0, "Empty host name"); Assert.True(entry.AddressList.Length >= 1, "No local IPs"); Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), "Not a loopback address: " + addr)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public async Task DnsGetHostEntry_LoopbackIP_MatchesGetHostEntryLoopbackString(int mode) { IPAddress address = IPAddress.Loopback; IPHostEntry ipEntry = mode switch { 0 => Dns.GetHostEntry(address), 1 => await Dns.GetHostEntryAsync(address), _ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address, null) }; IPHostEntry stringEntry = mode switch { 0 => Dns.GetHostEntry(address.ToString()), 1 => await Dns.GetHostEntryAsync(address.ToString()), _ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address.ToString(), null) }; Assert.Equal(ipEntry.HostName, stringEntry.HostName); Assert.Equal(ipEntry.AddressList, stringEntry.AddressList); } } }
#region License // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Data; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; namespace FluentMigrator.Builders.Create.Table { public class CreateTableExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateTableExpression, ICreateTableColumnOptionOrWithColumnSyntax>, ICreateTableWithColumnOrSchemaOrDescriptionSyntax, ICreateTableColumnAsTypeSyntax, ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax, IColumnExpressionBuilder { private readonly IMigrationContext _context; public CreateTableExpressionBuilder(CreateTableExpression expression, IMigrationContext context) : base(expression) { _context = context; ColumnHelper = new ColumnExpressionBuilderHelper(this, context); } public ColumnDefinition CurrentColumn { get; set; } public ForeignKeyDefinition CurrentForeignKey { get; set; } public ColumnExpressionBuilderHelper ColumnHelper { get; set; } public ICreateTableWithColumnSyntax InSchema(string schemaName) { Expression.SchemaName = schemaName; return this; } public ICreateTableColumnAsTypeSyntax WithColumn(string name) { var column = new ColumnDefinition { Name = name, TableName = Expression.TableName, ModificationType = ColumnModificationType.Create }; Expression.Columns.Add(column); CurrentColumn = column; return this; } public ICreateTableWithColumnOrSchemaSyntax WithDescription(string description) { Expression.TableDescription = description; return this; } public ICreateTableColumnOptionOrWithColumnSyntax WithDefault(SystemMethods method) { CurrentColumn.DefaultValue = method; return this; } public ICreateTableColumnOptionOrWithColumnSyntax WithDefaultValue(object value) { CurrentColumn.DefaultValue = value; return this; } public ICreateTableColumnOptionOrWithColumnSyntax WithColumnDescription(string description) { CurrentColumn.ColumnDescription = description; return this; } public ICreateTableColumnOptionOrWithColumnSyntax Identity() { CurrentColumn.IsIdentity = true; return this; } public ICreateTableColumnOptionOrWithColumnSyntax Indexed() { return Indexed(null); } public ICreateTableColumnOptionOrWithColumnSyntax Indexed(string indexName) { ColumnHelper.Indexed(indexName); return this; } public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey() { CurrentColumn.IsPrimaryKey = true; return this; } public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey(string primaryKeyName) { CurrentColumn.IsPrimaryKey = true; CurrentColumn.PrimaryKeyName = primaryKeyName; return this; } public ICreateTableColumnOptionOrWithColumnSyntax Nullable() { ColumnHelper.SetNullable(true); return this; } public ICreateTableColumnOptionOrWithColumnSyntax NotNullable() { ColumnHelper.SetNullable(false); return this; } public ICreateTableColumnOptionOrWithColumnSyntax Unique() { ColumnHelper.Unique(null); return this; } public ICreateTableColumnOptionOrWithColumnSyntax Unique(string indexName) { ColumnHelper.Unique(indexName); return this; } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string primaryTableName, string primaryColumnName) { return ForeignKey(null, null, primaryTableName, primaryColumnName); } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName) { return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName); } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableSchema, string primaryTableName, string primaryColumnName) { CurrentColumn.IsForeignKey = true; var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = primaryTableName, PrimaryTableSchema = primaryTableSchema, ForeignTable = Expression.TableName, ForeignTableSchema = Expression.SchemaName } }; fk.ForeignKey.PrimaryColumns.Add(primaryColumnName); fk.ForeignKey.ForeignColumns.Add(CurrentColumn.Name); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; return this; } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignTableName, string foreignColumnName) { return ReferencedBy(null, null, foreignTableName, foreignColumnName); } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName) { return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName); } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema, string foreignTableName, string foreignColumnName) { var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = Expression.TableName, PrimaryTableSchema = Expression.SchemaName, ForeignTable = foreignTableName, ForeignTableSchema = foreignTableSchema } }; fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name); fk.ForeignKey.ForeignColumns.Add(foreignColumnName); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; return this; } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey() { CurrentColumn.IsForeignKey = true; return this; } [Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")] public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames) { return References(foreignKeyName, null, foreignTableName, foreignColumnNames); } [Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")] public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName, IEnumerable<string> foreignColumnNames) { var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = Expression.TableName, PrimaryTableSchema = Expression.SchemaName, ForeignTable = foreignTableName, ForeignTableSchema = foreignTableSchema } }; fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name); foreach (var foreignColumnName in foreignColumnNames) fk.ForeignKey.ForeignColumns.Add(foreignColumnName); _context.Expressions.Add(fk); return this; } public override ColumnDefinition GetColumnForType() { return CurrentColumn; } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnDelete(Rule rule) { CurrentForeignKey.OnDelete = rule; return this; } public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnUpdate(Rule rule) { CurrentForeignKey.OnUpdate = rule; return this; } public ICreateTableColumnOptionOrWithColumnSyntax OnDeleteOrUpdate(Rule rule) { OnDelete(rule); OnUpdate(rule); return this; } string IColumnExpressionBuilder.SchemaName { get { return Expression.SchemaName; } } string IColumnExpressionBuilder.TableName { get { return Expression.TableName; } } ColumnDefinition IColumnExpressionBuilder.Column { get { return CurrentColumn; } } } }
using System; using System.Collections.Generic; using ExitGames.Client.Photon; using Mod; using Photon.Enums; using UnityEngine; // PUN Version: 1.28 namespace Photon { public static class PhotonNetwork { public const bool InstantiateInRoomOnly = true; public static readonly PhotonLogLevel LogLevel = PhotonLogLevel.ErrorsOnly; public const int MaxViewIds = 1000; public static readonly ServerSettings PhotonServerSettings = (ServerSettings) Resources.Load("PhotonServerSettings", typeof(ServerSettings)); private static readonly Dictionary<string, GameObject> PrefabCache = new Dictionary<string, GameObject>(); public static HashSet<GameObject> SendMonoMessageTargets; private static bool _mAutomaticallySyncScene = false; private static bool autoJoinLobbyField = true; private static bool isOfflineMode = false; internal static int lastUsedViewSubId = 0; internal static int lastUsedViewSubIdStatic = 0; private static bool _cleanupPlayerObjects = true; private static bool m_isMessageQueueRunning = true; internal static List<int> manuallyAllocatedViewIds = new List<int>(); internal static NetworkingPeer networkingPeer; private static Room offlineModeRoom = null; public static readonly PhotonHandler photonMono; public static float precisionForFloatSynchronization = 0.01f; public static float precisionForQuaternionSynchronization = 1f; public static float precisionForVectorSynchronization = 9.9E-05f; private static int sendInterval = 50; private static int sendIntervalOnSerialize = 100; public const string serverSettingsAssetFile = "PhotonServerSettings"; public const string serverSettingsAssetPath = "Assets/Photon Unity Networking/Resources/PhotonServerSettings.asset"; public static bool UseNameServer = true; public static bool UsePrefabCache = true; public const string versionPUN = "1.28"; static PhotonNetwork() { Application.runInBackground = true; GameObject obj2 = new GameObject(); photonMono = obj2.AddComponent<PhotonHandler>(); obj2.name = "PhotonMono"; obj2.hideFlags = HideFlags.HideInHierarchy; networkingPeer = new NetworkingPeer(photonMono, string.Empty, ConnectionProtocol.Udp); CustomTypes.Register(); } private static int[] AllocateSceneViewIDs(int countOfNewViews) { int[] numArray = new int[countOfNewViews]; for (int i = 0; i < countOfNewViews; i++) { numArray[i] = AllocateViewID(0); } return numArray; } public static int AllocateViewID() { int item = AllocateViewID(Player.Self.ID); manuallyAllocatedViewIds.Add(item); return item; } private static int AllocateViewID(int ownerId) { if (ownerId != 0) { int lastUsedViewSubId = PhotonNetwork.lastUsedViewSubId; int num6 = ownerId * MaxViewIds; for (int j = 1; j < MaxViewIds; j++) { lastUsedViewSubId = (lastUsedViewSubId + 1) % MaxViewIds; if (lastUsedViewSubId != 0) { int key = lastUsedViewSubId + num6; if (!networkingPeer.photonViewList.ContainsKey(key) && !manuallyAllocatedViewIds.Contains(key)) { PhotonNetwork.lastUsedViewSubId = lastUsedViewSubId; return key; } } } throw new Exception(string.Format("AllocateViewID() failed. User {0} is out of subIds, as all viewIDs are used.", ownerId)); } int lastUsedViewSubIdStatic = PhotonNetwork.lastUsedViewSubIdStatic; int num2 = ownerId * MaxViewIds; for (int i = 1; i < MaxViewIds; i++) { lastUsedViewSubIdStatic = (lastUsedViewSubIdStatic + 1) % MaxViewIds; if (lastUsedViewSubIdStatic != 0) { int num4 = lastUsedViewSubIdStatic + num2; if (!networkingPeer.photonViewList.ContainsKey(num4)) { PhotonNetwork.lastUsedViewSubIdStatic = lastUsedViewSubIdStatic; return num4; } } } throw new Exception(string.Format("AllocateViewID() failed. Room (user {0}) is out of subIds, as all room viewIDs are used.", ownerId)); } public static bool CloseConnection(Player kickPlayer) { if (!VerifyCanUseNetwork()) { return false; } if (!Player.Self.IsMasterClient) { Debug.LogError("CloseConnection: Only the masterclient can kick another player."); return false; } if (kickPlayer == null) { Debug.LogError("CloseConnection: No such player connected!"); return false; } RaiseEventOptions options = new RaiseEventOptions(); options.TargetActors = new int[] { kickPlayer.ID }; RaiseEventOptions raiseEventOptions = options; return networkingPeer.OpRaiseEvent(203, null, true, raiseEventOptions); } public static bool ConnectToBestCloudServer(string gameVersion) { if (PhotonServerSettings == null) { Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: PhotonServerSettings"); return false; } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode) { return ConnectUsingSettings(gameVersion); } networkingPeer.IsInitialConnect = true; networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion); CloudRegionCode bestRegionCodeInPreferences = PhotonHandler.BestRegionCodeInPreferences; if (bestRegionCodeInPreferences != CloudRegionCode.None) { Debug.Log("Best region found in PlayerPrefs. Connecting to: " + bestRegionCodeInPreferences); return networkingPeer.ConnectToRegionMaster(bestRegionCodeInPreferences); } return networkingPeer.ConnectToNameServer(); } public static bool ConnectToMaster(string masterServerAddress, int port, string appID, string gameVersion) { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ConnectToMaster() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (offlineMode) { offlineMode = false; Debug.LogWarning("ConnectToMaster() disabled the offline mode. No longer offline."); } if (!isMessageQueueRunning) { isMessageQueueRunning = true; Debug.LogWarning("ConnectToMaster() enabled isMessageQueueRunning. Needs to be able to dispatch incoming messages."); } networkingPeer.SetApp(appID, gameVersion); networkingPeer.IsUsingNameServer = false; networkingPeer.IsInitialConnect = true; networkingPeer.MasterServerAddress = masterServerAddress + ":" + port; return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer); } public static bool ConnectUsingSettings(string gameVersion) { if (PhotonServerSettings == null) { Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: PhotonServerSettings"); return false; } SwitchToProtocol(PhotonServerSettings.Protocol); networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion); if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode) { offlineMode = true; return true; } if (offlineMode) { Debug.LogWarning("ConnectUsingSettings() disabled the offline mode. No longer offline."); } offlineMode = false; isMessageQueueRunning = true; networkingPeer.IsInitialConnect = true; if (PhotonServerSettings.HostType == ServerSettings.HostingOption.SelfHosted) { networkingPeer.IsUsingNameServer = false; networkingPeer.MasterServerAddress = PhotonServerSettings.ServerAddress + ":" + PhotonServerSettings.ServerPort; return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer); } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion) { return ConnectToBestCloudServer(gameVersion); } return networkingPeer.ConnectToRegionMaster(PhotonServerSettings.PreferredRegion); } public static bool CreateRoom(string roomName) { return CreateRoom(roomName, null, null); } public static bool CreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("CreateRoom failed. In offline mode you still have to leave a room to enter another."); return false; } offlineModeRoom = new Room(roomName, roomOptions); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); return true; } if (networkingPeer.server == ServerConnection.MasterServer && connectedAndReady) { return networkingPeer.OpCreateGame(roomName, roomOptions, typedLobby); } Debug.LogError("CreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } public static bool CreateRoom(string roomName, bool isVisible, bool isOpen, int maxPlayers) { RoomOptions roomOptions = new RoomOptions { IsVisible = isVisible, IsOpen = isOpen, MaxPlayers = maxPlayers }; return CreateRoom(roomName, roomOptions, null); } public static void Destroy(PhotonView targetView) { if (targetView != null) { networkingPeer.RemoveInstantiatedGO(targetView.gameObject, !inRoom); } else { Debug.LogError("Destroy(targetPhotonView) failed, cause targetPhotonView is null."); } } public static void Destroy(GameObject targetGo) { networkingPeer.RemoveInstantiatedGO(targetGo, !inRoom); } public static void DestroyAll() { if (isMasterClient) { networkingPeer.DestroyAll(false); } else { Debug.LogError("Couldn't call DestroyAll() as only the master client is allowed to call this."); } } public static void DestroyPlayerObjects(Player targetPlayer) { if (Player.Self == null) { Debug.LogError("DestroyPlayerObjects() failed, cause parameter 'targetPlayer' was null."); } DestroyPlayerObjects(targetPlayer.ID); } private static void DestroyPlayerObjects(int targetPlayerId) { if (VerifyCanUseNetwork()) { if (!Player.Self.IsMasterClient && targetPlayerId != Player.Self.ID) { Debug.LogError("DestroyPlayerObjects() failed, cause players can only destroy their own GameObjects. A Master Client can destroy anyone's. This is master: " + isMasterClient); } else { networkingPeer.DestroyPlayerObjects(targetPlayerId, false); } } } public static void Disconnect() { if (!connected) return; if (offlineMode) { offlineMode = false; offlineModeRoom = null; networkingPeer.states = ClientState.Disconnecting; networkingPeer.OnStatusChanged(StatusCode.Disconnect); } else { networkingPeer?.Disconnect(); } } public static void FetchServerTimestamp() { networkingPeer?.FetchServerTimestamp(); } public static bool FindFriends(string[] friendsToFind) { return networkingPeer != null && !isOfflineMode && networkingPeer.OpFindFriends(friendsToFind); } public static int GetPing() { return networkingPeer.RoundTripTime; } [Obsolete("Used for compatibility with Unity networking only. Encryption is automatically initialized while connecting.")] public static void InitializeSecurity() { } public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group) { return Instantiate(prefabName, position, rotation, group, null); } private static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (connected && (!InstantiateInRoomOnly || inRoom)) { if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out var obj2)) { if (prefabName.StartsWith("RCAsset/")) { obj2 = GameManager.InstantiateCustomAsset(prefabName); } else { obj2 = (GameObject) Resources.Load(prefabName, typeof(GameObject)); } if (UsePrefabCache) { PrefabCache.Add(prefabName, obj2); } } if (obj2 == null) { Debug.LogError("Failed to Instantiate prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return null; } if (obj2.GetComponent<PhotonView>() == null) { Debug.LogError("Failed to Instantiate prefab:" + prefabName + ". Prefab must have a PhotonView component."); return null; } int[] viewIDs = new int[obj2.GetPhotonViewsInChildren().Length]; for (int i = 0; i < viewIDs.Length; i++) { viewIDs[i] = AllocateViewID(Player.Self.ID); } Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, viewIDs, data, false); return networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, obj2); } Debug.LogError(string.Concat("Failed to Instantiate prefab: ", prefabName, ". Client should be in a room. Current connectionStateDetailed: ", connectionStatesDetailed)); return null; } public static GameObject InstantiateSceneObject(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (connected && (!InstantiateInRoomOnly || inRoom)) { GameObject obj2; if (!isMasterClient) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Client is not the MasterClient in this room."); return null; } if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out obj2)) { obj2 = (GameObject) Resources.Load(prefabName, typeof(GameObject)); if (UsePrefabCache) { PrefabCache.Add(prefabName, obj2); } } if (obj2 == null) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return null; } if (obj2.GetComponent<PhotonView>() == null) { Debug.LogError("Failed to InstantiateSceneObject prefab:" + prefabName + ". Prefab must have a PhotonView component."); return null; } int[] viewIDs = AllocateSceneViewIDs(obj2.GetPhotonViewsInChildren().Length); if (viewIDs == null) { Debug.LogError(string.Concat("Failed to InstantiateSceneObject prefab: ", prefabName, ". No ViewIDs are free to use. Max is: ", MaxViewIds)); return null; } Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, viewIDs, data, true); return networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, obj2); } Debug.LogError(string.Concat("Failed to InstantiateSceneObject prefab: ", prefabName, ". Client should be in a room. Current connectionStateDetailed: ", connectionStatesDetailed)); return null; } public static void InternalCleanPhotonMonoFromSceneIfStuck() { if (UnityEngine.Object.FindObjectsOfType(typeof(PhotonHandler)) is PhotonHandler[] handlerArray && handlerArray.Length > 0) { Debug.Log("Cleaning up hidden PhotonHandler instances in scene. Please save it. This is not an issue."); foreach (PhotonHandler handler in handlerArray) { handler.gameObject.hideFlags = HideFlags.None; if (handler.gameObject != null && handler.gameObject.name == "PhotonMono") { UnityEngine.Object.DestroyImmediate(handler.gameObject); } UnityEngine.Object.DestroyImmediate(handler); } } } public static bool JoinLobby(TypedLobby typedLobby = null) { bool flag; if (!connected || Server != ServerConnection.MasterServer) { return false; } if (typedLobby == null) { typedLobby = TypedLobby.Default; } if (flag = networkingPeer.OpJoinLobby(typedLobby)) { networkingPeer.lobby = typedLobby; } return flag; } public static bool JoinOrCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinOrCreateRoom failed. In offline mode you still have to leave a room to enter another."); return false; } offlineModeRoom = new Room(roomName, roomOptions); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); return true; } if (networkingPeer.server == ServerConnection.MasterServer && connectedAndReady) { if (string.IsNullOrEmpty(roomName)) { Debug.LogError("JoinOrCreateRoom failed. A roomname is required. If you don't know one, how will you join?"); return false; } return networkingPeer.OpJoinRoom(roomName, roomOptions, typedLobby, true); } Debug.LogError("JoinOrCreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } public static bool JoinRandomRoom(Hashtable expectedCustomRoomProperties = null, byte expectedMaxPlayers = 0, MatchmakingMode matchingType = MatchmakingMode.FillRoom, TypedLobby typedLobby = null, string sqlLobbyFilter = null) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinRandomRoom failed. In offline mode you still have to leave a room to enter another."); return false; } offlineModeRoom = new Room("offline room", (Hashtable)null); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); return true; } if (networkingPeer.server == ServerConnection.MasterServer && connectedAndReady) { Hashtable target = new Hashtable(); target.MergeStringKeys(expectedCustomRoomProperties); if (expectedMaxPlayers > 0) { target[(byte) 255] = expectedMaxPlayers; } return networkingPeer.OpJoinRandomRoom(target, 0, null, matchingType, typedLobby, sqlLobbyFilter); } Debug.LogError("JoinRandomRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } public static bool JoinRoom(string roomName) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinRoom failed. In offline mode you still have to leave a room to enter another."); return false; } offlineModeRoom = new Room(roomName, (Hashtable)null); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); return true; } if (networkingPeer.server == ServerConnection.MasterServer && connectedAndReady) { if (string.IsNullOrEmpty(roomName)) { Debug.LogError("JoinRoom failed. A roomname is required. If you don't know one, how will you join?"); return false; } return networkingPeer.OpJoinRoom(roomName, null, null, false); } Debug.LogError("JoinRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } [Obsolete("Use overload with roomOptions and TypedLobby parameter.")] public static bool JoinRoom(string roomName, bool createIfNotExists) { if (connectionStatesDetailed != ClientState.Joining && connectionStatesDetailed != ClientState.Joined && connectionStatesDetailed != ClientState.ConnectedToGameserver) { if (Room == null) { if (roomName != string.Empty) { if (offlineMode) { offlineModeRoom = new Room(roomName, (Hashtable)null); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); return true; } return networkingPeer.OpJoinRoom(roomName, null, null, createIfNotExists); } Debug.LogError("JoinRoom aborted: You must specifiy a room name!"); } else { Debug.LogError("JoinRoom aborted: You are already in a room!"); } } else { Debug.LogError("JoinRoom aborted: You can only join a room while not currently connected/connecting to a room."); } return false; } public static bool LeaveLobby() { return connected && Server == ServerConnection.MasterServer && networkingPeer.OpLeaveLobby(); } public static bool LeaveRoom() { if (offlineMode) { offlineModeRoom = null; NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnLeftRoom); return true; } if (Room == null) { Debug.LogWarning("PhotonNetwork.room is null. You don't have to call LeaveRoom() when you're not in one. State: " + connectionStatesDetailed); } return networkingPeer.OpLeave(); } public static void LoadLevel(int levelNumber) { networkingPeer.SetLevelInPropsIfSynced(levelNumber); isMessageQueueRunning = false; networkingPeer.loadingLevelAndPausedNetwork = true; Application.LoadLevel(levelNumber); } public static void LoadLevel(string levelName) { networkingPeer.SetLevelInPropsIfSynced(levelName); isMessageQueueRunning = false; networkingPeer.loadingLevelAndPausedNetwork = true; Application.LoadLevel(levelName); } public static void NetworkStatisticsReset() { networkingPeer.TrafficStatsReset(); } public static string NetworkStatisticsToString() { if (networkingPeer != null && !offlineMode) { return networkingPeer.VitalStatsToString(false); } return "Offline or in OfflineMode. No VitalStats available."; } public static void OverrideBestCloudServer(CloudRegionCode region) { PhotonHandler.BestRegionCodeInPreferences = region; } public static bool RaiseEvent(byte eventCode, object eventContent, bool sendReliable, RaiseEventOptions options) { if (inRoom && eventCode < 255) { return networkingPeer.OpRaiseEvent(eventCode, eventContent, sendReliable, options); } Debug.LogWarning("RaiseEvent() failed. Your event is not being sent! Check if your are in a Room and the eventCode must be less than 200 (0..199)."); return false; } public static void RefreshCloudServerRating() { throw new NotImplementedException("not available at the moment"); } public static void RemoveRPCs(Player targetPlayer) { if (VerifyCanUseNetwork()) { if (!targetPlayer.IsLocal && !isMasterClient) { Debug.LogError("Error; Only the MasterClient can call RemoveRPCs for other players."); } else { networkingPeer.OpCleanRpcBuffer(targetPlayer.ID); } } } public static void RemoveRPCs(PhotonView targetPhotonView) { if (VerifyCanUseNetwork()) { networkingPeer.CleanRpcBufferIfMine(targetPhotonView); } } public static void RemoveRPCsInGroup(int targetGroup) { if (VerifyCanUseNetwork()) { networkingPeer.RemoveRPCsInGroup(targetGroup); } } internal static void RPC(PhotonView view, string methodName, Player targetPlayer, params object[] parameters) { if (VerifyCanUseNetwork()) { if (Room == null) { Debug.LogWarning("Cannot send RPCs in Lobby, only processed locally"); } else { if (Player.Self == null) { Debug.LogError("Error; Sending RPC to player null! Aborted \"" + methodName + "\""); } if (networkingPeer != null) { networkingPeer.RPC(view, methodName, targetPlayer, parameters); } else { Debug.LogWarning("Could not execute RPC " + methodName + ". Possible scene loading in progress?"); } } } } internal static void RPC(PhotonView view, string methodName, PhotonTargets target, params object[] parameters) { if (VerifyCanUseNetwork()) { if (Room == null) { Debug.LogWarning("Cannot send RPCs in Lobby! RPC dropped."); } else if (networkingPeer != null) { networkingPeer.RPC(view, methodName, target, parameters); } else { Debug.LogWarning("Could not execute RPC " + methodName + ". Possible scene loading in progress?"); } } } public static void SendOutgoingCommands() { if (VerifyCanUseNetwork()) { while (networkingPeer.SendOutgoingCommands()) { } } } public static void SetLevelPrefix(short prefix) { if (VerifyCanUseNetwork()) { networkingPeer.SetLevelPrefix(prefix); } } public static bool SetMasterClient(Player masterClientPlayer) { return networkingPeer.SetMasterClient(masterClientPlayer.ID, true); } public static void SetReceivingEnabled(int group, bool enabled) { if (VerifyCanUseNetwork()) { networkingPeer.SetReceivingEnabled(group, enabled); } } public static void SetReceivingEnabled(int[] enableGroups, int[] disableGroups) { if (VerifyCanUseNetwork()) { networkingPeer.SetReceivingEnabled(enableGroups, disableGroups); } } public static void SetSendingEnabled(int group, bool enabled) { if (VerifyCanUseNetwork()) { networkingPeer.SetSendingEnabled(group, enabled); } } public static void SetSendingEnabled(int[] enableGroups, int[] disableGroups) { if (VerifyCanUseNetwork()) { networkingPeer.SetSendingEnabled(enableGroups, disableGroups); } } public static void SwitchToProtocol(ConnectionProtocol cp) { if (networkingPeer.UsedProtocol != cp) { try { networkingPeer.Disconnect(); networkingPeer.StopThread(); } catch { // ignored } networkingPeer = new NetworkingPeer(photonMono, string.Empty, cp); Debug.Log("Protocol switched to: " + cp); } } public static void UnAllocateViewID(int viewID) { manuallyAllocatedViewIds.Remove(viewID); if (networkingPeer.photonViewList.ContainsKey(viewID)) { Debug.LogWarning(string.Format("Unallocated manually used viewID: {0} but found it used still in a PhotonView: {1}", viewID, networkingPeer.photonViewList[viewID])); } } private static bool VerifyCanUseNetwork() { if (connected) { return true; } Debug.LogError("Cannot send messages when not connected. Either connect to Photon OR use offline mode!"); return false; } public static bool WebRpc(string name, object parameters) { return networkingPeer.WebRpc(name, parameters); } public static AuthenticationValues AuthValues { get => networkingPeer?.CustomAuthenticationValues; set { if (networkingPeer != null) { networkingPeer.CustomAuthenticationValues = value; } } } public static bool CleanupPlayerObjects { get => _cleanupPlayerObjects; set { if (Room != null) { Debug.LogError("Setting autoCleanUpPlayerObjects while in a room is not supported."); } else { _cleanupPlayerObjects = value; } } } public static bool autoJoinLobby { get => autoJoinLobbyField; set => autoJoinLobbyField = value; } public static bool automaticallySyncScene { get => _mAutomaticallySyncScene; set { _mAutomaticallySyncScene = value; if (_mAutomaticallySyncScene && Room != null) { networkingPeer.LoadLevelIfSynced(); } } } public static bool connected { get { if (offlineMode) { return true; } if (networkingPeer == null) { return false; } return !networkingPeer.IsInitialConnect && networkingPeer.states != ClientState.PeerCreated && networkingPeer.states != ClientState.Disconnected && networkingPeer.states != ClientState.Disconnecting && networkingPeer.states != ClientState.ConnectingToNameServer; } } public static bool connectedAndReady { get { if (!connected) { return false; } if (!offlineMode) { switch (connectionStatesDetailed) { case ClientState.ConnectingToGameserver: case ClientState.Joining: case ClientState.Leaving: case ClientState.ConnectingToMasterserver: case ClientState.Disconnecting: case ClientState.Disconnected: case ClientState.ConnectingToNameServer: case ClientState.Authenticating: case ClientState.PeerCreated: return false; } } return true; } } public static bool connecting => networkingPeer.IsInitialConnect && !offlineMode; public static ConnectionState connectionState { get { if (offlineMode) { return ConnectionState.Connected; } if (networkingPeer == null) { return ConnectionState.Disconnected; } PeerStateValue peerState = networkingPeer.PeerState; switch (peerState) { case PeerStateValue.Disconnected: return ConnectionState.Disconnected; case PeerStateValue.Connecting: return ConnectionState.Connecting; case PeerStateValue.Connected: return ConnectionState.Connected; case PeerStateValue.Disconnecting: return ConnectionState.Disconnecting; } if (peerState != PeerStateValue.InitializingApplication) { return ConnectionState.Disconnected; } return ConnectionState.InitializingApplication; } } public static ClientState connectionStatesDetailed { get { if (offlineMode) { return offlineModeRoom == null ? ClientState.ConnectedToMaster : ClientState.Joined; } if (networkingPeer == null) { return ClientState.Disconnected; } return networkingPeer.states; } } public static int countOfPlayers => networkingPeer.mPlayersInRoomsCount + networkingPeer.mPlayersOnMasterCount; public static int countOfPlayersInRooms => networkingPeer.mPlayersInRoomsCount; public static int countOfPlayersOnMaster => networkingPeer.mPlayersOnMasterCount; public static int countOfRooms => networkingPeer.mGameCount; public static bool CrcCheckEnabled { get => networkingPeer.CrcEnabled; set { if (!connected && !connecting) { networkingPeer.CrcEnabled = value; } else { Debug.Log("Can't change CrcCheckEnabled while being connected. CrcCheckEnabled stays " + networkingPeer.CrcEnabled); } } } public static int FriendsListAge => networkingPeer?.FriendsListAge ?? 0; public static string gameVersion { get => networkingPeer.mAppVersion; set => networkingPeer.mAppVersion = value; } public static bool inRoom => connectionStatesDetailed == ClientState.Joined; public static bool insideLobby => networkingPeer.insideLobby; public static bool isMasterClient => offlineMode || networkingPeer.mMasterClient == networkingPeer.mLocalActor; public static bool isMessageQueueRunning { get => m_isMessageQueueRunning; set { if (value) { PhotonHandler.StartFallbackSendAckThread(); } networkingPeer.IsSendingOnlyAcks = !value; m_isMessageQueueRunning = value; } } public static bool isNonMasterClientInRoom => !isMasterClient && Room != null; public static TypedLobby lobby { get => networkingPeer.lobby; set => networkingPeer.lobby = value; } public static Player MasterClient => networkingPeer?.mMasterClient; [Obsolete("Used for compatibility with Unity networking only.")] public static int maxConnections { get { if (Room == null) { return 0; } return Room.MaxPlayers; } set => Room.MaxPlayers = value; } public static int MaxResendsBeforeDisconnect { get => networkingPeer.SentCountAllowance; set { if (value < 3) { value = 3; } if (value > 10) { value = 10; } networkingPeer.SentCountAllowance = value; } } public static bool NetworkStatisticsEnabled { get => networkingPeer.TrafficStatsEnabled; set => networkingPeer.TrafficStatsEnabled = value; } public static bool offlineMode { get => isOfflineMode; set { if (value != isOfflineMode) { if (value && connected) { Debug.LogError("Can't start OFFLINE mode while connected!"); } else { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { networkingPeer.Disconnect(); } isOfflineMode = value; if (isOfflineMode) { NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster); networkingPeer.ChangeLocalID(1); networkingPeer.mMasterClient = Player.Self; } else { offlineModeRoom = null; networkingPeer.ChangeLocalID(-1); networkingPeer.mMasterClient = null; } } } } } public static Player[] otherPlayers { get { if (networkingPeer == null) { return new Player[0]; } return networkingPeer.mOtherPlayerListCopy; } } public static int PacketLossByCrcCheck => networkingPeer.PacketLossByCrc; public static Player[] PlayerList { get { if (networkingPeer == null) { return new Player[0]; } return networkingPeer.mPlayerListCopy; } } public static string playerName { get => networkingPeer.PlayerName; set => networkingPeer.PlayerName = value; } public static int ResentReliableCommands => networkingPeer.ResentReliableCommands; public static Room Room //TODO: Make it into a custom class/struct with all infos { get { if (isOfflineMode) { return offlineModeRoom; } return networkingPeer.mCurrentGame; } } public static int sendRate { get => 1000 / sendInterval; set { sendInterval = 1000 / value; if (photonMono != null) { photonMono.updateInterval = sendInterval; } if (value < sendRateOnSerialize) { sendRateOnSerialize = value; } } } public static int sendRateOnSerialize { get => 1000 / sendIntervalOnSerialize; private set { if (value > sendRate) { Debug.LogError("Error, can not set the OnSerialize SendRate more often then the overall SendRate"); value = sendRate; } sendIntervalOnSerialize = 1000 / value; if (photonMono != null) { photonMono.updateIntervalOnSerialize = sendIntervalOnSerialize; } } } public static ServerConnection Server => networkingPeer.server; public static string ServerAddress => networkingPeer == null ? "<not connected>" : networkingPeer.ServerAddress; public static double time { get { if (offlineMode) { return Time.time; } return networkingPeer.ServerTimeInMilliSeconds / 1000.0; } } public static int unreliableCommandsLimit { get => networkingPeer.LimitOfUnreliableCommands; set => networkingPeer.LimitOfUnreliableCommands = value; } public delegate void EventCallback(byte eventCode, object content, int senderId); public static List<FriendInfo> Friends { get; set; } } }
//---------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Net; using System.ServiceModel.Channels; using System.ServiceModel; using System.Net.Sockets; using System.Collections.ObjectModel; using System.IdentityModel.Selectors; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.Security.Principal; using System.ServiceModel.Security.Tokens; using System.Collections.Generic; using System.Runtime.Serialization; using System.Globalization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.Runtime.Diagnostics; public abstract class IdentityVerifier { protected IdentityVerifier() { // empty } public static IdentityVerifier CreateDefault() { return DefaultIdentityVerifier.Instance; } internal bool CheckAccess(EndpointAddress reference, Message message) { if (reference == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference"); if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); EndpointIdentity identity; if (!this.TryGetIdentity(reference, out identity)) return false; SecurityMessageProperty securityContextProperty = null; if (message.Properties != null) securityContextProperty = message.Properties.Security; if (securityContextProperty == null || securityContextProperty.ServiceSecurityContext == null) return false; return this.CheckAccess(identity, securityContextProperty.ServiceSecurityContext.AuthorizationContext); } public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext); public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity); static void AdjustAddress(ref EndpointAddress reference, Uri via) { // if we don't have an identity and we have differing Uris, we should use the Via if (reference.Identity == null && reference.Uri != via) { reference = new EndpointAddress(via); } } internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity) { AdjustAddress(ref reference, via); return this.TryGetIdentity(reference, out identity); } internal void EnsureIncomingIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext) { EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForIncomingMessage); } internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext) { AdjustAddress(ref serviceReference, via); this.EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForOutgoingMessage); } internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies"); } AuthorizationContext ac = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies); EnsureIdentity(serviceReference, ac, SR.IdentityCheckFailedForOutgoingMessage); } void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString) { if (authorizationContext == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext"); } EndpointIdentity identity; if (!TryGetIdentity(serviceReference, out identity)) { SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(errorString, identity, serviceReference))); } else { if (!CheckAccess(identity, authorizationContext)) { // CheckAccess performs a Trace on failure, no need to do it twice Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e); } } } Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference) { Exception result; if (identity.IdentityClaim != null && identity.IdentityClaim.ClaimType == ClaimTypes.Dns && identity.IdentityClaim.Right == Rights.PossessProperty && identity.IdentityClaim.Resource is string) { string expectedDnsName = (string)identity.IdentityClaim.Resource; string actualDnsName = null; for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authorizationContext.ClaimSets[i]; foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty)) { if (claim.Resource is string) { actualDnsName = (string)claim.Resource; break; } } if (actualDnsName != null) { break; } } if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString)) { if (actualDnsName == null) { result = new MessageSecurityException(SR.GetString(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName)); } else { result = new MessageSecurityException(SR.GetString(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName)); } } else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString)) { if (actualDnsName == null) { result = new MessageSecurityException(SR.GetString(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName)); } else { result = new MessageSecurityException(SR.GetString(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName)); } } else { result = new MessageSecurityException(SR.GetString(errorString, identity, serviceReference)); } } else { result = new MessageSecurityException(SR.GetString(errorString, identity, serviceReference)); } return result; } class DefaultIdentityVerifier : IdentityVerifier { static readonly DefaultIdentityVerifier instance = new DefaultIdentityVerifier(); public static DefaultIdentityVerifier Instance { get { return instance; } } public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity) { if (reference == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference"); identity = reference.Identity; if (identity == null) { identity = this.TryCreateDnsIdentity(reference); } if (identity == null) { SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier)); return false; } else { SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier)); return true; } } EndpointIdentity TryCreateDnsIdentity(EndpointAddress reference) { Uri toAddress = reference.Uri; if (!toAddress.IsAbsoluteUri) return null; return EndpointIdentity.CreateDnsIdentity(toAddress.DnsSafeHost); } SecurityIdentifier GetSecurityIdentifier(Claim claim) { // if the incoming claim is a SID and the EndpointIdentity is UPN/SPN/DNS, try to find the SID corresponding to // the UPN/SPN/DNS (transactions case) if (claim.Resource is WindowsIdentity) return ((WindowsIdentity)claim.Resource).User; else if (claim.Resource is WindowsSidIdentity) return ((WindowsSidIdentity)claim.Resource).SecurityIdentifier; return claim.Resource as SecurityIdentifier; } Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn) { // host/<machine-name> satisfies the DNS identity claim IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty); foreach (Claim claim in claims) { if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase)) { return claim; } } return null; } Claim CheckSidEquivalence(SecurityIdentifier identitySid, ClaimSet claimSet) { foreach (Claim claim in claimSet) { SecurityIdentifier sid = GetSecurityIdentifier(claim); if (sid != null) { if (identitySid.Equals(sid)) { return claim; } } } return null; } public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext) { EventTraceActivity eventTraceActivity = null; if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (authContext == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext"); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null); } for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; if (claimSet.ContainsClaim(identity.IdentityClaim)) { SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType()); return true; } // try Claim equivalence string expectedSpn = null; if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) { expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource); Claim claim = CheckDnsEquivalence(claimSet, expectedSpn); if (claim != null) { SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType()); return true; } } // Allow a Sid claim to support UPN, and SPN identities SecurityIdentifier identitySid = null; if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType)) { identitySid = GetSecurityIdentifier(identity.IdentityClaim); } else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)) { identitySid = ((UpnEndpointIdentity)identity).GetUpnSid(); } else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)) { identitySid = ((SpnEndpointIdentity)identity).GetSpnSid(); } else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) { identitySid = new SpnEndpointIdentity(expectedSpn).GetSpnSid(); } if (identitySid != null) { Claim claim = CheckSidEquivalence(identitySid, claimSet); if (claim != null) { SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType()); return true; } } } SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType()); if (TD.SecurityIdentityVerificationFailureIsEnabled()) { TD.SecurityIdentityVerificationFailure(eventTraceActivity); } return false; } } } }
/* * MindTouch DekiScript - embeddable web-oriented scripting runtime * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using MindTouch.Deki.Script.Runtime; using MindTouch.Xml; namespace MindTouch.Deki.Script.Expr { public class DekiScriptMap : DekiScriptComplexLiteral { //--- Class Methods --- private static void FillDictionaryRecursively(DekiScriptMap map, Dictionary<string, DekiScriptLiteral> dictionary) { if(map.Outer != null) { FillDictionaryRecursively(map.Outer, dictionary); } foreach(var entry in map._value) { dictionary[entry.Key] = entry.Value; } } //--- Fields --- private readonly Dictionary<string, DekiScriptLiteral> _value = new Dictionary<string, DekiScriptLiteral>(StringComparer.OrdinalIgnoreCase); public readonly DekiScriptMap Outer; //--- Constructors --- public DekiScriptMap() : this(null, null) { } public DekiScriptMap(Hashtable value) : this(value, null) { } public DekiScriptMap(DekiScriptMap outer) : this(null, outer) { } public DekiScriptMap(Hashtable value, DekiScriptMap outer) { this.Outer = outer; if(value != null) { foreach(System.Collections.DictionaryEntry entry in value) { Add(entry.Key.ToString(), FromNativeValue(entry.Value)); } } } //--- Properties --- public override DekiScriptType ScriptType { get { return DekiScriptType.MAP; } } public bool IsEmpty { get { return _value.Count == 0 && (Outer == null || Outer.IsEmpty); } } public Dictionary<string, DekiScriptLiteral> Value { get { if(Outer == null) { return _value; } var value = new Dictionary<string, DekiScriptLiteral>(); FillDictionaryRecursively(this, value); return value; } } public override object NativeValue { get { Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach(KeyValuePair<string, DekiScriptLiteral> entry in Value) { result[entry.Key] = entry.Value.NativeValue; } return result; } } public DekiScriptLiteral this[string name] { get { DekiScriptLiteral result; if(!_value.TryGetValue(name, out result)) { if(Outer != null) { return Outer[name]; } return DekiScriptNil.Value; } return result; } set { // find defining scopye (if any) DekiScriptMap scope = this; while((scope != null) && !scope._value.ContainsKey(name)) { scope = scope.Outer; } // check if we found a scope if(scope != null) { scope._value[name] = value; } else { Add(name, value); } } } public DekiScriptLiteral this[DekiScriptLiteral index] { get { if(index == null) { throw new ArgumentNullException("index"); } if((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { return this[SysUtil.ChangeType<string>(index.NativeValue)]; } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } } set { if(index == null) { throw new ArgumentNullException("index"); } if((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { this[SysUtil.ChangeType<string>(index.NativeValue)] = value; } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } } } //--- Methods --- public DekiScriptMap Add(string key, DekiScriptLiteral value) { if(key == null) { throw new ArgumentNullException("key"); } if(value == null) { _value.Remove(key); } else { _value[key] = value; } return this; } public DekiScriptMap AddAt(string[] keys, DekiScriptLiteral value) { return AddAt(keys, value, true); } public DekiScriptMap AddAt(string[] keys, DekiScriptLiteral value, bool ignoreOnError) { if(ArrayUtil.IsNullOrEmpty(keys)) { throw new ArgumentNullException("keys"); } if(value == null) { throw new ArgumentNullException("value"); } // loop over all keys, except last, to get to the last map string key; DekiScriptMap current = this; for(int i = 0; i < keys.Length - 1; ++i) { if(keys[i] == null) { if(ignoreOnError) { return this; } throw new ArgumentException(string.Format("keys[{0}] is null", i)); } key = keys[i]; DekiScriptLiteral next = current[key]; if(next.ScriptType == DekiScriptType.NIL) { next = new DekiScriptMap(); current.Add(key, next); } else if(next.ScriptType != DekiScriptType.MAP) { if(ignoreOnError) { return this; } throw new Exception(string.Format("entry at '{0}' is not a map", string.Join(".", keys, 0, i + 1))); } current = (DekiScriptMap)next; } // add new item using the final key current.Add(keys[keys.Length - 1], value); return this; } public DekiScriptMap AddAt(string path, DekiScriptLiteral value) { if(path == null) { throw new ArgumentNullException("path"); } if(value == null) { throw new ArgumentNullException("value"); } return AddAt(path.Split('.'), value); } public DekiScriptMap AddNativeValueAt(string path, object value) { if(path == null) { throw new ArgumentNullException("path"); } return AddAt(path.Split('.'), FromNativeValue(value)); } public DekiScriptLiteral GetAt(string[] keys) { if(ArrayUtil.IsNullOrEmpty(keys)) { return DekiScriptNil.Value; } DekiScriptMap container = this; for(int i = 0; i < keys.Length - 1; ++i) { container = container[keys[i]] as DekiScriptMap; if(container == null) { return DekiScriptNil.Value; } } return container[keys[keys.Length - 1]]; } public DekiScriptLiteral GetAt(string path) { if(path == null) { throw new ArgumentNullException("path"); } return GetAt(path.Split('.')); } public DekiScriptMap AddRange(DekiScriptMap map) { foreach(KeyValuePair<string, DekiScriptLiteral> entry in map.Value) { _value[entry.Key] = entry.Value; } return this; } public bool TryGetValue(string name, out DekiScriptLiteral value) { if(!_value.TryGetValue(name, out value)) { if(Outer != null) { return Outer.TryGetValue(name, out value); } value = DekiScriptNil.Value; return false; } return true; } public bool TryGetValue(DekiScriptLiteral index, out DekiScriptLiteral value) { if(index == null) { throw new ArgumentNullException("index"); } if((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { return TryGetValue(SysUtil.ChangeType<string>(index.NativeValue), out value); } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } } public XDoc ToXml() { XDoc result = new XDoc("value").Attr("type", ScriptTypeName); AppendXml(result); return result; } public override void AppendXml(XDoc doc) { if(Outer != null) { Outer.AppendXml(doc); } foreach(KeyValuePair<string, DekiScriptLiteral> entry in _value) { doc.Start("value").Attr("key", entry.Key).Attr("type", entry.Value.ScriptTypeName); entry.Value.AppendXml(doc); doc.End(); } } public override DekiScriptLiteral Convert(DekiScriptType type) { switch(type) { case DekiScriptType.ANY: case DekiScriptType.MAP: return this; case DekiScriptType.LIST: { DekiScriptList result = new DekiScriptList(); foreach(DekiScriptLiteral value in Value.Values) { result.Add(value); } return result; } } throw new DekiScriptInvalidCastException(Location, ScriptType, type); } public override TReturn VisitWith<TState, TReturn>(IDekiScriptExpressionVisitor<TState, TReturn> visitor, TState state) { return visitor.Visit(this, state); } } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:41 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.layout { #region ContextItem /// <inheritdocs /> /// <summary> /// <p><strong>NOTE</strong> This is a private utility class for internal use by the framework. Don't rely on its existence.</p><p>This class manages state information for a component or element during a layout.</p> /// <h1>Blocks</h1> /// <p>A "block" is a required value that is preventing further calculation. When a layout has /// encountered a situation where it cannot possibly calculate results, it can associate /// itself with the context item and missing property so that it will not be rescheduled /// until that property is set.</p> /// <p>Blocks are a one-shot registration. Once the property changes, the block is removed.</p> /// <p>Be careful with blocks. If <em>any</em> further calculations can be made, a block is not the /// right choice.</p> /// <h1>Triggers</h1> /// <p>Whenever any call to <see cref="Ext.layout.ContextItem.getProp">getProp</see>, <see cref="Ext.layout.ContextItem.getDomProp">getDomProp</see>, <see cref="Ext.layout.ContextItem.hasProp">hasProp</see> or /// <see cref="Ext.layout.ContextItem.hasDomProp">hasDomProp</see> is made, the current layout is automatically registered as being /// dependent on that property in the appropriate state. Any changes to the property will /// trigger the layout and it will be queued in the <see cref="Ext.layout.Context">Ext.layout.Context</see>.</p> /// <p>Triggers, once added, remain for the entire layout. Any changes to the property will /// reschedule all unfinished layouts in their trigger set.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class ContextItem : Ext.Base { /// <summary> /// State variables that are cleared when invalidated. Only applies to component items. /// Defaults to: <c>null</c> /// </summary> public JsObject state{get;set;} /// <summary> /// True if this item wraps a Component (rather than an Element). /// Defaults to: <c>false</c> /// </summary> public bool wrapsComponent{get;set;} /// <summary> /// Adds a block. /// </summary> /// <param name="name"><p>The name of the block list ('blocks' or 'domBlocks').</p> /// </param> /// <param name="layout"><p>The layout that is blocked.</p> /// </param> /// <param name="propName"><p>The property name that blocked the layout (e.g., 'width').</p> /// </param> private void addBlock(JsString name, Layout layout, JsString propName){} /// <summary> /// Queue the addition of a class name (or array of class names) to this ContextItem's target when next flushed. /// </summary> /// <param name="newCls"> /// </param> public void addCls(object newCls){} /// <summary> /// Adds a trigger. /// </summary> /// <param name="propName"><p>The property name that triggers the layout (e.g., 'width').</p> /// </param> /// <param name="inDom"><p>True if the trigger list is <c>domTriggers</c>, false if <c>triggers</c>.</p> /// </param> private void addTrigger(JsString propName, bool inDom){} /// <summary> /// Registers a layout in the block list for the given property. Once the property is /// set in the Ext.layout.Context, the layout is unblocked. /// </summary> /// <param name="layout"> /// </param> /// <param name="propName"><p>The property name that blocked the layout (e.g., 'width').</p> /// </param> public void block(Layout layout, JsString propName){} /// <summary> /// Removes any blocks on a property in the specified set. Any layouts that were blocked /// by this property and are not still blocked (by other properties) will be rescheduled. /// </summary> /// <param name="name"><p>The name of the block list ('blocks' or 'domBlocks').</p> /// </param> /// <param name="propName"><p>The property name that blocked the layout (e.g., 'width').</p> /// </param> private void clearBlocks(JsString name, JsString propName){} /// <summary> /// clears the margin cache so that marginInfo get re-read from the dom on the next call to getMarginInfo() /// This is needed in some special cases where the margins have changed since the last layout, making the cached /// values invalid. For example collapsed window headers have different margin than expanded ones. /// </summary> public void clearMarginCache(){} /// <summary> /// Registers a layout in the DOM block list for the given property. Once the property /// flushed to the DOM by the Ext.layout.Context, the layout is unblocked. /// </summary> /// <param name="layout"> /// </param> /// <param name="propName"><p>The property name that blocked the layout (e.g., 'width').</p> /// </param> public void domBlock(Layout layout, JsString propName){} /// <summary> /// Reschedules any layouts associated with a given trigger. /// </summary> /// <param name="name"><p>The name of the trigger list ('triggers' or 'domTriggers').</p> /// </param> /// <param name="propName"><p>The property name that triggers the layout (e.g., 'width').</p> /// </param> private void fireTriggers(JsString name, JsString propName){} /// <summary> /// Flushes any updates in the dirty collection to the DOM. This is only called if there /// are dirty entries because this object is only added to the flushQueue of the /// Ext.layout.Context when entries become dirty. /// </summary> public void flush(){} /// <summary> /// </summary> private void flushAnimations(){} /// <summary> /// Gets the border information for the element as an object with left, top, right and /// bottom properties holding border size in pixels. This object is only read from the /// DOM on first request and is cached. /// </summary> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public object getBorderInfo(){return null;} /// <summary> /// Returns a ClassList-like object to buffer access to this item's element's classes. /// </summary> public void getClassList(){} /// <summary> /// Gets a property of this object if it is correct in the DOM. Also tracks the current /// layout as dependent on this property so that DOM writes of it will trigger the /// layout to be recalculated. /// </summary> /// <param name="propName"><p>The property name (e.g., 'width').</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The property value or undefined if not yet set or is dirty.</p> /// </div> /// </returns> public object getDomProp(JsString propName){return null;} /// <summary> /// Returns the context item for an owned element. This should only be called on a /// component's item. The list of child items is used to manage invalidating calculated /// results. /// </summary> /// <param name="nameOrEl"> /// </param> /// <param name="owner"> /// </param> public void getEl(object nameOrEl, object owner){} /// <summary> /// Gets the "frame" information for the element as an object with left, top, right and /// bottom properties holding border+framing size in pixels. This object is calculated /// on first request and is cached. /// </summary> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public object getFrameInfo(){return null;} /// <summary> /// Gets the margin information for the element as an object with left, top, right and /// bottom properties holding margin size in pixels. This object is only read from the /// DOM on first request and is cached. /// </summary> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public object getMarginInfo(){return null;} /// <summary> /// Gets the padding information for the element as an object with left, top, right and /// bottom properties holding padding size in pixels. This object is only read from the /// DOM on first request and is cached. /// </summary> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public object getPaddingInfo(){return null;} /// <summary> /// Gets a property of this object. Also tracks the current layout as dependent on this /// property so that changes to it will trigger the layout to be recalculated. /// </summary> /// <param name="propName"><p>The property name that blocked the layout (e.g., 'width').</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The property value or undefined if not yet set.</p> /// </div> /// </returns> public object getProp(JsString propName){return null;} /// <summary> /// Returns a style for this item. Each style is read from the DOM only once on first /// request and is then cached. If the value is an integer, it is parsed automatically /// (so '5px' is not returned, but rather 5). /// </summary> /// <param name="styleName"><p>The CSS style name.</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The value of the DOM style (parsed as necessary).</p> /// </div> /// </returns> public object getStyle(JsString styleName){return null;} /// <summary> /// Returns styles for this item. Each style is read from the DOM only once on first /// request and is then cached. If the value is an integer, it is parsed automatically /// (so '5px' is not returned, but rather 5). /// </summary> /// <param name="styleNames"><p>The CSS style names.</p> /// </param> /// <param name="altNames"><p>The alternate names for the returned styles. If given, /// these names must correspond one-for-one to the <c>styleNames</c>.</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The values of the DOM styles (parsed as necessary).</p> /// </div> /// </returns> public object getStyles(JsArray<String> styleNames, object altNames=null){return null;} /// <summary> /// Returns true if the given property is correct in the DOM. This is equivalent to /// calling getDomProp and not getting an undefined result. In particular, /// this call registers the current layout to be triggered by flushes of this property. /// </summary> /// <param name="propName"><p>The property name (e.g., 'width').</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div> /// </div> /// </returns> public bool hasDomProp(JsString propName){return false;} /// <summary> /// Returns true if the given property has been set. This is equivalent to calling /// getProp and not getting an undefined result. In particular, this call /// registers the current layout to be triggered by changes to this property. /// </summary> /// <param name="propName"><p>The property name (e.g., 'width').</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div> /// </div> /// </returns> public bool hasProp(JsString propName){return false;} /// <summary> /// Clears all properties on this object except (perhaps) those not calculated by this /// component. This is more complex than it would seem because a layout can decide to /// invalidate its results and run the component's layouts again, but since some of the /// values may be calculated by the container, care must be taken to preserve those /// values. /// </summary> /// <param name="full"><p>True if all properties are to be invalidated, false to keep /// those calculated by the ownerCt.</p> /// </param> /// <returns> /// <span>Mixed</span><div><p>A value to pass as the first argument to <see cref="Ext.layout.ContextItem">initContinue</see>.</p> /// </div> /// </returns> private JsObject init(bool full){return null;} /// <summary> /// </summary> private void initAnimation(){} /// <summary> /// Parameters<li><span>full</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="full"> /// </param> private void initContinue(object full){} /// <summary> /// Parameters<li><span>full</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>componentChildrenDone</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>containerChildrenDone</span> : <see cref="Object">Object</see><div> /// </div></li><li><span>containerLayoutDone</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="full"> /// </param> /// <param name="componentChildrenDone"> /// </param> /// <param name="containerChildrenDone"> /// </param> /// <param name="containerLayoutDone"> /// </param> private void initDone(object full, object componentChildrenDone, object containerChildrenDone, object containerLayoutDone){} /// <summary> /// Invalidates the component associated with this item. The layouts for this component /// and all of its contained items will be re-run after first clearing any computed /// values. /// If state needs to be carried forward beyond the invalidation, the <c>options</c> parameter /// can be used. /// </summary> /// <param name="options"><p>An object describing how to handle the invalidation.</p> /// <ul><li><span>state</span> : <see cref="Object">Object</see><div><p>An object to <see cref="Ext.ExtContext.apply">Ext.apply</see> to the <see cref="Ext.layout.ContextItem.state">state</see> /// of this item after invalidation clears all other properties.</p> /// </div></li><li><span>before</span> : <see cref="Function">Function</see><div><p>A function to call after the context data is cleared /// and before the <see cref="Ext.layout.Layout.beginLayoutCycle">Ext.layout.Layout.beginLayoutCycle</see> methods are called.</p> /// <h3>Parameters</h3><ul><li><span>item</span> : <see cref="Ext.layout.ContextItem">Ext.layout.ContextItem</see><div><p>This ContextItem.</p> /// </div></li><li><span>options</span> : <see cref="Object">Object</see><div><p>The options object passed to <see cref="Ext.layout.ContextItem.invalidate">invalidate</see>.</p> /// </div></li></ul></div></li><li><span>after</span> : <see cref="Function">Function</see><div><p>A function to call after the context data is cleared /// and after the <see cref="Ext.layout.Layout.beginLayoutCycle">Ext.layout.Layout.beginLayoutCycle</see> methods are called.</p> /// <h3>Parameters</h3><ul><li><span>item</span> : <see cref="Ext.layout.ContextItem">Ext.layout.ContextItem</see><div><p>This ContextItem.</p> /// </div></li><li><span>options</span> : <see cref="Object">Object</see><div><p>The options object passed to <see cref="Ext.layout.ContextItem.invalidate">invalidate</see>.</p> /// </div></li></ul></div></li><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope to use when calling the callback functions.</p> /// </div></li></ul></param> public void invalidate(object options){} /// <summary> /// Recovers a property value from the last computation and restores its value and /// dirty state. /// </summary> /// <param name="propName"><p>The name of the property to recover.</p> /// </param> /// <param name="oldProps"><p>The old "props" object from which to recover values.</p> /// </param> /// <param name="oldDirty"><p>The old "dirty" object from which to recover state.</p> /// </param> public void recoverProp(JsString propName, object oldProps, object oldDirty){} /// <summary> /// Queue the removal of a class name (or array of class names) from this ContextItem's target when next flushed. /// </summary> /// <param name="removeCls"> /// </param> public void removeCls(object removeCls){} /// <summary> /// Queue the setting of a DOM attribute on this ContextItem's target when next flushed. /// </summary> /// <param name="name"> /// </param> /// <param name="value"> /// </param> public void setAttribute(object name, object value){} /// <summary> /// Sets the contentHeight property. If the component uses raw content, then only the /// measured height is acceptable. /// Calculated values can sometimes be NaN or undefined, which generally mean the /// calculation is not done. To indicate that such as value was passed, 0 is returned. /// Otherwise, 1 is returned. /// If the caller is not measuring (i.e., they are calculating) and the component has raw /// content, 1 is returned indicating that the caller is done. /// </summary> /// <param name="height"> /// </param> /// <param name="measured"> /// </param> public void setContentHeight(object height, object measured){} /// <summary> /// Sets the contentWidth and contentHeight properties. If the component uses raw content, /// then only the measured values are acceptable. /// Calculated values can sometimes be NaN or undefined, which generally means that the /// calculation is not done. To indicate that either passed value was such a value, false /// returned. Otherwise, true is returned. /// If the caller is not measuring (i.e., they are calculating) and the component has raw /// content, true is returned indicating that the caller is done. /// </summary> /// <param name="width"> /// </param> /// <param name="height"> /// </param> /// <param name="measured"> /// </param> public void setContentSize(object width, object height, object measured){} /// <summary> /// Sets the contentWidth property. If the component uses raw content, then only the /// measured width is acceptable. /// Calculated values can sometimes be NaN or undefined, which generally means that the /// calculation is not done. To indicate that such as value was passed, 0 is returned. /// Otherwise, 1 is returned. /// If the caller is not measuring (i.e., they are calculating) and the component has raw /// content, 1 is returned indicating that the caller is done. /// </summary> /// <param name="width"> /// </param> /// <param name="measured"> /// </param> public void setContentWidth(object width, object measured){} /// <summary> /// Sets the height and constrains the height to min/maxHeight range. /// </summary> /// <param name="height"><p>The height.</p> /// </param> /// <param name="dirty"><p>Specifies if the value is currently in the DOM. A /// value of <c>false</c> indicates that the value is already in the DOM.</p> /// <p>Defaults to: <c>true</c></p></param> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>The actual height after constraining.</p> /// </div> /// </returns> public JsNumber setHeight(JsNumber height, object dirty=null){return null;} /// <summary> /// Sets a property value. This will unblock and/or trigger dependent layouts if the /// property value is being changed. Values of NaN and undefined are not accepted by /// this method. /// </summary> /// <param name="propName"><p>The property name (e.g., 'width').</p> /// </param> /// <param name="value"><p>The new value of the property.</p> /// </param> /// <param name="dirty"><p>Optionally specifies if the value is currently in the DOM /// (default is <c>true</c> which indicates the value is not in the DOM and must be flushed /// at some point).</p> /// </param> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>1 if this call specified the property value, 0 if not.</p> /// </div> /// </returns> public JsNumber setProp(JsString propName, object value, object dirty=null){return null;} /// <summary> /// Sets the height and constrains the width to min/maxWidth range. /// </summary> /// <param name="width"><p>The width.</p> /// </param> /// <param name="dirty"><p>Specifies if the value is currently in the DOM. A /// value of <c>false</c> indicates that the value is already in the DOM.</p> /// <p>Defaults to: <c>true</c></p></param> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>The actual width after constraining.</p> /// </div> /// </returns> public JsNumber setWidth(JsNumber width, object dirty=null){return null;} public ContextItem(ContextItemConfig config){} public ContextItem(){} public ContextItem(params object[] args){} } #endregion #region ContextItemConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ContextItemConfig : Ext.BaseConfig { public ContextItemConfig(params object[] args){} } #endregion #region ContextItemEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ContextItemEvents : Ext.BaseEvents { public ContextItemEvents(params object[] args){} } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using CryptographicException = System.Security.Cryptography.CryptographicException; using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle; using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle; using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags; using SafeNCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; internal static partial class Interop { public static partial class crypt32 { [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 out CertEncodingType pdwMsgAndCertEncodingType, out ContentType pdwContentType, out FormatType pdwFormatType, out SafeCertStoreHandle phCertStore, out SafeCryptMsgHandle phMsg, out SafeCertContextHandle ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 IntPtr pdwMsgAndCertEncodingType, out ContentType pdwContentType, IntPtr pdwFormatType, IntPtr phCertStore, IntPtr phMsg, IntPtr ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 IntPtr pdwMsgAndCertEncodingType, out ContentType pdwContentType, IntPtr pdwFormatType, out SafeCertStoreHandle phCertStore, IntPtr phMsg, IntPtr ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")] public static extern bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] StringBuilder pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")] public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvTypePara, [Out] StringBuilder pszNameString, int cchNameString); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")] public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext); public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, string pvPara) { return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pvPara); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext); /// <summary> /// A less error-prone wrapper for CertEnumCertificatesInStore(). /// /// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with /// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle /// and returns "false" to indicate the the end of the store has been reached. /// </summary> public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext) { unsafe { CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect(); pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext); return !pCertContext.IsInvalid; } } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, string szPassword, PfxCertStoreFlags dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, [Out] byte[] pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, string szPassword, PFXExportFlags dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertNameToStrW")] public static extern int CertNameToStr(CertEncodingType dwCertEncodingType, [In] ref CRYPTOAPI_BLOB pName, CertNameStrTypeAndFlags dwStrType, StringBuilder psz, int csz); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")] public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError); public static bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, FormatObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, StringBuilder pbFormat, ref int pcbFormat) { return CryptFormatObject(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (IntPtr)lpszStructType, pbEncoded, cbEncoded, pbFormat, ref pcbFormat); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, [Out] StringBuilder pbFormat, [In, Out] ref int pcbFormat); public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo) { return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo); public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo) { return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")] private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")] public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo); public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded) { return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded); public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded) { int cb = 0; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] encoded = new byte[cb]; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return encoded; } public static unsafe byte[] EncodeObject(string lpszStructType, void* decoded) { int cb = 0; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] encoded = new byte[cb]; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return encoded; } public static unsafe bool CertGetCertificateChain(ChainEngine hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext) { return CertGetCertificateChain((IntPtr)hChainEngine, pCertContext, pTime, hStore, ref pChainPara, dwFlags, pvReserved, out ppChainContext); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")] public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStrTypeAndFlags pvPara, [Out] StringBuilder pszNameString, int cchNameString); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags); /// <summary> /// A less error-prone wrapper for CertEnumCertificatesInStore(). /// /// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with /// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle /// and returns "false" to indicate the the end of the store has been reached. /// </summary> public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext) { CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect(); pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext); return !pCertContext.IsInvalid; } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static unsafe extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions); // Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise // identical to the wincrypt CERT_*_USAGE values. [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static unsafe extern bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara); // Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered. [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void CertFreeCertificateChain(IntPtr pChainContext); public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertFreeCertificateContext(IntPtr pCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptMsgClose(IntPtr hCryptMsg); #if !NETNATIVE [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey); #endif [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey); } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <[email protected]> * Rudi Pettazzi <[email protected]> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Collections.Generic; using System.Text; namespace Ude.Core { public abstract class JapaneseContextAnalyser { protected const int CATEGORIES_NUM = 6; protected const int ENOUGH_REL_THRESHOLD = 100; protected const int MAX_REL_THRESHOLD = 1000; protected const int MINIMUM_DATA_THRESHOLD = 4; protected const float DONT_KNOW = -1.0f; // hiragana frequency category table // This is hiragana 2-char sequence table, the number in each cell represents its frequency category protected static byte[,] jp2CharContext = { { 0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,}, { 2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4,}, { 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,}, { 0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4,}, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}, { 0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4,}, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}, { 0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3,}, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}, { 0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4,}, { 1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4,}, { 0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3,}, { 0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3,}, { 0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3,}, { 0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4,}, { 0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3,}, { 2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4,}, { 0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3,}, { 0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5,}, { 0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3,}, { 2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5,}, { 0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4,}, { 1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4,}, { 0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3,}, { 0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3,}, { 0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3,}, { 0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5,}, { 0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4,}, { 0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5,}, { 0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3,}, { 0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4,}, { 0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4,}, { 0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4,}, { 0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1,}, { 0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,}, { 1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3,}, { 0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0,}, { 0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3,}, { 0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3,}, { 0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5,}, { 0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4,}, { 2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5,}, { 0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3,}, { 0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3,}, { 0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3,}, { 0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3,}, { 0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4,}, { 0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4,}, { 0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,0,2,0,0,0,0,0,0,2,}, { 0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3,}, { 0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3,}, { 0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3,}, { 0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3,}, { 0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4,}, { 0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3,}, { 0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4,}, { 0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3,}, { 0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,0,0,0,0,0,3,}, { 0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4,}, { 0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4,}, { 0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,2,3,}, { 2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4,}, { 0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4,}, { 0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3,}, { 0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4,}, { 0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4,}, { 1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4,}, { 0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3,}, { 0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2,}, { 0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2,}, { 0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3,}, { 0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3,}, { 0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5,}, { 0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3,}, { 0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4,}, { 1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4,}, { 0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4,}, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}, { 0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3,}, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1,}, { 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2,}, { 0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3,}, { 0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1,}, }; // category counters, each integer counts sequence in its category int[] relSample = new int[CATEGORIES_NUM]; // total sequence received int totalRel; // The order of previous char int lastCharOrder; // if last byte in current buffer is not the last byte of a character, // we need to know how many byte to skip in next buffer. int needToSkipCharNum; // If this flag is set to true, detection is done and conclusion has // been made bool done; public JapaneseContextAnalyser() { Reset(); } public float GetConfidence() { // This is just one way to calculate confidence. It works well for me. if (totalRel > MINIMUM_DATA_THRESHOLD) return ((float)(totalRel - relSample[0]))/totalRel; else return DONT_KNOW; } public void HandleData(byte[] buf, int offset, int len) { int charLen = 0; int max = offset + len; if (done) return; // The buffer we got is byte oriented, and a character may span // more than one buffer. In case the last one or two byte in last // buffer is not complete, we record how many byte needed to // complete that character and skip these bytes here. We can choose // to record those bytes as well and analyse the character once it // is complete, but since a character will not make much difference, // skipping it will simplify our logic and improve performance. for (int i = needToSkipCharNum+offset; i < max; ) { int order = GetOrder(buf, i, out charLen); i += charLen; if (i > max) { needToSkipCharNum = i - max; lastCharOrder = -1; } else { if (order != -1 && lastCharOrder != -1) { totalRel ++; if (totalRel > MAX_REL_THRESHOLD) { done = true; break; } relSample[jp2CharContext[lastCharOrder, order]]++; } lastCharOrder = order; } } } public void HandleOneChar(byte[] buf, int offset, int charLen) { if (totalRel > MAX_REL_THRESHOLD) done = true; if (done) return; // Only 2-bytes characters are of our interest int order = (charLen == 2) ? GetOrder(buf, offset) : -1; if (order != -1 && lastCharOrder != -1) { totalRel++; // count this sequence to its category counter relSample[jp2CharContext[lastCharOrder, order]]++; } lastCharOrder = order; } public void Reset() { totalRel = 0; for (int i = 0; i < CATEGORIES_NUM; i++) { relSample[i] = 0; needToSkipCharNum = 0; lastCharOrder = -1; done = false; } } protected abstract int GetOrder(byte[] buf, int offset, out int charLen); protected abstract int GetOrder(byte[] buf, int offset); public bool GotEnoughData() { return totalRel > ENOUGH_REL_THRESHOLD; } } public class SJISContextAnalyser : JapaneseContextAnalyser { private const byte HIRAGANA_FIRST_BYTE = 0x82; protected override int GetOrder(byte[] buf, int offset, out int charLen) { //find out current char's byte length if (buf[offset] >= 0x81 && buf[offset] <= 0x9F || buf[offset] >= 0xe0 && buf[offset] <= 0xFC) charLen = 2; else charLen = 1; // return its order if it is hiragana if (buf[offset] == HIRAGANA_FIRST_BYTE) { byte low = buf[offset+1]; if (low >= 0x9F && low <= 0xF1) return low - 0x9F; } return -1; } protected override int GetOrder(byte[] buf, int offset) { // We are only interested in Hiragana if (buf[offset] == HIRAGANA_FIRST_BYTE) { byte low = buf[offset+1]; if (low >= 0x9F && low <= 0xF1) return low - 0x9F; } return -1; } } public class EUCJPContextAnalyser : JapaneseContextAnalyser { private const byte HIRAGANA_FIRST_BYTE = 0xA4; protected override int GetOrder(byte[] buf, int offset, out int charLen) { byte high = buf[offset]; //find out current char's byte length if (high == 0x8E || high >= 0xA1 && high <= 0xFE) charLen = 2; else if (high == 0xBF) charLen = 3; else charLen = 1; // return its order if it is hiragana if (high == HIRAGANA_FIRST_BYTE) { byte low = buf[offset+1]; if (low >= 0xA1 && low <= 0xF3) return low - 0xA1; } return -1; } protected override int GetOrder(byte[] buf, int offset) { // We are only interested in Hiragana if (buf[offset] == HIRAGANA_FIRST_BYTE) { byte low = buf[offset+1]; if (low >= 0xA1 && low <= 0xF3) return low - 0xA1; } return -1; } } }
// Copyright 2007-2016 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.Saga { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Logging; using MassTransit.Pipeline; using Util; public class InMemorySagaRepository<TSaga> : ISagaRepository<TSaga>, IQuerySagaRepository<TSaga> where TSaga : class, ISaga { static readonly ILog _log = Logger.Get(typeof(InMemorySagaRepository<TSaga>)); readonly IndexedSagaDictionary<TSaga> _sagas; public InMemorySagaRepository() { _sagas = new IndexedSagaDictionary<TSaga>(); } public SagaInstance<TSaga> this[Guid id] => _sagas[id]; public Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query) { return Task.FromResult(_sagas.Where(query).Select(x => x.Instance.CorrelationId)); } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("sagaRepository"); scope.Set(new { _sagas.Count, Persistence = "memory" }); } async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) { if (!context.CorrelationId.HasValue) throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T)); var sagaId = context.CorrelationId.Value; var needToLeaveSagas = true; await _sagas.MarkInUse(context.CancellationToken).ConfigureAwait(false); try { SagaInstance<TSaga> saga = _sagas[sagaId]; if (saga != null) { await saga.MarkInUse(context.CancellationToken).ConfigureAwait(false); try { _sagas.Release(); needToLeaveSagas = false; if (saga.IsRemoved) { saga.Release(); saga = null; } else { if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, sagaId, TypeMetadataCache<T>.ShortName); SagaConsumeContext<TSaga, T> sagaConsumeContext = new InMemorySagaConsumeContext<TSaga, T>(context, saga.Instance, () => Remove(saga, context.CancellationToken)); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); } } finally { saga?.Release(); } } if(saga == null) { var missingSagaPipe = new MissingPipe<T>(this, next, true); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); _sagas.Release(); needToLeaveSagas = false; } } finally { if (needToLeaveSagas) { _sagas.Release(); } } } async Task ISagaRepository<TSaga>.SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) { SagaInstance<TSaga>[] existingSagas = _sagas.Where(context.Query).ToArray(); if (existingSagas.Length == 0) { var missingSagaPipe = new MissingPipe<T>(this, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else await Task.WhenAll(existingSagas.Select(instance => SendToInstance(context, policy, instance, next))).ConfigureAwait(false); } async Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, SagaInstance<TSaga> saga, IPipe<SagaConsumeContext<TSaga, T>> next) where T : class { await saga.MarkInUse(context.CancellationToken).ConfigureAwait(false); try { if (saga.IsRemoved) return; if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, saga.Instance.CorrelationId, TypeMetadataCache<T>.ShortName); SagaConsumeContext<TSaga, T> sagaConsumeContext = new InMemorySagaConsumeContext<TSaga, T>(context, saga.Instance, () => Remove(saga, context.CancellationToken)); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); } finally { saga.Release(); } } /// <summary> /// Add an instance to the saga repository /// </summary> /// <param name="instance"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task Add(SagaInstance<TSaga> instance, CancellationToken cancellationToken) { await _sagas.MarkInUse(cancellationToken).ConfigureAwait(false); try { _sagas.Add(instance); } finally { _sagas.Release(); } } /// <summary> /// Adds the saga within an existing lock /// </summary> /// <param name="instance"></param> void AddWithinLock(SagaInstance<TSaga> instance) { _sagas.Add(instance); } async Task Remove(SagaInstance<TSaga> instance, CancellationToken cancellationToken) { instance.Remove(); await _sagas.MarkInUse(cancellationToken).ConfigureAwait(false); try { _sagas.Remove(instance); } finally { _sagas.Release(); } } void RemoveWithinLock(SagaInstance<TSaga> instance) { instance.Remove(); _sagas.Remove(instance); } /// <summary> /// Once the message pipe has processed the saga instance, add it to the saga repository /// </summary> /// <typeparam name="TMessage"></typeparam> class MissingPipe<TMessage> : IPipe<SagaConsumeContext<TSaga, TMessage>> where TMessage : class { readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next; readonly InMemorySagaRepository<TSaga> _repository; readonly bool _withinLock; public MissingPipe(InMemorySagaRepository<TSaga> repository, IPipe<SagaConsumeContext<TSaga, TMessage>> next, bool withinLock = false) { _repository = repository; _next = next; _withinLock = withinLock; } void IProbeSite.Probe(ProbeContext context) { _next.Probe(context); } public async Task Send(SagaConsumeContext<TSaga, TMessage> context) { var instance = new SagaInstance<TSaga>(context.Saga); await instance.MarkInUse(context.CancellationToken).ConfigureAwait(false); try { var proxy = new InMemorySagaConsumeContext<TSaga, TMessage>(context, context.Saga, () => RemoveNewSaga(instance, context.CancellationToken)); if (_withinLock) _repository.AddWithinLock(instance); else await _repository.Add(instance, context.CancellationToken).ConfigureAwait(false); if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId, TypeMetadataCache<TMessage>.ShortName); } try { await _next.Send(proxy).ConfigureAwait(false); if (proxy.IsCompleted) { await RemoveNewSaga(instance, context.CancellationToken).ConfigureAwait(false); } } catch (Exception) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Removed(Fault) {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId, TypeMetadataCache<TMessage>.ShortName); } await RemoveNewSaga(instance, context.CancellationToken).ConfigureAwait(false); throw; } } finally { instance.Release(); } } async Task RemoveNewSaga(SagaInstance<TSaga> instance, CancellationToken cancellationToken) { if (_withinLock) _repository.RemoveWithinLock(instance); else await _repository.Remove(instance, cancellationToken).ConfigureAwait(false); } } } }
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation { partial class HerdReport { /// <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 Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HerdReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.herdDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSet(); this.sp_Rep_Vet_HerdDetailsTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel(); this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand(); this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.herdDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UseTextAlignment = false; // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UseFont = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell4, this.xrTableCell5, this.xrTableCell6, this.xrTableCell10}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.StylePriority.UseBorders = false; this.xrTableRow2.Weight = 0.65999999999999992; // // xrTableCell7 // this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.HerdCode")}); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseBorders = false; this.xrTableCell7.Weight = 0.94269278277332014; // // xrTableCell4 // this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.SpeciesID")}); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseBorders = false; this.xrTableCell4.Weight = 0.94269313860580994; // // xrTableCell5 // this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Total")}); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.Weight = 0.641295190088522; // // xrTableCell6 // this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Sick")}); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.Weight = 0.6412959020723481; // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.strNote")}); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.Weight = 1.2919416589675907; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell8, this.xrTableCell1, this.xrTableCell2, this.xrTableCell3, this.xrTableCell9}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1; // // xrTableCell8 // this.xrTableCell8.Name = "xrTableCell8"; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Weight = 0.94269287173144256; // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Weight = 0.94269287173144256; // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Weight = 0.6412955459210119; // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Weight = 0.641295546239858; // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Weight = 1.2919421927163259; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // herdDataSet1 // this.herdDataSet1.DataSetName = "HerdDataSet"; this.herdDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // sp_Rep_Vet_HerdDetailsTableAdapter // this.sp_Rep_Vet_HerdDetailsTableAdapter.ClearBeforeFill = true; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel1, this.xrTable1}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UseTextAlignment = false; // // xrLabel1 // this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel1, "xrLabel1"); this.xrLabel1.Name = "xrLabel1"; this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel1.StylePriority.UseBorders = false; this.xrLabel1.StylePriority.UseFont = false; // // topMarginBand1 // resources.ApplyResources(this.topMarginBand1, "topMarginBand1"); this.topMarginBand1.Name = "topMarginBand1"; // // bottomMarginBand1 // resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1"); this.bottomMarginBand1.Name = "bottomMarginBand1"; // // HerdReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.topMarginBand1, this.bottomMarginBand1}); this.DataAdapter = this.sp_Rep_Vet_HerdDetailsTableAdapter; this.DataMember = "spRepVetHerdDetails"; this.DataSource = this.herdDataSet1; resources.ApplyResources(this, "$this"); this.Version = "10.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.herdDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private HerdDataSet herdDataSet1; private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter sp_Rep_Vet_HerdDetailsTableAdapter; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRLabel xrLabel1; private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1; private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; } }
using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Versioning; namespace NuGet { [DataServiceKey("Id", "Version")] [EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)] [CLSCompliant(false)] public class DataServicePackage : IPackage { private IHashProvider _hashProvider; private bool _usingMachineCache; internal IPackage _package; public string Id { get; set; } public string Version { get; set; } public string Title { get; set; } public string Authors { get; set; } public string Owners { get; set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public Uri ReportAbuseUrl { get; set; } public Uri GalleryDetailsUrl { get; set; } public Uri DownloadUrl { get { return Context.GetReadStreamUri(this); } } public bool Listed { get; set; } public DateTimeOffset? Published { get; set; } public DateTimeOffset LastUpdated { get; set; } public int DownloadCount { get; set; } public bool RequireLicenseAcceptance { get; set; } public string Description { get; set; } public string Summary { get; set; } public string ReleaseNotes { get; set; } public string Language { get; set; } public string Tags { get; set; } public string Dependencies { get; set; } public string PackageHash { get; set; } public string PackageHashAlgorithm { get; set; } public bool IsLatestVersion { get; set; } public bool IsAbsoluteLatestVersion { get; set; } public string Copyright { get; set; } public string MinClientVersion { get; set; } private string OldHash { get; set; } private IPackage Package { get { EnsurePackage(MachineCache.Default); return _package; } } internal IDataServiceContext Context { get; set; } internal PackageDownloader Downloader { get; set; } internal IHashProvider HashProvider { get { return _hashProvider ?? new CryptoHashProvider(PackageHashAlgorithm); } set { _hashProvider = value; } } bool IPackage.Listed { get { return Listed; } } IEnumerable<string> IPackageMetadata.Authors { get { if (String.IsNullOrEmpty(Authors)) { return Enumerable.Empty<string>(); } return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<string> IPackageMetadata.Owners { get { if (String.IsNullOrEmpty(Owners)) { return Enumerable.Empty<string>(); } return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } public IEnumerable<PackageDependencySet> DependencySets { get { if (String.IsNullOrEmpty(Dependencies)) { return Enumerable.Empty<PackageDependencySet>(); } return ParseDependencySet(Dependencies); } } public ICollection<PackageReferenceSet> PackageAssemblyReferences { get { return Package.PackageAssemblyReferences; } } SemanticVersion IPackageMetadata.Version { get { if (Version != null) { return new SemanticVersion(Version); } return null; } } Version IPackageMetadata.MinClientVersion { get { if (!String.IsNullOrEmpty(MinClientVersion)) { return new Version(MinClientVersion); } return null; } } public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { return Package.AssemblyReferences; } } public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get { return Package.FrameworkAssemblies; } } public virtual IEnumerable<FrameworkName> GetSupportedFrameworks() { return Package.GetSupportedFrameworks(); } public IEnumerable<IPackageFile> GetFiles() { return Package.GetFiles(); } public Stream GetStream() { return Package.GetStream(); } public override string ToString() { return this.GetFullName(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] internal void EnsurePackage(IPackageCacheRepository cacheRepository) { // OData caches instances of DataServicePackage while updating their property values. As a result, // the ZipPackage that we downloaded may no longer be valid (as indicated by a newer hash). // When using MachineCache, once we've verified that the hashes match (which happens the first time around), // we'll simply verify the file exists between successive calls. IPackageMetadata packageMetadata = this; bool refreshPackage = _package == null || (_package is OptimizedZipPackage && !((OptimizedZipPackage)_package).IsValid) || !String.Equals(OldHash, PackageHash, StringComparison.OrdinalIgnoreCase) || (_usingMachineCache && !cacheRepository.Exists(Id, packageMetadata.Version)); if (refreshPackage && TryGetPackage(cacheRepository, packageMetadata, out _package) && _package.GetHash(HashProvider).Equals(PackageHash, StringComparison.OrdinalIgnoreCase)) { OldHash = PackageHash; // Reset the flag so that we no longer need to download the package since it exists and is valid. refreshPackage = false; // Make a note that the backing store for the ZipPackage is the machine cache. _usingMachineCache = true; } if (refreshPackage) { // We either do not have a package available locally or they are invalid. Download the package from the server. Stream targetStream = null; try { targetStream = cacheRepository.CreatePackageStream(packageMetadata.Id, packageMetadata.Version); // this can happen when access to the %LocalAppData% directory is blocked, e.g. on Windows Azure Web Site build if (targetStream != null) { _usingMachineCache = true; } else { // if we can't store the package into machine cache, store it in memory targetStream = new MemoryStream(); _usingMachineCache = false; } // download package into the stream Downloader.DownloadPackage(DownloadUrl, this, targetStream); } finally { if (targetStream != null && _usingMachineCache) { targetStream.Dispose(); } } if (_usingMachineCache) { _package = cacheRepository.FindPackage(packageMetadata.Id, packageMetadata.Version); Debug.Assert(_package != null); } else { targetStream.Seek(0, SeekOrigin.Begin); _package = new ZipPackage(targetStream); targetStream.Dispose(); } OldHash = PackageHash; } } private static List<PackageDependencySet> ParseDependencySet(string value) { var dependencySets = new List<PackageDependencySet>(); var dependencies = value.Split('|').Select(ParseDependency).ToList(); // group the dependencies by target framework var groups = dependencies.GroupBy(d => d.Item3); dependencySets.AddRange( groups.Select(g => new PackageDependencySet( g.Key, // target framework g.Where(pair => !String.IsNullOrEmpty(pair.Item1)) // the Id is empty when a group is empty. .Select(pair => new PackageDependency(pair.Item1, pair.Item2))))); // dependencies by that target framework return dependencySets; } /// <summary> /// Parses a dependency from the feed in the format: /// id or id:versionSpec, or id:versionSpec:targetFramework /// </summary> private static Tuple<string, IVersionSpec, FrameworkName> ParseDependency(string value) { if (String.IsNullOrWhiteSpace(value)) { return null; } // IMPORTANT: Do not pass StringSplitOptions.RemoveEmptyEntries to this method, because it will break // if the version spec is null, for in that case, the Dependencies string sent down is "<id>::<target framework>". // We do want to preserve the second empty element after the split. string[] tokens = value.Trim().Split(new[] { ':' }); if (tokens.Length == 0) { return null; } // Trim the id string id = tokens[0].Trim(); IVersionSpec versionSpec = null; if (tokens.Length > 1) { // Attempt to parse the version VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec); } var targetFramework = (tokens.Length > 2 && !String.IsNullOrEmpty(tokens[2])) ? VersionUtility.ParseFrameworkName(tokens[2]) : null; return Tuple.Create(id, versionSpec, targetFramework); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to return null if any error occurred while trying to find the package.")] private static bool TryGetPackage(IPackageRepository repository, IPackageMetadata packageMetadata, out IPackage package) { try { package = repository.FindPackage(packageMetadata.Id, packageMetadata.Version); } catch { // If the package in the repository is corrupted then return null package = null; } return package != null; } } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.Set, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssStorageProfile", SupportsShouldProcess = true)] [OutputType(typeof(PSVirtualMachineScaleSet))] public partial class SetAzureRmVmssStorageProfileCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public string ImageReferencePublisher { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public string ImageReferenceOffer { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public string ImageReferenceSku { get; set; } [Parameter( Mandatory = false, Position = 4, ValueFromPipelineByPropertyName = true)] public string ImageReferenceVersion { get; set; } [Parameter( Mandatory = false, Position = 5, ValueFromPipelineByPropertyName = true)] [Alias("Name")] public string OsDiskName { get; set; } [Parameter( Mandatory = false, Position = 6, ValueFromPipelineByPropertyName = true)] public CachingTypes? OsDiskCaching { get; set; } [Parameter( Mandatory = false, Position = 7, ValueFromPipelineByPropertyName = true)] public string OsDiskCreateOption { get; set; } [Parameter( Mandatory = false, Position = 8, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsDiskOsType { get; set; } [Parameter( Mandatory = false, Position = 9, ValueFromPipelineByPropertyName = true)] public string Image { get; set; } [Parameter( Mandatory = false, Position = 10, ValueFromPipelineByPropertyName = true)] public string[] VhdContainer { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string ImageReferenceId { get; set; } [Parameter( Mandatory = false)] public SwitchParameter OsDiskWriteAccelerator { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] [PSArgumentCompleter("Standard_LRS", "Premium_LRS")] public string ManagedDisk { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public VirtualMachineScaleSetDataDisk[] DataDisk { get; set; } protected override void ProcessRecord() { if (ShouldProcess("VirtualMachineScaleSet", "Set")) { Run(); } } private void Run() { if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferencePublisher")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // ImageReference if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher; } if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceOffer")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // ImageReference if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer; } if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceSku")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // ImageReference if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku; } if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceVersion")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // ImageReference if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion; } if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceId")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // ImageReference if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId; } if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskName")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name = this.OsDiskName; } if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCaching")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching; } // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.WriteAcceleratorEnabled = this.OsDiskWriteAccelerator.IsPresent; if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCreateOption")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.CreateOption = this.OsDiskCreateOption; } if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskOsType")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.OsType = this.OsDiskOsType; } if (this.MyInvocation.BoundParameters.ContainsKey("Image")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } // Image if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.Image; } if (this.MyInvocation.BoundParameters.ContainsKey("VhdContainer")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer; } if (this.MyInvocation.BoundParameters.ContainsKey("ManagedDisk")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } // OsDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } // ManagedDisk if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetManagedDiskParameters(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDisk; } if (this.MyInvocation.BoundParameters.ContainsKey("DataDisk")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } // StorageProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks = this.DataDisk; } WriteObject(this.VirtualMachineScaleSet); } } }
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; /** * Interpolation utility functions: easing, bezier, and catmull-rom. * Consider using Unity's Animation curve editor and AnimationCurve class * before scripting the desired behaviour using this utility. * * Interpolation functionality available at different levels of abstraction. * Low level access via individual easing functions (ex. EaseInOutCirc), * Bezier(), and CatmullRom(). High level access using sequence generators, * NewEase(), NewBezier(), and NewCatmullRom(). * * Sequence generators are typically used as follows: * * IEnumerable<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration); * foreach (Vector3 newPoint in sequence) { * transform.position = newPoint; * yield return WaitForSeconds(1.0f); * } * * Or: * * IEnumerator<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration).GetEnumerator(); * function Update() { * if (sequence.MoveNext()) { * transform.position = sequence.Current; * } * } * * The low level functions work similarly to Unity's built in Lerp and it is * up to you to track and pass in elapsedTime and duration on every call. The * functions take this form (or the logical equivalent for Bezier() and CatmullRom()). * * transform.position = ease(start, distance, elapsedTime, duration); * * For convenience in configuration you can use the Ease(EaseType) function to * look up a concrete easing function: * * [SerializeField] * Interpolate.EaseType easeType; // set using Unity's property inspector * Interpolate.Function ease; // easing of a particular EaseType * function Awake() { * ease = Interpolate.Ease(easeType); * } * * @author Fernando Zapata ([email protected]) * @Traduzione Andrea85cs ([email protected]) */ public class Interpolate { /** * Different methods of easing interpolation. */ public enum EaseType { Linear, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInSine, EaseOutSine, EaseInOutSine, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc } /** * Sequence of eleapsedTimes until elapsedTime is >= duration. * * Note: elapsedTimes are calculated using the value of Time.deltatTime each * time a value is requested. */ static Vector3 Identity(Vector3 v) { return v; } static Vector3 TransformDotPosition(Transform t) { return t.position; } static IEnumerable<float> NewTimer(float duration) { float elapsedTime = 0.0f; while (elapsedTime < duration) { yield return elapsedTime; elapsedTime += Time.deltaTime; // make sure last value is never skipped if (elapsedTime >= duration) { yield return elapsedTime; } } } public delegate Vector3 ToVector3<T>(T v); public delegate float Function(float a, float b, float c, float d); /** * Generates sequence of integers from start to end (inclusive) one step * at a time. */ static IEnumerable<float> NewCounter(int start, int end, int step) { for (int i = start; i <= end; i += step) { yield return i; } } /** * Returns sequence generator from start to end over duration using the * given easing function. The sequence is generated as it is accessed * using the Time.deltaTime to calculate the portion of duration that has * elapsed. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewEase(ease, start, end, duration, timer); } /** * Instead of easing based on time, generate n interpolated points (slices) * between the start and end positions. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, int slices) { IEnumerable<float> counter = Interpolate.NewCounter(0, slices + 1, 1); return NewEase(ease, start, end, slices + 1, counter); } /** * Generic easing sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float total, IEnumerable<float> driver) { Vector3 distance = end - start; foreach (float i in driver) { yield return Ease(ease, start, distance, i, total); } } /** * Vector3 interpolation using given easing method. Easing is done independently * on all three vector axis. */ static Vector3 Ease(Function ease, Vector3 start, Vector3 distance, float elapsedTime, float duration) { start.x = ease(start.x, distance.x, elapsedTime, duration); start.y = ease(start.y, distance.y, elapsedTime, duration); start.z = ease(start.z, distance.z, elapsedTime, duration); return start; } /** * Returns the static method that implements the given easing type for scalars. * Use this method to easily switch between easing interpolation types. * * All easing methods clamp elapsedTime so that it is always <= duration. * * var ease = Interpolate.Ease(EaseType.EaseInQuad); * i = ease(start, distance, elapsedTime, duration); */ public static Function Ease(EaseType type) { // Source Flash easing functions: // http://gizma.com/easing/ // http://www.robertpenner.com/easing/easing_demo.html // // Changed to use more friendly variable names, that follow my Lerp // conventions: // start = b (start value) // distance = c (change in value) // elapsedTime = t (current time) // duration = d (time duration) Function f = null; switch (type) { case EaseType.Linear: f = Interpolate.Linear; break; case EaseType.EaseInQuad: f = Interpolate.EaseInQuad; break; case EaseType.EaseOutQuad: f = Interpolate.EaseOutQuad; break; case EaseType.EaseInOutQuad: f = Interpolate.EaseInOutQuad; break; case EaseType.EaseInCubic: f = Interpolate.EaseInCubic; break; case EaseType.EaseOutCubic: f = Interpolate.EaseOutCubic; break; case EaseType.EaseInOutCubic: f = Interpolate.EaseInOutCubic; break; case EaseType.EaseInQuart: f = Interpolate.EaseInQuart; break; case EaseType.EaseOutQuart: f = Interpolate.EaseOutQuart; break; case EaseType.EaseInOutQuart: f = Interpolate.EaseInOutQuart; break; case EaseType.EaseInQuint: f = Interpolate.EaseInQuint; break; case EaseType.EaseOutQuint: f = Interpolate.EaseOutQuint; break; case EaseType.EaseInOutQuint: f = Interpolate.EaseInOutQuint; break; case EaseType.EaseInSine: f = Interpolate.EaseInSine; break; case EaseType.EaseOutSine: f = Interpolate.EaseOutSine; break; case EaseType.EaseInOutSine: f = Interpolate.EaseInOutSine; break; case EaseType.EaseInExpo: f = Interpolate.EaseInExpo; break; case EaseType.EaseOutExpo: f = Interpolate.EaseOutExpo; break; case EaseType.EaseInOutExpo: f = Interpolate.EaseInOutExpo; break; case EaseType.EaseInCirc: f = Interpolate.EaseInCirc; break; case EaseType.EaseOutCirc: f = Interpolate.EaseOutCirc; break; case EaseType.EaseInOutCirc: f = Interpolate.EaseInOutCirc; break; } return f; } /** * Returns sequence generator from the first node to the last node over * duration time using the points in-between the first and last node * as control points of a bezier curve used to generate the interpolated points * in the sequence. If there are no control points (ie. only two nodes, first * and last) then this behaves exactly the same as NewEase(). In other words * a zero-degree bezier spline curve is just the easing method. The sequence * is generated as it is accessed using the Time.deltaTime to calculate the * portion of duration that has elapsed. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewBezier<Transform>(ease, nodes, TransformDotPosition, duration, timer); } /** * Instead of interpolating based on time, generate n interpolated points * (slices) between the first and last node. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Transform>(ease, nodes, TransformDotPosition, slices + 1, counter); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, float duration) { IEnumerable<float> timer = NewTimer(duration); return NewBezier<Vector3>(ease, points, Identity, duration, timer); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Vector3>(ease, points, Identity, slices + 1, counter); } /** * Generic bezier spline sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerable<Vector3> NewBezier<T>(Function ease, IList nodes, ToVector3<T> toVector3, float maxStep, IEnumerable<float> steps) { // need at least two nodes to spline between if (nodes.Count >= 2) { // copy nodes array since Bezier is destructive Vector3[] points = new Vector3[nodes.Count]; foreach (float step in steps) { // re-initialize copy before each destructive call to Bezier for (int i = 0; i < nodes.Count; i++) { points[i] = toVector3((T)nodes[i]); } yield return Bezier(ease, points, step, maxStep); // make sure last value is always generated } } } /** * A Vector3 n-degree bezier spline. * * WARNING: The points array is modified by Bezier. See NewBezier() for a * safe and user friendly alternative. * * You can pass zero control points, just the start and end points, for just * plain easing. In other words a zero-degree bezier spline curve is just the * easing method. * * @param points start point, n control points, end point */ static Vector3 Bezier(Function ease, Vector3[] points, float elapsedTime, float duration) { // Reference: http://ibiblio.org/e-notes/Splines/Bezier.htm // Interpolate the n starting points to generate the next j = (n - 1) points, // then interpolate those n - 1 points to generate the next n - 2 points, // continue this until we have generated the last point (n - (n - 1)), j = 1. // We store the next set of output points in the same array as the // input points used to generate them. This works because we store the // result in the slot of the input point that is no longer used for this // iteration. for (int j = points.Length - 1; j > 0; j--) { for (int i = 0; i < j; i++) { points[i].x = ease(points[i].x, points[i + 1].x - points[i].x, elapsedTime, duration); points[i].y = ease(points[i].y, points[i + 1].y - points[i].y, elapsedTime, duration); points[i].z = ease(points[i].z, points[i + 1].z - points[i].z, elapsedTime, duration); } } return points[0]; } /** * Returns sequence generator from the first node, through each control point, * and to the last node. N points are generated between each node (slices) * using Catmull-Rom. */ public static IEnumerable<Vector3> NewCatmullRom(Transform[] nodes, int slices, bool loop) { return NewCatmullRom<Transform>(nodes, TransformDotPosition, slices, loop); } /** * A Vector3[] variation of the Transform[] NewCatmullRom() function. * Same functionality but using Vector3s to define curve. */ public static IEnumerable<Vector3> NewCatmullRom(Vector3[] points, int slices, bool loop) { return NewCatmullRom<Vector3>(points, Identity, slices, loop); } /** * Generic catmull-rom spline sequence generator used to implement the * Vector3[] and Transform[] variants. Normally you would not use this * function directly. */ static IEnumerable<Vector3> NewCatmullRom<T>(IList nodes, ToVector3<T> toVector3, int slices, bool loop) { // need at least two nodes to spline between if (nodes.Count >= 2) { // yield the first point explicitly, if looping the first point // will be generated again in the step for loop when interpolating // from last point back to the first point yield return toVector3((T)nodes[0]); int last = nodes.Count - 1; for (int current = 0; loop || current < last; current++) { // wrap around when looping if (loop && current > last) { current = 0; } // handle edge cases for looping and non-looping scenarios // when looping we wrap around, when not looping use start for previous // and end for next when you at the ends of the nodes array int previous = (current == 0) ? ((loop) ? last : current) : current - 1; int start = current; int end = (current == last) ? ((loop) ? 0 : current) : current + 1; int next = (end == last) ? ((loop) ? 0 : end) : end + 1; // adding one guarantees yielding at least the end point int stepCount = slices + 1; for (int step = 1; step <= stepCount; step++) { yield return CatmullRom(toVector3((T)nodes[previous]), toVector3((T)nodes[start]), toVector3((T)nodes[end]), toVector3((T)nodes[next]), step, stepCount); } } } } // public static Vector3 GetCatmullRomPoint(IEnumerable<Vector3> catmullRom, float point) // { //// CatmullRom( // // Find the points involved // int prevIndex, nextIndex; // // Vector3[] catmullArray = catmullRom.ToArray(); // prevIndex = Mathf.FloorToInt(catmullArray.Length * point); // nextIndex = Mathf.CeilToInt(catmullArray.Length * point); // // return CatmullRom(catmullArray[prevIndex], catmullArray[0], // catmullArray[catmullArray.Length-1], catmullArray[nextIndex], // } /** * A Vector3 Catmull-Rom spline. Catmull-Rom splines are similar to bezier * splines but have the useful property that the generated curve will go * through each of the control points. * * NOTE: The NewCatmullRom() functions are an easier to use alternative to this * raw Catmull-Rom implementation. * * @param previous the point just before the start point or the start point * itself if no previous point is available * @param start generated when elapsedTime == 0 * @param end generated when elapsedTime >= duration * @param next the point just after the end point or the end point itself if no * next point is available */ static Vector3 CatmullRom(Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime, float duration) { // References used: // p.266 GemsV1 // // tension is often set to 0.5 but you can use any reasonable value: // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf // // bias and tension controls: // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/ float percentComplete = elapsedTime / duration; float percentCompleteSquared = percentComplete * percentComplete; float percentCompleteCubed = percentCompleteSquared * percentComplete; return previous * (-0.5f * percentCompleteCubed + percentCompleteSquared - 0.5f * percentComplete) + start * ( 1.5f * percentCompleteCubed + -2.5f * percentCompleteSquared + 1.0f) + end * (-1.5f * percentCompleteCubed + 2.0f * percentCompleteSquared + 0.5f * percentComplete) + next * ( 0.5f * percentCompleteCubed - 0.5f * percentCompleteSquared); } /** * Linear interpolation (same as Mathf.Lerp) */ static float Linear(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (elapsedTime / duration) + start; } /** * quadratic easing in - accelerating from zero velocity */ static float EaseInQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime + start; } /** * quadratic easing out - decelerating to zero velocity */ static float EaseOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * elapsedTime * (elapsedTime - 2) + start; } /** * quadratic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime + start; elapsedTime--; return -distance / 2 * (elapsedTime * (elapsedTime - 2) - 1) + start; } /** * cubic easing in - accelerating from zero velocity */ static float EaseInCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime + start; } /** * cubic easing out - decelerating to zero velocity */ static float EaseOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * cubic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * quartic easing in - accelerating from zero velocity */ static float EaseInQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quartic easing out - decelerating to zero velocity */ static float EaseOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return -distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 1) + start; } /** * quartic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return -distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 2) + start; } /** * quintic easing in - accelerating from zero velocity */ static float EaseInQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quintic easing out - decelerating to zero velocity */ static float EaseOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * quintic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2f); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * sinusoidal easing in - accelerating from zero velocity */ static float EaseInSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance * Mathf.Cos(elapsedTime / duration * (Mathf.PI / 2)) + distance + start; } /** * sinusoidal easing out - decelerating to zero velocity */ static float EaseOutSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Sin(elapsedTime / duration * (Mathf.PI / 2)) + start; } /** * sinusoidal easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance / 2 * (Mathf.Cos(Mathf.PI * elapsedTime / duration) - 1) + start; } /** * exponential easing in - accelerating from zero velocity */ static float EaseInExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Pow(2, 10 * (elapsedTime / duration - 1)) + start; } /** * exponential easing out - decelerating to zero velocity */ static float EaseOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (-Mathf.Pow(2, -10 * elapsedTime / duration) + 1) + start; } /** * exponential easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * Mathf.Pow(2, 10 * (elapsedTime - 1)) + start; elapsedTime--; return distance / 2 * (-Mathf.Pow(2, -10 * elapsedTime) + 2) + start; } /** * circular easing in - accelerating from zero velocity */ static float EaseInCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; } /** * circular easing out - decelerating to zero velocity */ static float EaseOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * Mathf.Sqrt(1 - elapsedTime * elapsedTime) + start; } /** * circular easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return -distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; elapsedTime -= 2; return distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) + 1) + start; } public static Vector3[] NormalizePath(IEnumerable<Vector3> pathSource, int segments) { float distance; return NormalizePath(pathSource, segments, out distance); } public static Vector3[] NormalizePath(IEnumerable<Vector3> pathSource, int segments, out float pathLength) { List<Vector3> originalPath = new List<Vector3>(); // Get the distance of the path and create a list for easy reference float pathDistance = 0; Vector3 lastPoint = Vector3.zero; foreach (Vector3 pathPt in pathSource) { if (lastPoint != Vector3.zero) { pathDistance += (pathPt - lastPoint).magnitude; } originalPath.Add(pathPt); lastPoint = pathPt; } pathLength = pathDistance; float normalDistance = pathDistance / segments; // Construct a new path List<Vector3> newPath = new List<Vector3>(); newPath.Add(originalPath[0]); int pathIndex = 1; lastPoint = originalPath[0]; // Loop through the points of the path while (pathIndex < originalPath.Count) { Vector3 segmentVector = originalPath[pathIndex] - lastPoint; // If distance from last point is less than the // average distance we want, go to the next point if (segmentVector.magnitude < normalDistance) { pathIndex++; } else { // Something went wrong, just return the path if (newPath.Count > segments) { throw new Exception("Could not normalize segment, normal distance was " + normalDistance); } // More than or equals to the next point Vector3 nextPoint = lastPoint + (segmentVector.normalized * normalDistance); // Debug.Log("Segment length is " + (nextPoint - lastPoint).magnitude); newPath.Add(nextPoint); lastPoint = nextPoint; } // If we reach the end but new path is not the expected segment count, add the last path // might have missed it due to floating point errors if (pathIndex == originalPath.Count) { if (newPath.Count < segments) { newPath.Add(originalPath[originalPath.Count-1]); } } } return newPath.ToArray(); } public static Vector3 PointOnNormalizedPath(Vector3[] normalizedPath, float position) { float pos = Mathf.Clamp((position * normalizedPath.Length), 0f, (normalizedPath.Length-1)); int pathIndex = Mathf.FloorToInt(pos); if (pathIndex >= (normalizedPath.Length-1)) return normalizedPath[normalizedPath.Length-1]; float pathFraction = pos - pathIndex; Vector3 pathDirection = (normalizedPath[pathIndex + 1] - normalizedPath[pathIndex]); Vector3 finalPosition = normalizedPath[pathIndex] + (pathDirection * pathFraction); return finalPosition; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Tests { public class YieldAwaitableTests { // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests() { // Test direct usage works even though it's not encouraged { for (int i = 0; i < 2; i++) { SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = i == 0 ? new YieldAwaitable.YieldAwaiter() : new YieldAwaitable().GetAwaiter(); var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, "RunAsyncYieldAwaiterTests > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format("RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } { // Yield when there's a current TaskScheduler Task.Factory.StartNew(() => { try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // Yield when there's a current TaskScheduler and SynchronizationContext.Current is the base SynchronizationContext Task.Factory.StartNew(() => { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } SynchronizationContext.SetSynchronizationContext(null); }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // OnCompleted grabs the current context, not Task.Yield nor GetAwaiter SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var ya = Task.Yield().GetAwaiter(); SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests_Negative() { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); Assert.Throws<ArgumentNullException>(() => { ya.OnCompleted(null); }); SynchronizationContext.SetSynchronizationContext(null); } [Fact] public static async Task AsyncMethod_Yields_ReturnsToDefaultTaskScheduler() { await Task.Yield(); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); } [Fact] public static async Task AsyncMethod_Yields_ReturnsToCorrectTaskScheduler() { QUWITaskScheduler ts = new QUWITaskScheduler(); Assert.NotSame(ts, TaskScheduler.Current); await Task.Factory.StartNew(async delegate { Assert.Same(ts, TaskScheduler.Current); await Task.Yield(); Assert.Same(ts, TaskScheduler.Current); }, CancellationToken.None, TaskCreationOptions.None, ts).Unwrap(); Assert.NotSame(ts, TaskScheduler.Current); } [Fact] public static async Task AsyncMethod_Yields_ReturnsToCorrectSynchronizationContext() { var sc = new ValidateCorrectContextSynchronizationContext (); SynchronizationContext.SetSynchronizationContext(sc); await Task.Yield(); Assert.Equal(1, sc.PostCount); } #region Helper Methods / Classes private class ValidateCorrectContextSynchronizationContext : SynchronizationContext { [ThreadStatic] internal static bool t_isPostedInContext; internal int PostCount; internal int SendCount; public override void Post(SendOrPostCallback d, object state) { Interlocked.Increment(ref PostCount); Task.Run(() => { t_isPostedInContext = true; d(state); t_isPostedInContext = false; }); } public override void Send(SendOrPostCallback d, object state) { Interlocked.Increment(ref SendCount); d(state); } } /// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary> private class QUWITaskScheduler : TaskScheduler { private int _queueTaskCount; private int _tryExecuteTaskInlineCount; public int QueueTaskCount { get { return _queueTaskCount; } } public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } } protected override IEnumerable<Task> GetScheduledTasks() { return null; } protected override void QueueTask(Task task) { Interlocked.Increment(ref _queueTaskCount); Task.Run(() => TryExecuteTask(task)); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Interlocked.Increment(ref _tryExecuteTaskInlineCount); return TryExecuteTask(task); } } #endregion } }
using System; using k8s.Models; using Xunit; using static k8s.Models.ResourceQuantity.SuffixFormat; namespace k8s.Tests { public class QuantityValueTests { [Fact] public void Deserialize() { { var q = KubernetesJson.Deserialize<ResourceQuantity>("\"12k\""); Assert.Equal(new ResourceQuantity(12000, 0, DecimalSI), q); } } [Fact] public void Parse() { foreach (var (input, expect) in new[] { ("0", new ResourceQuantity(0, 0, DecimalSI)), ("0n", new ResourceQuantity(0, 0, DecimalSI)), ("0u", new ResourceQuantity(0, 0, DecimalSI)), ("0m", new ResourceQuantity(0, 0, DecimalSI)), ("0Ki", new ResourceQuantity(0, 0, BinarySI)), ("0k", new ResourceQuantity(0, 0, DecimalSI)), ("0Mi", new ResourceQuantity(0, 0, BinarySI)), ("0M", new ResourceQuantity(0, 0, DecimalSI)), ("0Gi", new ResourceQuantity(0, 0, BinarySI)), ("0G", new ResourceQuantity(0, 0, DecimalSI)), ("0Ti", new ResourceQuantity(0, 0, BinarySI)), ("0T", new ResourceQuantity(0, 0, DecimalSI)), // Quantity less numbers are allowed ("1", new ResourceQuantity(1, 0, DecimalSI)), // Binary suffixes ("1Ki", new ResourceQuantity(1024, 0, BinarySI)), ("8Ki", new ResourceQuantity(8 * 1024, 0, BinarySI)), ("7Mi", new ResourceQuantity(7 * 1024 * 1024, 0, BinarySI)), ("6Gi", new ResourceQuantity(6L * 1024 * 1024 * 1024, 0, BinarySI)), ("5Ti", new ResourceQuantity(5L * 1024 * 1024 * 1024 * 1024, 0, BinarySI)), ("4Pi", new ResourceQuantity(4L * 1024 * 1024 * 1024 * 1024 * 1024, 0, BinarySI)), ("3Ei", new ResourceQuantity(3L * 1024 * 1024 * 1024 * 1024 * 1024 * 1024, 0, BinarySI)), ("10Ti", new ResourceQuantity(10L * 1024 * 1024 * 1024 * 1024, 0, BinarySI)), ("100Ti", new ResourceQuantity(100L * 1024 * 1024 * 1024 * 1024, 0, BinarySI)), // Decimal suffixes ("5n", new ResourceQuantity(5, -9, DecimalSI)), ("4u", new ResourceQuantity(4, -6, DecimalSI)), ("3m", new ResourceQuantity(3, -3, DecimalSI)), ("9", new ResourceQuantity(9, 0, DecimalSI)), ("8k", new ResourceQuantity(8, 3, DecimalSI)), ("50k", new ResourceQuantity(5, 4, DecimalSI)), ("7M", new ResourceQuantity(7, 6, DecimalSI)), ("6G", new ResourceQuantity(6, 9, DecimalSI)), ("5T", new ResourceQuantity(5, 12, DecimalSI)), ("40T", new ResourceQuantity(4, 13, DecimalSI)), ("300T", new ResourceQuantity(3, 14, DecimalSI)), ("2P", new ResourceQuantity(2, 15, DecimalSI)), ("1E", new ResourceQuantity(1, 18, DecimalSI)), // Decimal exponents ("1E-3", new ResourceQuantity(1, -3, DecimalExponent)), ("1e3", new ResourceQuantity(1, 3, DecimalExponent)), ("1E6", new ResourceQuantity(1, 6, DecimalExponent)), ("1e9", new ResourceQuantity(1, 9, DecimalExponent)), ("1E12", new ResourceQuantity(1, 12, DecimalExponent)), ("1e15", new ResourceQuantity(1, 15, DecimalExponent)), ("1E18", new ResourceQuantity(1, 18, DecimalExponent)), // Nonstandard but still parsable ("1e14", new ResourceQuantity(1, 14, DecimalExponent)), ("1e13", new ResourceQuantity(1, 13, DecimalExponent)), ("1e3", new ResourceQuantity(1, 3, DecimalExponent)), ("100.035k", new ResourceQuantity(100035, 0, DecimalSI)), // Things that look like floating point ("0.001", new ResourceQuantity(1, -3, DecimalSI)), ("0.0005k", new ResourceQuantity(5, -1, DecimalSI)), ("0.005", new ResourceQuantity(5, -3, DecimalSI)), ("0.05", new ResourceQuantity(5, -2, DecimalSI)), ("0.5", new ResourceQuantity(5, -1, DecimalSI)), ("0.00050k", new ResourceQuantity(5, -1, DecimalSI)), ("0.00500", new ResourceQuantity(5, -3, DecimalSI)), ("0.05000", new ResourceQuantity(5, -2, DecimalSI)), ("0.50000", new ResourceQuantity(5, -1, DecimalSI)), ("0.5e0", new ResourceQuantity(5, -1, DecimalExponent)), ("0.5e-1", new ResourceQuantity(5, -2, DecimalExponent)), ("0.5e-2", new ResourceQuantity(5, -3, DecimalExponent)), ("0.5e0", new ResourceQuantity(5, -1, DecimalExponent)), ("10.035M", new ResourceQuantity(10035, 3, DecimalSI)), ("1.2e3", new ResourceQuantity(12, 2, DecimalExponent)), ("1.3E+6", new ResourceQuantity(13, 5, DecimalExponent)), ("1.40e9", new ResourceQuantity(14, 8, DecimalExponent)), ("1.53E12", new ResourceQuantity(153, 10, DecimalExponent)), ("1.6e15", new ResourceQuantity(16, 14, DecimalExponent)), ("1.7E18", new ResourceQuantity(17, 17, DecimalExponent)), ("9.01", new ResourceQuantity(901, -2, DecimalSI)), ("8.1k", new ResourceQuantity(81, 2, DecimalSI)), ("7.123456M", new ResourceQuantity(7123456, 0, DecimalSI)), ("6.987654321G", new ResourceQuantity(6987654321, 0, DecimalSI)), ("5.444T", new ResourceQuantity(5444, 9, DecimalSI)), ("40.1T", new ResourceQuantity(401, 11, DecimalSI)), ("300.2T", new ResourceQuantity(3002, 11, DecimalSI)), ("2.5P", new ResourceQuantity(25, 14, DecimalSI)), ("1.01E", new ResourceQuantity(101, 16, DecimalSI)), // Things that saturate/round ("3.001n", new ResourceQuantity(4, -9, DecimalSI)), ("1.1E-9", new ResourceQuantity(2, -9, DecimalExponent)), ("0.0000000001", new ResourceQuantity(1, -9, DecimalSI)), ("0.0000000005", new ResourceQuantity(1, -9, DecimalSI)), ("0.00000000050", new ResourceQuantity(1, -9, DecimalSI)), ("0.5e-9", new ResourceQuantity(1, -9, DecimalExponent)), ("0.9n", new ResourceQuantity(1, -9, DecimalSI)), ("0.00000012345", new ResourceQuantity(124, -9, DecimalSI)), ("0.00000012354", new ResourceQuantity(124, -9, DecimalSI)), ("9Ei", new ResourceQuantity(ResourceQuantity.MaxAllowed, 0, BinarySI)), ("9223372036854775807Ki", new ResourceQuantity(ResourceQuantity.MaxAllowed, 0, BinarySI)), ("12E", new ResourceQuantity(12, 18, DecimalSI)), // We'll accept fractional binary stuff, too. ("100.035Ki", new ResourceQuantity(10243584, -2, BinarySI)), ("0.5Mi", new ResourceQuantity(.5m * 1024 * 1024, 0, BinarySI)), ("0.05Gi", new ResourceQuantity(536870912, -1, BinarySI)), ("0.025Ti", new ResourceQuantity(274877906944, -1, BinarySI)), // Things written by trolls ("0.000000000001Ki", new ResourceQuantity(2, -9, DecimalSI)), // rounds up, changes format (".001", new ResourceQuantity(1, -3, DecimalSI)), (".0001k", new ResourceQuantity(100, -3, DecimalSI)), ("1.", new ResourceQuantity(1, 0, DecimalSI)), ("1.G", new ResourceQuantity(1, 9, DecimalSI)), }) { Assert.Equal(expect.ToString(), new ResourceQuantity(input).ToString()); } foreach (var s in new[] { "1.1.M", "1+1.0M", "0.1mi", "0.1am", "aoeu", ".5i", "1i", "-3.01i", "-3.01e-", // TODO support trailing whitespace is forbidden // " 1", // "1 " }) { Assert.ThrowsAny<Exception>(() => { new ResourceQuantity(s); }); } } [Fact] public void ConstructorTest() { Assert.Throws<FormatException>(() => new ResourceQuantity(string.Empty)); } [Fact] public void QuantityString() { foreach (var (input, expect, alternate) in new[] { (new ResourceQuantity(1024 * 1024 * 1024, 0, BinarySI), "1Gi", "1024Mi"), (new ResourceQuantity(300 * 1024 * 1024, 0, BinarySI), "300Mi", "307200Ki"), (new ResourceQuantity(6 * 1024, 0, BinarySI), "6Ki", ""), (new ResourceQuantity(1001 * 1024 * 1024 * 1024L, 0, BinarySI), "1001Gi", "1025024Mi"), (new ResourceQuantity(1024 * 1024 * 1024 * 1024L, 0, BinarySI), "1Ti", "1024Gi"), (new ResourceQuantity(5, 0, BinarySI), "5", "5000m"), (new ResourceQuantity(500, -3, BinarySI), "500m", "0.5"), (new ResourceQuantity(1, 9, DecimalSI), "1G", "1000M"), (new ResourceQuantity(1000, 6, DecimalSI), "1G", "0.001T"), (new ResourceQuantity(1000000, 3, DecimalSI), "1G", ""), (new ResourceQuantity(1000000000, 0, DecimalSI), "1G", ""), (new ResourceQuantity(1, -3, DecimalSI), "1m", "1000u"), (new ResourceQuantity(80, -3, DecimalSI), "80m", ""), (new ResourceQuantity(1080, -3, DecimalSI), "1080m", "1.08"), (new ResourceQuantity(108, -2, DecimalSI), "1080m", "1080000000n"), (new ResourceQuantity(10800, -4, DecimalSI), "1080m", ""), (new ResourceQuantity(300, 6, DecimalSI), "300M", ""), (new ResourceQuantity(1, 12, DecimalSI), "1T", ""), (new ResourceQuantity(1234567, 6, DecimalSI), "1234567M", ""), (new ResourceQuantity(1234567, -3, BinarySI), "1234567m", ""), (new ResourceQuantity(3, 3, DecimalSI), "3k", ""), (new ResourceQuantity(1025, 0, BinarySI), "1025", ""), (new ResourceQuantity(0, 0, DecimalSI), "0", ""), (new ResourceQuantity(0, 0, BinarySI), "0", ""), (new ResourceQuantity(1, 9, DecimalExponent), "1e9", ".001e12"), (new ResourceQuantity(1, -3, DecimalExponent), "1e-3", "0.001e0"), (new ResourceQuantity(1, -9, DecimalExponent), "1e-9", "1000e-12"), (new ResourceQuantity(80, -3, DecimalExponent), "80e-3", ""), (new ResourceQuantity(300, 6, DecimalExponent), "300e6", ""), (new ResourceQuantity(1, 12, DecimalExponent), "1e12", ""), (new ResourceQuantity(1, 3, DecimalExponent), "1e3", ""), (new ResourceQuantity(3, 3, DecimalExponent), "3e3", ""), (new ResourceQuantity(3, 3, DecimalSI), "3k", ""), (new ResourceQuantity(0, 0, DecimalExponent), "0", "00"), (new ResourceQuantity(1, -9, DecimalSI), "1n", ""), (new ResourceQuantity(80, -9, DecimalSI), "80n", ""), (new ResourceQuantity(1080, -9, DecimalSI), "1080n", ""), (new ResourceQuantity(108, -8, DecimalSI), "1080n", ""), (new ResourceQuantity(10800, -10, DecimalSI), "1080n", ""), (new ResourceQuantity(1, -6, DecimalSI), "1u", ""), (new ResourceQuantity(80, -6, DecimalSI), "80u", ""), (new ResourceQuantity(1080, -6, DecimalSI), "1080u", ""), }) { Assert.Equal(expect, input.ToString()); Assert.Equal(expect, new ResourceQuantity(expect).ToString()); if (string.IsNullOrEmpty(alternate)) { continue; } Assert.Equal(expect, new ResourceQuantity(alternate).ToString()); } } [Fact] public void Serialize() { { ResourceQuantity quantity = 12000; Assert.Equal("\"12e3\"", KubernetesJson.Serialize(quantity)); } } [Fact] public void DeserializeYaml() { var value = Yaml.LoadFromString<ResourceQuantity>("\"1\""); Assert.Equal(new ResourceQuantity(1, 0, DecimalSI), value); } [Fact] public void SerializeYaml() { var value = Yaml.SaveToString(new ResourceQuantity(1, -1, DecimalSI)); Assert.Equal("100m", value); } } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; namespace Drove.Tests { public class TestReflectObject { public Guid Id; public string Code; } [TestClass] public class TestRelect { public TestRelect() { } private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } // Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void Initialize(TestContext testContext) { } // Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void Cleanup() { } // Use TestInitialize to run code before running each test [TestInitialize()] public void TestInitialize() { } // Use TestCleanup to run code after each test has run [TestCleanup()] public void TestCleanup() { } [TestMethod] public void TestReflect_GetProperties() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; PropertyInfo[] props = Reflect.GetProperties(obj); Assert.IsNotNull(props); Assert.IsTrue(props.Length > 0); } [TestMethod] public void TestReflect_CopyTo() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj2 = obj.CopyTo<TestReflectObject>(obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); } [TestMethod] public void TestReflect_Clone() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj2 = Reflect.Clone<TestReflectObject>(obj, obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); } [TestMethod] public void TestReflect_CopyToRef() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj.CopyTo<TestReflectObject>(ref obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); } [TestMethod] public void TestReflect_CloneRef() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; Reflect.Clone<TestReflectObject>(obj, ref obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); } [TestMethod] public void TestReflect_ObjectSyncFieldValues() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj2.Status = "obj2 status"; obj2 = Reflect.ObjectSyncFieldValues<TestReflectObject>(obj, obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); Assert.AreNotEqual<string>(obj.Status, obj2.Status); } [TestMethod] public void TestReflect_ObjectSyncFieldValuesRef() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj2.Status = "obj2 status"; Reflect.ObjectSyncFieldValues<TestReflectObject>(obj, ref obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); Assert.AreNotEqual<string>(obj.Status, obj2.Status); } [TestMethod] public void TestReflect_ObjectSyncFieldValuesSerialize() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; TestReflectObject obj2 = new TestReflectObject(); obj2.Code = "Hello Again"; obj2.Status = "obj2 status"; Reflect.ObjectSyncFieldValuesSerialize<TestReflectObject>(obj, ref obj2); Assert.AreEqual<string>(obj.Code, obj2.Code); Assert.AreEqual<Guid>(obj.Id, obj2.Id); Assert.AreNotEqual<string>(obj.Status, obj2.Status); } [TestMethod] public void TestReflect_GetFieldValue() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; string code = Reflect.GetFieldValue<string>(obj, "Code"); Assert.AreEqual<string>(obj.Code, code); } [TestMethod] public void TestReflect_SetFieldValue() { TestReflectObject obj = new TestReflectObject(); obj.Code = "Hello"; Reflect.SetFieldValue(obj, "Code", "Hello Again"); Assert.AreEqual<string>(obj.Code, "Hello Again"); } } }
// /* // * Copyright (c) 2016, Alachisoft. All Rights Reserved. // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ using System; using System.Text; using System.Reflection; using System.IO; /// <summary> /// The namespace provides the CompactReader and CompactWriter that are required /// while implementing the Serialize and Deserialize methods of ICompactSerializable interface. /// </summary> #if JAVA namespace Alachisoft.TayzGrid.Runtime.Serialization.IO #else namespace Alachisoft.NosDB.Common.Serialization.IO #endif { /// <summary> /// CompactReader is the base class for CompactBinaryReader. /// </summary> /// <remark> /// This Feature is Not Available in Express /// </remark> //[CLSCompliant(false)] public abstract class CompactReader : IDisposable { /// <summary> /// Reads an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> /// <returns>object read from the stream</returns> public abstract object ReadObject(); public abstract T ReadObjectAs<T>(); public abstract Stream BaseStream { get; } /// <summary> /// Skips an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> public abstract void SkipObject(); public abstract void SkipObjectAs<T>(); #region / CompactBinaryReader.ReadXXX / /// <summary> /// Reads an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract bool ReadBoolean(); /// <summary> /// Reads an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract byte ReadByte(); /// <summary> /// Reads an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> /// <returns>object read from the stream</returns> public abstract byte[] ReadBytes(int count); /// <summary> /// Reads an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract char ReadChar(); /// <summary> /// Reads an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract char[] ReadChars(int count); /// <summary> /// Reads an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract decimal ReadDecimal(); /// <summary> /// Reads an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract float ReadSingle(); /// <summary> /// Reads an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract double ReadDouble(); /// <summary> /// Reads an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract short ReadInt16(); /// <summary> /// Reads an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract int ReadInt32(); /// <summary> /// Reads an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract long ReadInt64(); /// <summary> /// Reads an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract string ReadString(); /// <summary> /// Reads an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract DateTime ReadDateTime(); /// <summary> /// Reads an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract Guid ReadGuid(); /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of buffer read</returns> public abstract int Read(byte[] buffer, int index, int count); /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of chars read</returns> public abstract int Read(char[] buffer, int index, int count); /// <summary> /// Reads an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual sbyte ReadSByte() { return 0; } /// <summary> /// Reads an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual ushort ReadUInt16() { return 0; } /// <summary> /// Reads an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual uint ReadUInt32() { return 0; } /// <summary> /// Reads an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual ulong ReadUInt64() { return 0; } #endregion #region / CompactBinaryReader.SkipXXX / /// <summary> /// Skips an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipBoolean(); /// <summary> /// Skips an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipByte(); /// <summary> /// Skips an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> public abstract void SkipBytes(int count); /// <summary> /// Skips an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipChar(); /// <summary> /// Skips an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipChars(int count); /// <summary> /// Skips an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDecimal(); /// <summary> /// Skips an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipSingle(); /// <summary> /// Skips an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDouble(); /// <summary> /// Skips an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt16(); /// <summary> /// Skips an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt32(); /// <summary> /// Skips an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt64(); /// <summary> /// Skips an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipString(); /// <summary> /// Skips an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDateTime(); /// <summary> /// Skips an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipGuid(); /// <summary> /// Skips an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipSByte() { } /// <summary> /// Skips an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt16() { } /// <summary> /// Skips an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt32() { } /// <summary> /// Skips an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt64() { } #endregion public virtual void Dispose() {} } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Xml; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptSerializer { public static string Serialize(ScriptInstance instance) { bool running = instance.Running; XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ScriptState", ""); xmldoc.AppendChild(rootElement); XmlElement state = xmldoc.CreateElement("", "State", ""); state.AppendChild(xmldoc.CreateTextNode(instance.State)); rootElement.AppendChild(state); XmlElement run = xmldoc.CreateElement("", "Running", ""); run.AppendChild(xmldoc.CreateTextNode( running.ToString())); rootElement.AppendChild(run); Dictionary<string, Object> vars = instance.GetVars(); XmlElement variables = xmldoc.CreateElement("", "Variables", ""); foreach (KeyValuePair<string, Object> var in vars) WriteTypedValue(xmldoc, variables, "Variable", var.Key, var.Value); rootElement.AppendChild(variables); XmlElement queue = xmldoc.CreateElement("", "Queue", ""); long count = instance.EventsQueued; while (count > 0) { EventParams ep; try { ep = (EventParams)instance.DequeueEvent(); } catch(InvalidOperationException) { break; } instance.EnqueueEvent(ep); count--; XmlElement item = xmldoc.CreateElement("", "Item", ""); XmlAttribute itemEvent = xmldoc.CreateAttribute("", "event", ""); itemEvent.Value = ep.EventName; item.Attributes.Append(itemEvent); XmlElement parms = xmldoc.CreateElement("", "Params", ""); foreach (Object o in ep.Params) WriteTypedValue(xmldoc, parms, "Param", String.Empty, o); item.AppendChild(parms); XmlElement detect = xmldoc.CreateElement("", "Detected", ""); foreach (DetectParams det in ep.DetectParams) { XmlElement objectElem = xmldoc.CreateElement("", "Object", ""); XmlAttribute pos = xmldoc.CreateAttribute("", "pos", ""); pos.Value = det.OffsetPos.ToString(); objectElem.Attributes.Append(pos); XmlAttribute d_linkNum = xmldoc.CreateAttribute("", "linkNum", ""); d_linkNum.Value = det.LinkNum.ToString(); objectElem.Attributes.Append(d_linkNum); XmlAttribute d_group = xmldoc.CreateAttribute("", "group", ""); d_group.Value = det.Group.ToString(); objectElem.Attributes.Append(d_group); XmlAttribute d_name = xmldoc.CreateAttribute("", "name", ""); d_name.Value = det.Name.ToString(); objectElem.Attributes.Append(d_name); XmlAttribute d_owner = xmldoc.CreateAttribute("", "owner", ""); d_owner.Value = det.Owner.ToString(); objectElem.Attributes.Append(d_owner); XmlAttribute d_position = xmldoc.CreateAttribute("", "position", ""); d_position.Value = det.Position.ToString(); objectElem.Attributes.Append(d_position); XmlAttribute d_rotation = xmldoc.CreateAttribute("", "rotation", ""); d_rotation.Value = det.Rotation.ToString(); objectElem.Attributes.Append(d_rotation); XmlAttribute d_type = xmldoc.CreateAttribute("", "type", ""); d_type.Value = det.Type.ToString(); objectElem.Attributes.Append(d_type); XmlAttribute d_velocity = xmldoc.CreateAttribute("", "velocity", ""); d_velocity.Value = det.Velocity.ToString(); objectElem.Attributes.Append(d_velocity); objectElem.AppendChild( xmldoc.CreateTextNode(det.Key.ToString())); detect.AppendChild(objectElem); } item.AppendChild(detect); queue.AppendChild(item); } rootElement.AppendChild(queue); XmlNode plugins = xmldoc.CreateElement("", "Plugins", ""); DumpList(xmldoc, plugins, new LSL_Types.list(instance.PluginData)); rootElement.AppendChild(plugins); if (instance.ScriptTask != null) { if (instance.ScriptTask.PermsMask != 0 && instance.ScriptTask.PermsGranter != UUID.Zero) { XmlNode permissions = xmldoc.CreateElement("", "Permissions", ""); XmlAttribute granter = xmldoc.CreateAttribute("", "granter", ""); granter.Value = instance.ScriptTask.PermsGranter.ToString(); permissions.Attributes.Append(granter); XmlAttribute mask = xmldoc.CreateAttribute("", "mask", ""); mask.Value = instance.ScriptTask.PermsMask.ToString(); permissions.Attributes.Append(mask); rootElement.AppendChild(permissions); } } if (instance.MinEventDelay > 0.0) { XmlElement eventDelay = xmldoc.CreateElement("", "MinEventDelay", ""); eventDelay.AppendChild(xmldoc.CreateTextNode(instance.MinEventDelay.ToString())); rootElement.AppendChild(eventDelay); } return xmldoc.InnerXml; } public static void Deserialize(string xml, ScriptInstance instance) { XmlDocument doc = new XmlDocument(); Dictionary<string, object> vars = instance.GetVars(); instance.PluginData = new Object[0]; // Avoid removal of whitepace from LSL string vars doc.PreserveWhitespace = true; doc.LoadXml(xml); XmlNodeList rootL = doc.GetElementsByTagName("ScriptState"); if (rootL.Count != 1) { return; } XmlNode rootNode = rootL[0]; if (rootNode != null) { object varValue; XmlNodeList partL = rootNode.ChildNodes; foreach (XmlNode part in partL) { switch (part.Name) { case "State": instance.State=part.InnerText; break; case "Running": instance.Running=bool.Parse(part.InnerText); break; case "Variables": XmlNodeList varL = part.ChildNodes; foreach (XmlNode var in varL) { string varName; varValue=ReadTypedValue(var, out varName); if (vars.ContainsKey(varName)) { vars[varName] = varValue; } } instance.SetVars(vars); break; case "Queue": XmlNodeList itemL = part.ChildNodes; foreach (XmlNode item in itemL) { List<Object> parms = new List<Object>(); List<DetectParams> detected = new List<DetectParams>(); string eventName = item.Attributes.GetNamedItem("event").Value; XmlNodeList eventL = item.ChildNodes; foreach (XmlNode evt in eventL) { switch (evt.Name) { case "Params": XmlNodeList prms = evt.ChildNodes; foreach (XmlNode pm in prms) parms.Add(ReadTypedValue(pm)); break; case "Detected": XmlNodeList detL = evt.ChildNodes; foreach (XmlNode det in detL) { string vect = det.Attributes.GetNamedItem( "pos").Value; LSL_Types.Vector3 v = new LSL_Types.Vector3(vect); int d_linkNum=0; UUID d_group = UUID.Zero; string d_name = String.Empty; UUID d_owner = UUID.Zero; LSL_Types.Vector3 d_position = new LSL_Types.Vector3(); LSL_Types.Quaternion d_rotation = new LSL_Types.Quaternion(); int d_type = 0; LSL_Types.Vector3 d_velocity = new LSL_Types.Vector3(); try { string tmp; tmp = det.Attributes.GetNamedItem( "linkNum").Value; int.TryParse(tmp, out d_linkNum); tmp = det.Attributes.GetNamedItem( "group").Value; UUID.TryParse(tmp, out d_group); d_name = det.Attributes.GetNamedItem( "name").Value; tmp = det.Attributes.GetNamedItem( "owner").Value; UUID.TryParse(tmp, out d_owner); tmp = det.Attributes.GetNamedItem( "position").Value; d_position = new LSL_Types.Vector3(tmp); tmp = det.Attributes.GetNamedItem( "rotation").Value; d_rotation = new LSL_Types.Quaternion(tmp); tmp = det.Attributes.GetNamedItem( "type").Value; int.TryParse(tmp, out d_type); tmp = det.Attributes.GetNamedItem( "velocity").Value; d_velocity = new LSL_Types.Vector3(tmp); } catch (Exception) // Old version XML { } UUID uuid = new UUID(); UUID.TryParse(det.InnerText, out uuid); DetectParams d = new DetectParams(); d.Key = uuid; d.OffsetPos = v; d.LinkNum = d_linkNum; d.Group = d_group; d.Name = d_name; d.Owner = d_owner; d.Position = d_position; d.Rotation = d_rotation; d.Type = d_type; d.Velocity = d_velocity; detected.Add(d); } break; } } EventParams ep = new EventParams( eventName, parms.ToArray(), detected.ToArray()); instance.EnqueueEvent(ep); } break; case "Plugins": instance.PluginData = ReadList(part).Data; break; case "Permissions": string tmpPerm; int mask = 0; tmpPerm = part.Attributes.GetNamedItem("mask").Value; if (tmpPerm != null) { int.TryParse(tmpPerm, out mask); if (mask != 0) { tmpPerm = part.Attributes.GetNamedItem("granter").Value; if (tmpPerm != null) { UUID granter = new UUID(); UUID.TryParse(tmpPerm, out granter); if (granter != UUID.Zero) { instance.ScriptTask.PermsMask = mask; instance.ScriptTask.PermsGranter = granter; } } } } break; case "MinEventDelay": double minEventDelay = 0.0; double.TryParse(part.InnerText, NumberStyles.Float, Culture.NumberFormatInfo, out minEventDelay); instance.MinEventDelay = minEventDelay; break; } } } } private static void DumpList(XmlDocument doc, XmlNode parent, LSL_Types.list l) { foreach (Object o in l.Data) WriteTypedValue(doc, parent, "ListItem", "", o); } private static LSL_Types.list ReadList(XmlNode parent) { List<Object> olist = new List<Object>(); XmlNodeList itemL = parent.ChildNodes; foreach (XmlNode item in itemL) olist.Add(ReadTypedValue(item)); return new LSL_Types.list(olist.ToArray()); } private static void WriteTypedValue(XmlDocument doc, XmlNode parent, string tag, string name, object value) { Type t=value.GetType(); XmlAttribute typ = doc.CreateAttribute("", "type", ""); XmlNode n = doc.CreateElement("", tag, ""); if (value is LSL_Types.list) { typ.Value = "list"; n.Attributes.Append(typ); DumpList(doc, n, (LSL_Types.list) value); if (name != String.Empty) { XmlAttribute nam = doc.CreateAttribute("", "name", ""); nam.Value = name; n.Attributes.Append(nam); } parent.AppendChild(n); return; } n.AppendChild(doc.CreateTextNode(value.ToString())); typ.Value = t.ToString(); n.Attributes.Append(typ); if (name != String.Empty) { XmlAttribute nam = doc.CreateAttribute("", "name", ""); nam.Value = name; n.Attributes.Append(nam); } parent.AppendChild(n); } private static object ReadTypedValue(XmlNode tag, out string name) { name = tag.Attributes.GetNamedItem("name").Value; return ReadTypedValue(tag); } private static object ReadTypedValue(XmlNode tag) { Object varValue; string assembly; string itemType = tag.Attributes.GetNamedItem("type").Value; if (itemType == "list") return ReadList(tag); if (itemType == "OpenMetaverse.UUID") { UUID val = new UUID(); UUID.TryParse(tag.InnerText, out val); return val; } Type itemT = Type.GetType(itemType); if (itemT == null) { Object[] args = new Object[] { tag.InnerText }; assembly = itemType+", OpenSim.Region.ScriptEngine.Shared"; itemT = Type.GetType(assembly); if (itemT == null) return null; varValue = Activator.CreateInstance(itemT, args); if (varValue == null) return null; } else { varValue = Convert.ChangeType(tag.InnerText, itemT); } return varValue; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Roslyn.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostTests : AbstractInteractiveHostTests { #region Utils private SynchronizedStringWriter _synchronizedOutput; private SynchronizedStringWriter _synchronizedErrorOutput; private int[] _outputReadPosition = new int[] { 0, 0 }; private readonly InteractiveHost Host; private static readonly string s_fxDir = FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()); private static readonly string s_homeDir = FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); public InteractiveHostTests() { Host = new InteractiveHost(typeof(CSharpReplServiceProvider), GetInteractiveHostPath(), ".", millisecondsTimeout: -1); RedirectOutput(); Host.ResetAsync(new InteractiveHostOptions(initializationFile: null, culture: CultureInfo.InvariantCulture)).Wait(); var remoteService = Host.TryGetService(); Assert.NotNull(remoteService); remoteService.SetTestObjectFormattingOptions(); Host.SetPathsAsync(new[] { s_fxDir }, new[] { s_homeDir }, s_homeDir).Wait(); // assert and remove logo: var output = SplitLines(ReadOutputToEnd()); var errorOutput = ReadErrorOutputToEnd(); Assert.Equal("", errorOutput); Assert.Equal(2, output.Length); Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); // "Type "#help" for more information." Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]); // remove logo: ClearOutput(); } public override void Dispose() { try { Process process = Host.TryGetProcess(); DisposeInteractiveHostProcess(Host); // the process should be terminated if (process != null && !process.HasExited) { process.WaitForExit(); } } finally { // Dispose temp files only after the InteractiveHost exits, // so that assemblies are unloaded. base.Dispose(); } } private void RedirectOutput() { _synchronizedOutput = new SynchronizedStringWriter(); _synchronizedErrorOutput = new SynchronizedStringWriter(); ClearOutput(); Host.Output = _synchronizedOutput; Host.ErrorOutput = _synchronizedErrorOutput; } private bool LoadReference(string reference) { return Execute($"#r \"{reference}\""); } private bool Execute(string code) { var task = Host.ExecuteAsync(code); task.Wait(); return task.Result.Success; } private bool IsShadowCopy(string path) { return Host.TryGetService().IsShadowCopy(path); } public string ReadErrorOutputToEnd() { return ReadOutputToEnd(isError: true); } public void ClearOutput() { _outputReadPosition = new int[] { 0, 0 }; _synchronizedOutput.Clear(); _synchronizedErrorOutput.Clear(); } public void RestartHost(string rspFile = null) { ClearOutput(); var initTask = Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile, culture: CultureInfo.InvariantCulture)); initTask.Wait(); } public string ReadOutputToEnd(bool isError = false) { var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput; var markPrefix = '\uFFFF'; var mark = markPrefix + Guid.NewGuid().ToString(); // writes mark to the STDOUT/STDERR pipe in the remote process: Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError); while (true) { var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]); if (data != null) { return data; } Thread.Sleep(10); } } private class CompiledFile { public string Path; public ImmutableArray<byte> Image; } private static CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references) { var file = dir.CreateFile(fileName); var compilation = CreateCompilation( new[] { source }, assemblyName: assemblyName, references: references.Concat(new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }), options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll); var image = compilation.EmitToArray(); file.WriteAllBytes(image); return new CompiledFile { Path = file.Path, Image = image }; } #endregion [Fact] public void OutputRedirection() { Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1 "); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public void OutputRedirection2() { Execute(@"System.Console.WriteLine(1);"); Execute(@"System.Console.Error.WriteLine(2);"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); Execute(@"System.Console.WriteLine(3);"); Execute(@"System.Console.Error.WriteLine(4);"); output = ReadOutputToEnd(); error = ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact] public void StackOverflow() { // Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test: if (Environment.OSVersion.Version < new Version(6, 1, 0, 0)) { return; } Execute(@" int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9); } foo(0,1,2,3,4,5,6,7,8,9) "); Assert.Equal("", ReadOutputToEnd()); // Hosting process exited with exit code -1073741571. Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim()); Execute(@"1+1"); Assert.Equal("2\r\n", ReadOutputToEnd().ToString()); } private const string MethodWithInfiniteLoop = @" void foo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public void AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact(Skip = "529027")] public void AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); Assert.Equal("", ReadErrorOutputToEnd()); Assert.True(mayTerminate.WaitOne()); var service = Host.TryGetService(); Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); service.EmulateClientExit(); // the process should terminate with exit code 0: process.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public void AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact] public void AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1 1").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_NonExistingFile() { var task = Host.ExecuteFileAsync("non existing file"); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.Contains(FeaturesResources.SpecifiedFileNotFound, errorOut, StringComparison.Ordinal); Assert.Contains(FeaturesResources.SearchedInDirectory, errorOut, StringComparison.Ordinal); } [Fact] public void AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Foo(int i) { return i; } } public int Foo(int i) { return i; } WriteLine(5); ").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.True(task.Result.Success); Assert.Equal("5", ReadOutputToEnd().Trim()); Execute("Foo(2)"); Assert.Equal("2", ReadOutputToEnd().Trim()); Execute("new C().Foo(3)"); Assert.Equal("3", ReadOutputToEnd().Trim()); Execute("new C().field"); Assert.Equal("4", ReadOutputToEnd().Trim()); } [Fact] public void AsyncExecuteFile_InvalidFileContent() { var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location); executeTask.Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); Host.ExecuteFileAsync(file.Path).Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public void UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); Host.TryGetService().HookMaliciousAssemblyResolve(); var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(mayTerminate.WaitOne()); executeTask.Wait(); Assert.True(Execute(@"1+1")); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public void AddReference_Path() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference(Assembly.Load(new AssemblyName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")).Location)); Assert.True(Execute("new System.Data.DataSet()")); } [Fact] public void AddReference_PartialName() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference("System.Data")); Assert.True(Execute("new System.Data.DataSet()")); } [Fact] public void AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(LoadReference("System.Data")); Assert.True(LoadReference("System")); Assert.True(LoadReference("System.Xml")); Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public void AddReference_FullName() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); Assert.True(Execute("new System.Data.DataSet()")); } [ConditionalFact(typeof(Framework35Installed), Skip="https://github.com/dotnet/roslyn/issues/5167")] public void AddReference_VersionUnification1() { // V3.5 unifies with the current Framework version: var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } [Fact] public void AddReference_AssemblyAlreadyLoaded() { var result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core.dll"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } // Caused by submission not inheriting references. [Fact(Skip = "101161")] public void AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: Assert.True(LoadReference(c.Path)); Assert.True(Execute("new C()")); Assert.Equal("C { }", ReadOutputToEnd().Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = Execute("new C()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("C { }", ReadOutputToEnd().Trim()); Assert.True(result); } #if TODO /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } #endif /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path)); Assert.True(LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); Execute("#r \"" + lib1.Path + "\""); Execute("#r \"" + lib2.Path + "\""); Execute("new C().M()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact(Skip = "101161")] public void AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: Execute($@" #r ""{file.Path}"" C foo() => new C(); new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: Execute($@" #r ""{file.Path}"" new D().Y "); // TODO: We should report an error that assembly named 'a' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal( @"1 2", ReadOutputToEnd().Trim()); } [Fact(Skip = "129388")] public void AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); Execute("new C1()"); Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported". Assert.Equal( @"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } [Fact(Skip = "129388")] public void AddReference_MultipleReferencesWeakVersioning() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); Execute("new C1()"); Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. Assert.Equal("TODO: error", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/lib:" + directory.Path); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); Assert.Equal("", ReadErrorOutputToEnd()); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); } [Fact] public void DefaultUsings() { var rspFile = Temp.CreateFile(); rspFile.WriteAllText(@" /r:System /r:System.Core /r:Microsoft.CSharp /u:System /u:System.IO /u:System.Collections.Generic /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks "); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute(@" dynamic d = new ExpandoObject(); Process p = new Process(); Expression<Func<int>> e = () => 1; var squares = from x in new[] { 1, 2, 3 } select x * x; var sb = new StringBuilder(); var list = new List<int>(); var stream = new MemoryStream(); await Task.Delay(10); Console.Write(""OK"") "); Assert.Equal("", ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"Loading context from '{Path.GetFileName(rspFile.Path)}'. OK ", ReadOutputToEnd()); } [Fact] public void ScriptAndArguments() { var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" {scriptFile} a b c "); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Assert.Equal("", ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"Loading context from '{Path.GetFileName(rspFile.Path)}'. ""a"" ""b"" ""c"" ", ReadOutputToEnd()); } [Fact] public void ReferenceDirectives() { Execute(@" #r ""System.Numerics"" #r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @""" using static System.Console; using System.Linq.Expressions; using System.Numerics; WriteLine(Expression.Constant(1)); WriteLine(new Complex(2, 6).Real); "); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n", output); } [Fact] public void Script_NoHostNamespaces() { Execute("nameof(Microsoft.CodeAnalysis)"); AssertEx.AssertEqualToleratingWhitespaceDifferences(@" (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)", ReadErrorOutputToEnd()); Assert.Equal("", ReadOutputToEnd()); } [Fact] public void ExecutesOnStaThread() { Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public void ExecuteSequentially() { Execute(@"using System; using System.Threading.Tasks;"); Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); Execute(@"3"); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact] public void SearchPaths1() { var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path); srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework"); // print default: Host.ExecuteAsync(@"ReferencePaths").Wait(); var output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir })) + "\" }\r\n", output); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir })) + "\" }\r\n", output); // add and test if added: Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait(); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir, srcDir.Path })) + "\" }\r\n", output); // execute file (uses modified search paths), the file adds a reference path Host.ExecuteFileAsync("foo.csx").Wait(); Host.ExecuteAsync(@"ReferencePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir, dllDir })) + "\" }\r\n", output); Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait(); Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); output = ReadOutputToEnd(); Assert.Equal("[Metadata.ICSProp]\r\n", output); } #region Submission result printing - null/void/value. [Fact] public void SubmissionResult_PrintingNull() { Execute(@" string s; s "); var output = ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public void SubmissionResult_PrintingVoid() { Execute(@"System.Console.WriteLine(2)"); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); Execute(@" void foo() { } foo() "); output = ReadOutputToEnd(); Assert.Equal("", output); } #endregion private static ImmutableArray<string> SplitLines(string text) { return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } }
using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Collections.Generic; using DSL.POS.DTO.DTO; using DSL.POS.DataAccessLayer.Common.Imp; using DSL.POS.DataAccessLayer.Interface; namespace DSL.POS.DataAccessLayer.Imp { /// <summary> /// Summary description for SupplierInfoDALImp /// </summary> public class SupplierInfoDALImp : CommonDALImp, ISupplierInfoDAL { // Error Handling developed by Samad // 05/12/06 private void getPKCode(SupplierInfoDTO obj) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); string strPKCode = null; int PKSL = 0; string sqlSelect = "Select isnull(Max(SupplierCode),0)+1 From SupplierInfo"; SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; try { sqlConn.Open(); PKSL = (int)objCmd.ExecuteScalar(); } catch(Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } strPKCode = PKSL.ToString("000000"); obj.SupplierCode = strPKCode; //return strPKCode; } public override void Save(object obj) { SupplierInfoDTO oSupplierInfoDTO = (SupplierInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); if (oSupplierInfoDTO.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { //string strset = getPKCode(oProductCategoryInfoDTO); String sql = "Insert Into SupplierInfo(SupplierCode,SupplierName,ContractPerson,ShortName,Address,Phone,Fax,Email,WebAddress,EntryBy,EntryDate) values(@SupplierCode,@SupplierName,@ContractPerson,@ShortName,@Address,@Phone,@Fax,@Email,@WebAddress,@EntryBy,@EntryDate)"; try { getPKCode(oSupplierInfoDTO); objCmd.CommandText = sql; objCmd.Parameters.Add(new SqlParameter("@SupplierCode", SqlDbType.VarChar, 6)); objCmd.Parameters.Add(new SqlParameter("@SupplierName", SqlDbType.VarChar, 100)); objCmd.Parameters.Add(new SqlParameter("@ContractPerson", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@ShortName", SqlDbType.VarChar, 25)); objCmd.Parameters.Add(new SqlParameter("@Address", SqlDbType.VarChar, 150)); objCmd.Parameters.Add(new SqlParameter("@Phone", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@Fax", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@Email", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@WebAddress", SqlDbType.VarChar, 20)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 5)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime)); objCmd.Parameters["@SupplierCode"].Value = Convert.ToString(oSupplierInfoDTO.SupplierCode); objCmd.Parameters["@SupplierName"].Value = Convert.ToString(oSupplierInfoDTO.SupplierName); objCmd.Parameters["@ContractPerson"].Value = Convert.ToString(oSupplierInfoDTO.ContractPerson); objCmd.Parameters["@ShortName"].Value = Convert.ToString(oSupplierInfoDTO.ShortName); objCmd.Parameters["@Address"].Value = Convert.ToString(oSupplierInfoDTO.Address); objCmd.Parameters["@Phone"].Value = Convert.ToString(oSupplierInfoDTO.Phone); objCmd.Parameters["@Fax"].Value = Convert.ToString(oSupplierInfoDTO.Fax); objCmd.Parameters["@Email"].Value = Convert.ToString(oSupplierInfoDTO.Email); objCmd.Parameters["@WebAddress"].Value = Convert.ToString(oSupplierInfoDTO.WebAddress); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oSupplierInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oSupplierInfoDTO.EntryDate); sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Close(); sqlConn.Dispose(); } } else { String sql = "Update SupplierInfo set SupplierName=@SupplierName,ContractPerson=@ContractPerson,ShortName=@ShortName,Address=@Address,Phone=@Phone,Fax=@Fax,Email=@Email,WebAddress=@WebAddress,EntryBy=@EntryBy,EntryDate=@EntryDate where Sp_PK=@Sp_PK"; //objCmd = new SqlCommand(sql, getCurrentConnection(), getCurrentTransaction()); ; try { objCmd.CommandText = sql; objCmd.Parameters.Add(new SqlParameter("@Sp_PK", SqlDbType.UniqueIdentifier, 16)); //objCmd.Parameters.Add(new SqlParameter("@SupplierCode", SqlDbType.VarChar, 6)); objCmd.Parameters.Add(new SqlParameter("@SupplierName", SqlDbType.VarChar, 100)); objCmd.Parameters.Add(new SqlParameter("@ContractPerson", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@ShortName", SqlDbType.VarChar, 25)); objCmd.Parameters.Add(new SqlParameter("@Address", SqlDbType.VarChar, 150)); objCmd.Parameters.Add(new SqlParameter("@Phone", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@Fax", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@Email", SqlDbType.VarChar, 30)); objCmd.Parameters.Add(new SqlParameter("@WebAddress", SqlDbType.VarChar, 20)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 5)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime)); objCmd.Parameters["@Sp_PK"].Value = (Guid)oSupplierInfoDTO.PrimaryKey; //objCmd.Parameters["@SupplierCode"].Value = Convert.ToString(oSupplierInfoDTO.SupplierCode); objCmd.Parameters["@SupplierName"].Value = Convert.ToString(oSupplierInfoDTO.SupplierName); objCmd.Parameters["@ContractPerson"].Value = Convert.ToString(oSupplierInfoDTO.ContractPerson); objCmd.Parameters["@ShortName"].Value = Convert.ToString(oSupplierInfoDTO.ShortName); objCmd.Parameters["@Address"].Value = Convert.ToString(oSupplierInfoDTO.Address); objCmd.Parameters["@Phone"].Value = Convert.ToString(oSupplierInfoDTO.Phone); objCmd.Parameters["@Fax"].Value = Convert.ToString(oSupplierInfoDTO.Fax); objCmd.Parameters["@Email"].Value = Convert.ToString(oSupplierInfoDTO.Email); objCmd.Parameters["@WebAddress"].Value = Convert.ToString(oSupplierInfoDTO.WebAddress); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oSupplierInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oSupplierInfoDTO.EntryDate); sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } } public override void Delete(object obj) { SupplierInfoDTO oSupplierInfoDTO = (SupplierInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); String sql = "Delete SupplierInfo where Sp_PK=@Sp_PK"; SqlCommand objCmdDelete = sqlConn.CreateCommand(); objCmdDelete.CommandText = sql; try { objCmdDelete.Parameters.Add("@Sp_PK", SqlDbType.UniqueIdentifier, 16); objCmdDelete.Parameters["@Sp_PK"].Value = (Guid)oSupplierInfoDTO.PrimaryKey; sqlConn.Open(); objCmdDelete.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmdDelete.Dispose(); objCmdDelete.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } public SupplierInfoDTO findByPKDTO(Guid pk) { SupplierInfoDTO oSupplierInfoDTO = new SupplierInfoDTO(); //oSupplierInfoDTO.PrimaryKey = pk; string sqlSelect = "Select Sp_PK,SupplierCode,SupplierName,ContractPerson,ShortName,Address,Phone,Fax,Email,WebAddress,EntryBy,EntryDate From SupplierInfo where Sp_PK=@Sp_PK"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; try { objCmd.Parameters.Add("@Sp_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@Sp_PK"].Value = pk; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { oSupplierInfoDTO = populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return oSupplierInfoDTO; } public List<SupplierInfoDTO> getSupplierInfoData() { string sqlSelect = "Select Sp_PK,SupplierCode,SupplierName,ContractPerson,ShortName,Address,Phone,Fax,Email,WebAddress,EntryBy,EntryDate From SupplierInfo order by SupplierCode DESC"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); List<SupplierInfoDTO> oArrayList = new List<SupplierInfoDTO>(); SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; try { sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { SupplierInfoDTO oSupplierInfoDTO = populate(thisReader); oArrayList.Add(oSupplierInfoDTO); } thisReader.Close(); thisReader.Dispose(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return oArrayList; } public SupplierInfoDTO GetSupplierInfoBYCode(string strCode) { SupplierInfoDTO oSupplierInfoDTO = new SupplierInfoDTO(); //oSupplierInfoDTO.PrimaryKey = pk; string sqlSelect = "Select Sp_PK,SupplierCode,SupplierName,ContractPerson,ShortName,Address,Phone,Fax,Email,WebAddress,EntryBy,EntryDate From SupplierInfo where SupplierCode=@SupplierCode"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; try { objCmd.Parameters.Add(new SqlParameter("@SupplierCode", SqlDbType.VarChar, 6)); objCmd.Parameters["@SupplierCode"].Value = strCode; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { oSupplierInfoDTO = populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return oSupplierInfoDTO; } public SupplierInfoDTO populate(SqlDataReader reader) { try { SupplierInfoDTO dto = new SupplierInfoDTO(); dto.PrimaryKey = (Guid)reader["Sp_PK"]; dto.SupplierCode = (string)reader["SupplierCode"]; dto.SupplierName = (string)reader["SupplierName"]; dto.ContractPerson = (string)reader["ContractPerson"]; dto.ShortName = (string)reader["ShortName"]; dto.Address = (string)reader["Address"]; dto.Phone = (string)reader["Phone"]; dto.Fax = (string)reader["Fax"]; dto.Email = (string)reader["Email"]; dto.WebAddress = (string)reader["WebAddress"]; dto.EntryBy = (string)reader["EntryBy"]; dto.EntryDate = (DateTime)reader["EntryDate"]; return dto; } catch (Exception ex) { throw ex; } } public SupplierInfoDALImp() { // // TODO: Add constructor logic here // } } }
// 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 Infrastructure.Common; using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using Xunit; public class NegotiateStream_Http_Tests : ConditionalWcfTest { // The tests are as follows: // // NegotiateStream_*_AmbientCredentials // Windows: This should pass by default without any code changes // Linux: This should not pass by default // Run 'kinit [email protected]' before running this test to use ambient credentials // ('DC.DOMAIN.COM' must be in capital letters) // If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all // prior Kerberos tickets // // NegotiateStream_*_With_ExplicitUserNameAndPassword // Windows: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm // Linux: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm // If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all // prior Kerberos tickets // // NegotiateStream_*_With_ExplicitSpn // Windows: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server // Linux: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server // // By default, the SPN is the same as the host's fully qualified domain name, for example, // 'host.domain.com' // On a Windows host, one has to register the SPN using 'setspn', or run the process as LOCAL SYSTEM. // This can be done by setting the PSEXEC_PATH environment variable to point to the folder containing // psexec.exe prior to starting the WCF self-host service. // // NegotiateStream_*_With_Upn // Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server in the form of // '[email protected]' // Linux: This scenario is not yet supported - dotnet/corefx#6606 // // NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Spn // Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server // Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm // Linux: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server // Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm // // NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Upn // Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server // Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm // Linux: This scenario is not yet supported - dotnet/corefx#6606 // These tests are used for testing NegotiateStream (SecurityMode.Transport) [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Ambient_Credentials_Available))] [OuterLoop] public static void NegotiateStream_Http_AmbientCredentials() { string testString = "Hello"; string result = ""; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress(Endpoints.Https_WindowsAuth_Address)); serviceProxy = factory.CreateChannel(); if (Environment.Version.Major == 5 && !OSID.AnyWindows.MatchesCurrent() && !TestProperties.GetProperty(TestProperties.ServiceUri_PropertyName).Contains("/")) { Assert.Throws<System.ServiceModel.ProtocolException>(() => { result = serviceProxy.Echo(testString); }); } else { // *** EXECUTE *** \\ result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); } // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Ambient_Credentials_Available))] [OuterLoop] public static void NegotiateStream_Http_AmbientCredentialsForNet50() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; string spn = GetSPN().ToLowerInvariant().Replace("host", "HTTP"); factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress(new Uri(Endpoints.Https_WindowsAuth_Address), new SpnEndpointIdentity(spn))); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Explicit_Credentials_Available), nameof(Domain_Available))] [OuterLoop] // Test Requirements \\ // The following environment variables must be set... // "NegotiateTestRealm" // "NegotiateTestDomain" // "ExplicitUserName" // "ExplicitPassword" // "ServiceUri" (server running as machine context) public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress(Endpoints.Https_WindowsAuth_Address)); factory.Credentials.Windows.ClientCredential.Domain = GetDomain(); factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName(); factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword(); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Explicit_Credentials_Available), nameof(Domain_Available))] [OuterLoop] // Test Requirements \\ // The following environment variables must be set... // "NegotiateTestRealm" // "NegotiateTestDomain" // "ExplicitUserName" // "ExplicitPassword" // "ServiceUri" (server running as machine context) public static void NegotiateStream_Http_With_ExplicitUserNameAndPasswordForNet50() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; string spn = GetSPN().ToLowerInvariant().Replace("host", "HTTP"); factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress(new Uri(Endpoints.Https_WindowsAuth_Address), new SpnEndpointIdentity(spn))); factory.Credentials.Windows.ClientCredential.Domain = GetDomain(); factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName(); factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword(); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(SPN_Available))] [OuterLoop] // Test Requirements \\ // The following environment variables must be set... // "NegotiateTestRealm" // "NegotiateTestDomain" // "NegotiateTestSpn" (host/<servername>) // "ServiceUri" (server running as machine context) public static void NegotiateStream_Http_With_ExplicitSpn() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Https_WindowsAuth_Address), new SpnEndpointIdentity(GetSPN()) )); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(UPN_Available))] [OuterLoop] public static void NegotiateStream_Http_With_Upn() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Https_WindowsAuth_Address), new UpnEndpointIdentity(GetUPN()) )); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Explicit_Credentials_Available), nameof(Domain_Available), nameof(SPN_Available))] [OuterLoop] // Test Requirements \\ // The following environment variables must be set... // "NegotiateTestRealm" // "NegotiateTestDomain" // "ExplicitUserName" // "ExplicitPassword" // "NegotiateTestSpn" (host/<servername>) // "ServiceUri" (server running as machine context) public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword_With_Spn() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Https_WindowsAuth_Address), new SpnEndpointIdentity(GetSPN()) )); factory.Credentials.Windows.ClientCredential.Domain = GetDomain(); factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName(); factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword(); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Windows_Authentication_Available), nameof(Root_Certificate_Installed), nameof(Explicit_Credentials_Available), nameof(Domain_Available), nameof(UPN_Available))] [OuterLoop] public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword_With_Upn() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory<IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Https_WindowsAuth_Address), new UpnEndpointIdentity(GetUPN()) )); factory.Credentials.Windows.ClientCredential.Domain = GetDomain(); factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName(); factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword(); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Threading; using EasyNetQ.SystemMessages; using Newtonsoft.Json; namespace EasyNetQ.Scheduler { public interface IScheduleRepository { void Store(ScheduleMe scheduleMe); void Cancel(UnscheduleMe unscheduleMe); IList<ScheduleMe> GetPending(); void Purge(); } public class ScheduleRepository : IScheduleRepository { private readonly ScheduleRepositoryConfiguration configuration; private readonly IEasyNetQLogger log; private readonly Func<DateTime> now; private readonly ISqlDialect dialect; public ScheduleRepository(ScheduleRepositoryConfiguration configuration, IEasyNetQLogger log, Func<DateTime> now) { this.configuration = configuration; this.log = log; this.now = now; this.dialect = SqlDialectResolver.Resolve(configuration.ProviderName); } public void Store(ScheduleMe scheduleMe) { WithStoredProcedureCommand(dialect.InsertProcedureName, command => { AddParameter(command, dialect.WakeTimeParameterName, scheduleMe.WakeTime, DbType.DateTime); AddParameter(command, dialect.BindingKeyParameterName, scheduleMe.BindingKey, DbType.String); AddParameter(command, dialect.CancellationKeyParameterName, scheduleMe.CancellationKey, DbType.String); AddParameter(command, dialect.MessageParameterName, scheduleMe.InnerMessage, DbType.Binary); AddParameter(command, dialect.ExchangeParameterName, scheduleMe.Exchange, DbType.String); AddParameter(command, dialect.ExchangeTypeParameterName, scheduleMe.ExchangeType, DbType.String); AddParameter(command, dialect.RoutingKeyParameterName, scheduleMe.RoutingKey, DbType.String); AddParameter(command, dialect.MessagePropertiesParameterName, SerializeToString(scheduleMe.MessageProperties), DbType.String); AddParameter(command, dialect.InstanceNameParameterName, configuration.InstanceName, DbType.String); command.ExecuteNonQuery(); }); } public void Cancel(UnscheduleMe unscheduleMe) { ThreadPool.QueueUserWorkItem(state => WithStoredProcedureCommand(dialect.CancelProcedureName, command => { try { AddParameter(command, dialect.CancellationKeyParameterName, unscheduleMe.CancellationKey, DbType.String); command.ExecuteNonQuery(); } catch (Exception ex) { log.ErrorWrite("ScheduleRepository.Cancel threw an exception {0}", ex); } }) ); } public IList<ScheduleMe> GetPending() { var scheduledMessages = new List<ScheduleMe>(); var scheduleMessageIds = new List<int>(); WithStoredProcedureCommand(dialect.SelectProcedureName, command => { var dateTime = now(); AddParameter(command, dialect.RowsParameterName, configuration.MaximumScheduleMessagesToReturn, DbType.Int32); AddParameter(command, dialect.StatusParameterName, 0, DbType.Int16); AddParameter(command, dialect.WakeTimeParameterName, dateTime, DbType.DateTime); AddParameter(command, dialect.InstanceNameParameterName, configuration.InstanceName ?? "", DbType.String); using (var reader = command.ExecuteReader()) { while (reader.Read()) { scheduledMessages.Add(new ScheduleMe { WakeTime = (DateTime) reader["WakeTime"], BindingKey = reader["BindingKey"].ToString(), InnerMessage = (byte[])reader["InnerMessage"], CancellationKey = reader["CancellationKey"].ToString(), Exchange = reader["Exchange"].ToString(), ExchangeType = reader["ExchangeType"].ToString(), RoutingKey = reader["RoutingKey"].ToString(), MessageProperties = DeserializeToMessageProperties(reader["MessageProperties"].ToString()), }); scheduleMessageIds.Add((int)reader["WorkItemId"]); } } }); MarkItemsForPurge(scheduleMessageIds); return scheduledMessages; } public void MarkItemsForPurge(IEnumerable<int> scheduleMessageIds) { // mark items for purge on a background thread. ThreadPool.QueueUserWorkItem(state => WithStoredProcedureCommand(dialect.MarkForPurgeProcedureName, command => { try { var purgeDate = now().AddDays(configuration.PurgeDelayDays); var idParameter = AddParameter(command, dialect.IdParameterName, DbType.Int32); AddParameter(command, dialect.PurgeDateParameterName, purgeDate, DbType.DateTime); foreach (var scheduleMessageId in scheduleMessageIds) { idParameter.Value = scheduleMessageId; command.ExecuteNonQuery(); } } catch (Exception ex) { log.ErrorWrite("ScheduleRepository.MarkItemsForPurge threw an exception {0}", ex); } }) ); } private static MessageProperties DeserializeToMessageProperties(string properties) { // backwards compatibility with older messages if (string.IsNullOrWhiteSpace(properties)) return null; return JsonConvert.DeserializeObject<MessageProperties>(properties); } private static string SerializeToString(MessageProperties properties) { if (properties == null) throw new ArgumentNullException("properties"); return JsonConvert.SerializeObject(properties); } public void Purge() { WithStoredProcedureCommand(dialect.PurgeProcedureName, command => { AddParameter(command, dialect.RowsParameterName, configuration.PurgeBatchSize, DbType.Int16); AddParameter(command, dialect.PurgeDateParameterName, now(), DbType.DateTime); command.ExecuteNonQuery(); }); } private void WithStoredProcedureCommand(string storedProcedureName, Action<IDbCommand> commandAction) { using (var connection = GetConnection()) using (var command = CreateCommand(connection, FormatWithSchemaName(storedProcedureName))) { command.CommandType = CommandType.StoredProcedure; commandAction(command); } } private string FormatWithSchemaName(string storedProcedureName) { if (string.IsNullOrWhiteSpace(configuration.SchemaName)) return storedProcedureName; return string.Format("[{0}].{1}", configuration.SchemaName.TrimStart('[').TrimEnd('.', ']'), storedProcedureName); } private IDbConnection GetConnection() { var factory = DbProviderFactories.GetFactory(configuration.ProviderName); var connection = factory.CreateConnection(); connection.ConnectionString = configuration.ConnectionString; connection.Open(); return connection; } private IDbCommand CreateCommand(IDbConnection connection, string commandText) { var command = connection.CreateCommand(); command.CommandText = commandText; return command; } private void AddParameter(IDbCommand command, string parameterName, object value, DbType dbType) { var parameter = command.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; parameter.DbType = dbType; command.Parameters.Add(parameter); } private IDbDataParameter AddParameter(IDbCommand command, string parameterName, DbType dbType) { var parameter = command.CreateParameter(); parameter.ParameterName = parameterName; parameter.DbType = dbType; command.Parameters.Add(parameter); return parameter; } } }
// <copyright file="DataGenerator.Strings.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using IX.StandardExtensions.Contracts; namespace IX.DataGeneration; /// <summary> /// A static class that is used for generating random data for testing. /// </summary> public static partial class DataGenerator { #region Internal state private static readonly char[] AllCharacters; // Complex character classes private static readonly char[] AlphaCharacters; private static readonly char[] AlphaNumericCharacters; private static readonly char[] BasicSymbolCharacters = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', ';', ':', '\'', '"', '\\', '|', ',', '.', '<', '>' }; // Character classes private static readonly char[] LowerCaseAlphaCharacters; private static readonly char[] NumericCharacters; private static readonly char[] UpperCaseAlphaCharacters; #endregion #region Methods #region Static methods /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomAlphanumericString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, AlphaNumericCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomAlphanumericString(Random random) { Random localRandom = Requires.NotNull(random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, AlphaNumericCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomAlphanumericString(int length) => RandomString( R, length, AlphaNumericCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomAlphanumericString( Random random, int length) => RandomString( random, length, AlphaNumericCharacters); /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomAlphaString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, AlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomAlphaString(Random random) { Random localRandom = Requires.NotNull(random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, AlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomAlphaString(int length) => RandomString( R, length, AlphaCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomAlphaString( Random random, int length) => RandomString( random, length, AlphaCharacters); /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomLowercaseString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, LowerCaseAlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomLowercaseString(Random random) { Random localRandom = Requires.NotNull(random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, LowerCaseAlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomLowercaseString(int length) => RandomString( R, length, LowerCaseAlphaCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomLowercaseString( Random random, int length) => RandomString( random, length, LowerCaseAlphaCharacters); /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomNumericString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, NumericCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomNumericString(Random random) { Random localRandom = Requires.NotNull( random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, NumericCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomNumericString(int length) => RandomString( R, length, NumericCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomNumericString( Random random, int length) => RandomString( random, length, NumericCharacters); /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, AllCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomString(Random random) { Random localRandom = Requires.NotNull( random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, AllCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomString(int length) => RandomString( R, length, AllCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomString( Random random, int length) => RandomString( random, length, AllCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="fromCharacters">The array of characters from which to generate the string.</param> /// <returns>A random string.</returns> public static string RandomString( Random random, char[] fromCharacters) { Random localRandom = Requires.NotNull( random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, fromCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <param name="fromCharacters">The array of characters from which to generate the string.</param> /// <returns>A random string.</returns> public static string RandomString( Random random, int length, char[] fromCharacters) { Random localRandom = Requires.NotNull( random); var localFromCharacters = Requires.NotNull( fromCharacters); var randomString = new char[length]; for (var i = 0; i < length; i++) { int position; lock (localRandom) { position = localRandom.Next(localFromCharacters.Length); } randomString[i] = localFromCharacters[position]; } return new string(randomString); } /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomSymbolString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, BasicSymbolCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomSymbolString(Random random) { Random localRandom = Requires.NotNull( random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, BasicSymbolCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomSymbolString(int length) => RandomString( R, length, BasicSymbolCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomSymbolString( Random random, int length) => RandomString( random, length, BasicSymbolCharacters); /// <summary> /// Generates a random string. /// </summary> /// <returns>A random string.</returns> public static string RandomUppercaseString() { int length; lock (R) { length = R.Next(); } return RandomString( R, length, UpperCaseAlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <returns>A random string.</returns> public static string RandomUppercaseString(Random random) { Random localRandom = Requires.NotNull( random); int length; lock (localRandom) { length = localRandom.Next(); } return RandomString( localRandom, length, UpperCaseAlphaCharacters); } /// <summary> /// Generates a random string. /// </summary> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomUppercaseString(int length) => RandomString( R, length, UpperCaseAlphaCharacters); /// <summary> /// Generates a random string. /// </summary> /// <param name="random">The random generator to use.</param> /// <param name="length">The length of the string to generate.</param> /// <returns>A random string.</returns> public static string RandomUppercaseString( Random random, int length) => RandomString( random, length, UpperCaseAlphaCharacters); #endregion #endregion }
using Chemistry; using Proteomics.Fragmentation; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; namespace EngineLayer { public class PsmFromTsv { private static readonly Regex PositionParser = new Regex(@"(\d+)\s+to\s+(\d+)"); private static readonly Regex VariantParser = new Regex(@"[a-zA-Z]+(\d+)([a-zA-Z]+)"); private static readonly Regex IonParser = new Regex(@"([a-zA-Z]+)(\d+)"); private static readonly char[] MzSplit = { '[', ',', ']', ';' }; public string FullSequence { get; } public int Ms2ScanNumber { get; } public string Filename { get; } public int PrecursorScanNum { get; } public int PrecursorCharge { get; } public double PrecursorMz { get; } public double PrecursorMass { get; } public double Score { get; } public string ProteinAccession { get; } public List<MatchedFragmentIon> MatchedIons { get; } public Dictionary<int, List<MatchedFragmentIon>> ChildScanMatchedIons { get; } // this is only used in crosslink for now, but in the future will be used for other experiment types public double QValue { get; } public double? TotalIonCurrent { get; } public double? DeltaScore { get; } public string Notch { get; } public string BaseSeq { get; } public string EssentialSeq { get; } public string MissedCleavage { get; } public string PeptideMonoMass { get; } public string MassDiffDa { get; } public string MassDiffPpm { get; } public string ProteinName { get; } public string GeneName { get; } public string OrganismName { get; } public string IntersectingSequenceVariations { get; } public string IdentifiedSequenceVariations { get; } public string SpliceSites { get; } public string PeptideDesicription { get; } public string StartAndEndResiduesInProtein { get; } public string PreviousAminoAcid { get; } public string NextAminoAcid { get; } public string DecoyContamTarget { get; } public double? QValueNotch { get; } public List<MatchedFragmentIon> VariantCrossingIons { get; } //For crosslink public string CrossType { get; } public string LinkResidues { get; } public int? ProteinLinkSite { get; } public int? Rank { get; } public string BetaPeptideProteinAccession { get; } public int? BetaPeptideProteinLinkSite { get; } public string BetaPeptideBaseSequence { get; } public string BetaPeptideFullSequence { get; } public string BetaPeptideTheoreticalMass { get; } public double? BetaPeptideScore { get; } public int? BetaPeptideRank { get; } public List<MatchedFragmentIon> BetaPeptideMatchedIons { get; } public Dictionary<int, List<MatchedFragmentIon>> BetaPeptideChildScanMatchedIons { get; } public double? XLTotalScore { get; } public string ParentIons { get; } public double? RetentionTime { get; } public PsmFromTsv(string line, char[] split, Dictionary<string, int> parsedHeader) { var spl = line.Split(split); //Required properties Filename = spl[parsedHeader[PsmTsvHeader.FileName]].Trim(); Ms2ScanNumber = int.Parse(spl[parsedHeader[PsmTsvHeader.Ms2ScanNumber]]); PrecursorScanNum = int.Parse(spl[parsedHeader[PsmTsvHeader.PrecursorScanNum]].Trim()); PrecursorCharge = (int)double.Parse(spl[parsedHeader[PsmTsvHeader.PrecursorCharge]].Trim(), CultureInfo.InvariantCulture); PrecursorMz = double.Parse(spl[parsedHeader[PsmTsvHeader.PrecursorMz]].Trim(), CultureInfo.InvariantCulture); PrecursorMass = double.Parse(spl[parsedHeader[PsmTsvHeader.PrecursorMass]].Trim(), CultureInfo.InvariantCulture); BaseSeq = RemoveParentheses(spl[parsedHeader[PsmTsvHeader.BaseSequence]].Trim()); FullSequence = spl[parsedHeader[PsmTsvHeader.FullSequence]]; PeptideMonoMass = spl[parsedHeader[PsmTsvHeader.PeptideMonoMass]].Trim(); Score = double.Parse(spl[parsedHeader[PsmTsvHeader.Score]].Trim(), CultureInfo.InvariantCulture); DecoyContamTarget = spl[parsedHeader[PsmTsvHeader.DecoyContaminantTarget]].Trim(); QValue = double.Parse(spl[parsedHeader[PsmTsvHeader.QValue]].Trim(), CultureInfo.InvariantCulture); MatchedIons = (spl[parsedHeader[PsmTsvHeader.MatchedIonMzRatios]].StartsWith("{")) ? ReadChildScanMatchedIons(spl[parsedHeader[PsmTsvHeader.MatchedIonMzRatios]].Trim(), BaseSeq).First().Value : ReadFragmentIonsFromString(spl[parsedHeader[PsmTsvHeader.MatchedIonMzRatios]].Trim(), BaseSeq); //For general psms TotalIonCurrent = (parsedHeader[PsmTsvHeader.TotalIonCurrent] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.TotalIonCurrent]].Trim(), CultureInfo.InvariantCulture); DeltaScore = (parsedHeader[PsmTsvHeader.DeltaScore] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.DeltaScore]].Trim(), CultureInfo.InvariantCulture); Notch = (parsedHeader[PsmTsvHeader.Notch] < 0) ? null : spl[parsedHeader[PsmTsvHeader.Notch]].Trim(); EssentialSeq = (parsedHeader[PsmTsvHeader.EssentialSequence] < 0) ? null : spl[parsedHeader[PsmTsvHeader.EssentialSequence]].Trim(); MissedCleavage = (parsedHeader[PsmTsvHeader.MissedCleavages] < 0) ? null : spl[parsedHeader[PsmTsvHeader.MissedCleavages]].Trim(); MassDiffDa = (parsedHeader[PsmTsvHeader.MassDiffDa] < 0) ? null : spl[parsedHeader[PsmTsvHeader.MassDiffDa]].Trim(); MassDiffPpm = (parsedHeader[PsmTsvHeader.MassDiffPpm] < 0) ? null : spl[parsedHeader[PsmTsvHeader.MassDiffPpm]].Trim(); ProteinAccession = (parsedHeader[PsmTsvHeader.ProteinAccession] < 0) ? null : spl[parsedHeader[PsmTsvHeader.ProteinAccession]].Trim(); ProteinName = (parsedHeader[PsmTsvHeader.ProteinName] < 0) ? null : spl[parsedHeader[PsmTsvHeader.ProteinName]].Trim(); GeneName = (parsedHeader[PsmTsvHeader.GeneName] < 0) ? null : spl[parsedHeader[PsmTsvHeader.GeneName]].Trim(); OrganismName = (parsedHeader[PsmTsvHeader.OrganismName] < 0) ? null : spl[parsedHeader[PsmTsvHeader.OrganismName]].Trim(); IntersectingSequenceVariations = (parsedHeader[PsmTsvHeader.IntersectingSequenceVariations] < 0) ? null : spl[parsedHeader[PsmTsvHeader.IntersectingSequenceVariations]].Trim(); IdentifiedSequenceVariations = (parsedHeader[PsmTsvHeader.IdentifiedSequenceVariations] < 0) ? null : spl[parsedHeader[PsmTsvHeader.IdentifiedSequenceVariations]].Trim(); SpliceSites = (parsedHeader[PsmTsvHeader.SpliceSites] < 0) ? null : spl[parsedHeader[PsmTsvHeader.SpliceSites]].Trim(); PeptideDesicription = (parsedHeader[PsmTsvHeader.PeptideDesicription] < 0) ? null : spl[parsedHeader[PsmTsvHeader.PeptideDesicription]].Trim(); StartAndEndResiduesInProtein = (parsedHeader[PsmTsvHeader.StartAndEndResiduesInProtein] < 0) ? null : spl[parsedHeader[PsmTsvHeader.StartAndEndResiduesInProtein]].Trim(); PreviousAminoAcid = (parsedHeader[PsmTsvHeader.PreviousAminoAcid] < 0) ? null : spl[parsedHeader[PsmTsvHeader.PreviousAminoAcid]].Trim(); NextAminoAcid = (parsedHeader[PsmTsvHeader.NextAminoAcid] < 0) ? null : spl[parsedHeader[PsmTsvHeader.NextAminoAcid]].Trim(); QValueNotch = (parsedHeader[PsmTsvHeader.QValueNotch] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.QValueNotch]].Trim(), CultureInfo.InvariantCulture); RetentionTime = (parsedHeader[PsmTsvHeader.Ms2ScanRetentionTime] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.Ms2ScanRetentionTime]].Trim(), CultureInfo.InvariantCulture); VariantCrossingIons = findVariantCrossingIons(); //For crosslinks CrossType = (parsedHeader[PsmTsvHeader.CrossTypeLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.CrossTypeLabel]].Trim(); LinkResidues = (parsedHeader[PsmTsvHeader.LinkResiduesLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.LinkResiduesLabel]].Trim(); ProteinLinkSite = (parsedHeader[PsmTsvHeader.ProteinLinkSiteLabel] < 0) ? null : (spl[parsedHeader[PsmTsvHeader.ProteinLinkSiteLabel]] == "" ? null : (int?)int.Parse(spl[parsedHeader[PsmTsvHeader.ProteinLinkSiteLabel]].Trim())); Rank = (parsedHeader[PsmTsvHeader.RankLabel] < 0) ? null : (int?)int.Parse(spl[parsedHeader[PsmTsvHeader.RankLabel]].Trim()); BetaPeptideProteinAccession = (parsedHeader[PsmTsvHeader.BetaPeptideProteinAccessionLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.BetaPeptideProteinAccessionLabel]].Trim(); BetaPeptideProteinLinkSite = (parsedHeader[PsmTsvHeader.BetaPeptideProteinLinkSiteLabel] < 0) ? null : (spl[parsedHeader[PsmTsvHeader.BetaPeptideProteinLinkSiteLabel]] == "" ? null : (int?)int.Parse(spl[parsedHeader[PsmTsvHeader.BetaPeptideProteinLinkSiteLabel]].Trim())); BetaPeptideBaseSequence = (parsedHeader[PsmTsvHeader.BetaPeptideBaseSequenceLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.BetaPeptideBaseSequenceLabel]].Trim(); BetaPeptideFullSequence = (parsedHeader[PsmTsvHeader.BetaPeptideFullSequenceLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.BetaPeptideFullSequenceLabel]].Trim(); BetaPeptideTheoreticalMass = (parsedHeader[PsmTsvHeader.BetaPeptideTheoreticalMassLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.BetaPeptideTheoreticalMassLabel]].Trim(); BetaPeptideScore = (parsedHeader[PsmTsvHeader.BetaPeptideScoreLabel] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.BetaPeptideScoreLabel]].Trim(), CultureInfo.InvariantCulture); BetaPeptideRank = (parsedHeader[PsmTsvHeader.BetaPeptideRankLabel] < 0) ? null : (int?)int.Parse(spl[parsedHeader[PsmTsvHeader.BetaPeptideRankLabel]].Trim()); BetaPeptideMatchedIons = (parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel] < 0) ? null : ((spl[parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel]].StartsWith("{")) ? ReadChildScanMatchedIons(spl[parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel]].Trim(), BetaPeptideBaseSequence).First().Value : ReadFragmentIonsFromString(spl[parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel]].Trim(), BetaPeptideBaseSequence)); XLTotalScore = (parsedHeader[PsmTsvHeader.XLTotalScoreLabel] < 0) ? null : (double?)double.Parse(spl[parsedHeader[PsmTsvHeader.XLTotalScoreLabel]].Trim(), CultureInfo.InvariantCulture); ParentIons = (parsedHeader[PsmTsvHeader.ParentIonsLabel] < 0) ? null : spl[parsedHeader[PsmTsvHeader.ParentIonsLabel]].Trim(); // child scan matched ions (only for crosslinks for now, but in the future this will change) ChildScanMatchedIons = (!spl[parsedHeader[PsmTsvHeader.MatchedIonMzRatios]].StartsWith("{")) ? null : ReadChildScanMatchedIons(spl[parsedHeader[PsmTsvHeader.MatchedIonMzRatios]].Trim(), BaseSeq); if (ChildScanMatchedIons != null && ChildScanMatchedIons.ContainsKey(Ms2ScanNumber)) { ChildScanMatchedIons.Remove(Ms2ScanNumber); } // beta peptide child scan matched ions (for crosslinks) BetaPeptideChildScanMatchedIons = (parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel] < 0) ? null : ((!spl[parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel]].StartsWith("{")) ? null : ReadChildScanMatchedIons(spl[parsedHeader[PsmTsvHeader.BetaPeptideMatchedIonsLabel]].Trim(), BetaPeptideBaseSequence)); if (BetaPeptideChildScanMatchedIons != null && BetaPeptideChildScanMatchedIons.ContainsKey(Ms2ScanNumber)) { BetaPeptideChildScanMatchedIons.Remove(Ms2ScanNumber); } } //Used to remove Silac labels for proper annotation public static string RemoveParentheses(string baseSequence) { if (baseSequence.Contains("(")) { string updatedBaseSequence = ""; bool withinParentheses = false; foreach (char c in baseSequence) { if (c == ')') //leaving the parentheses { withinParentheses = false; } else if (c == '(') //entering the parentheses { withinParentheses = true; } else if (!withinParentheses) //if outside the parentheses, preserve this amino acid { updatedBaseSequence += c; } //else do nothing } return updatedBaseSequence; } return baseSequence; } private static List<MatchedFragmentIon> ReadFragmentIonsFromString(string matchedMzString, string peptideBaseSequence) { var peaks = matchedMzString.Split(MzSplit, StringSplitOptions.RemoveEmptyEntries).Select(v => v.Trim()) .ToList(); peaks.RemoveAll(p => p.Contains("\"")); List<MatchedFragmentIon> matchedIons = new List<MatchedFragmentIon>(); foreach (var peak in peaks) { var split = peak.Split(new char[] { '+', ':' }); string ionTypeAndNumber = split[0]; Match result = IonParser.Match(ionTypeAndNumber); ProductType productType = (ProductType)Enum.Parse(typeof(ProductType), result.Groups[1].Value); int fragmentNumber = int.Parse(result.Groups[2].Value); int z = int.Parse(split[1]); double mz = double.Parse(split[2], CultureInfo.InvariantCulture); double neutralLoss = 0; // check for neutral loss if (ionTypeAndNumber.Contains("-")) { string temp = ionTypeAndNumber.Replace("(", ""); temp = temp.Replace(")", ""); var split2 = temp.Split('-'); neutralLoss = double.Parse(split2[1], CultureInfo.InvariantCulture); } FragmentationTerminus terminus = FragmentationTerminus.None; if (TerminusSpecificProductTypes.ProductTypeToFragmentationTerminus.ContainsKey(productType)) { terminus = TerminusSpecificProductTypes.ProductTypeToFragmentationTerminus[productType]; } int aminoAcidPosition = fragmentNumber; if (terminus == FragmentationTerminus.C) { aminoAcidPosition = peptideBaseSequence.Length - fragmentNumber; } var t = new NeutralTerminusFragment(terminus, mz.ToMass(z) - DissociationTypeCollection.GetMassShiftFromProductType(productType), fragmentNumber, aminoAcidPosition); Product p = new Product(productType, t, neutralLoss); matchedIons.Add(new MatchedFragmentIon(p, mz, 1.0, z)); } return matchedIons; } private static Dictionary<int, List<MatchedFragmentIon>> ReadChildScanMatchedIons(string childScanMatchedMzString, string peptideBaseSequence) { var childScanMatchedIons = new Dictionary<int, List<MatchedFragmentIon>>(); foreach (var childScan in childScanMatchedMzString.Split(new char[] { '}' }).Where(p => !string.IsNullOrWhiteSpace(p))) { var split1 = childScan.Split(new char[] { '@' }); int scanNumber = int.Parse(split1[0].Trim(new char[] { '{' })); string matchedIonsString = split1[1]; var childMatchedIons = ReadFragmentIonsFromString(matchedIonsString, peptideBaseSequence); childScanMatchedIons.Add(scanNumber, childMatchedIons); } return childScanMatchedIons; } // finds the ions that contain variant residues using the position in IdentifiedSequenceVariations. When the variation spans // multiple residues, if any part is contained in an ion, the ion is marked as variant crossing. private List<MatchedFragmentIon> findVariantCrossingIons() { List<MatchedFragmentIon> variantCrossingIons = new List<MatchedFragmentIon>(); if (StartAndEndResiduesInProtein != null && IdentifiedSequenceVariations != null) { Match positionMatch = PositionParser.Match(StartAndEndResiduesInProtein); Match variantMatch = VariantParser.Match(IdentifiedSequenceVariations); if (positionMatch.Success && variantMatch.Success) { List<ProductType> abcProductTypes = new List<ProductType>() { ProductType.a, ProductType.aDegree, ProductType.aStar, ProductType.b, ProductType.bDegree, ProductType.bStar, ProductType.c }; List<ProductType> xyzProductTypes = new List<ProductType>() { ProductType.x, ProductType.y, ProductType.yDegree, ProductType.yStar, ProductType.zDot, ProductType.zPlusOne}; int peptideStart = int.Parse(positionMatch.Groups[1].Value); int peptideEnd = int.Parse(positionMatch.Groups[2].Value); int variantResidueStart = int.Parse(variantMatch.Groups[1].Value); int variantResidueEnd = variantResidueStart + variantMatch.Groups[2].Value.Length - 1; foreach (MatchedFragmentIon ion in MatchedIons) { Match ionMatch = IonParser.Match(ion.Annotation); if (ionMatch.Success && (variantResidueEnd >= peptideStart && variantResidueStart <= peptideEnd) && // variant is within peptide ((abcProductTypes.Contains(ion.NeutralTheoreticalProduct.ProductType) && // type a, b, or c peptideStart + int.Parse(ionMatch.Groups[2].Value) > variantResidueStart) || // crosses variant (xyzProductTypes.Contains(ion.NeutralTheoreticalProduct.ProductType) && // type x, y, or z peptideEnd - int.Parse(ionMatch.Groups[2].Value) < variantResidueEnd))) // crosses variant { variantCrossingIons.Add(ion); } } } } return variantCrossingIons; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using bv.common.Configuration; using bv.common.Core; using bv.common.Resources; using bv.winclient.Localization; using DevExpress.Utils; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using Localizer = bv.common.Core.Localizer; namespace bv.winclient.Core { public class WinUtils { private const int StartFrame = 4; private static readonly Graphics m_Graphics; static WinUtils() { var label = new Label(); m_Graphics = label.CreateGraphics(); } public static SizeF MeasureString(String text, Font font, int width) { return m_Graphics.MeasureString(text, font, width); } /// <summary> /// </summary> /// <returns></returns> public static string AppPath() { return Path.GetDirectoryName(Application.ExecutablePath); } /// <summary> /// </summary> /// <param name="msg"></param> /// <param name="caption"></param> /// <returns></returns> public static bool ConfirmMessage(string msg, string caption) { return MessageForm.Show(msg, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes); } public static bool ConfirmMessage(IWin32Window owner, string msg, string caption) { MessageForm.ParentWindowHandle = owner; return MessageForm.Show(msg, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes); } public static DialogResult ConfirmMessage3Buttons(IWin32Window owner, string msg, string caption) { MessageForm.ParentWindowHandle = owner; return MessageForm.Show(msg, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } public static bool ConfirmMessage(IWin32Window owner, string msg) { MessageForm.ParentWindowHandle = owner; return MessageForm.Show(msg, BvMessages.Get("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes); } public static bool ConfirmMessage(string msg) { return MessageForm.Show(msg, BvMessages.Get("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes); } /// <summary> /// </summary> /// <returns></returns> public static bool ConfirmDelete() { return ConfirmMessage(BvMessages.Get("msgDeleteRecordPrompt", "The record will be deleted. Delete record?"), BvMessages.Get("Delete Record")); } public static bool ConfirmLookupClear() { return ConfirmMessage(BvMessages.Get("msgConfirmClearLookup"), BvMessages.Get("Confirmation")); } /// <summary> /// </summary> /// <returns></returns> public static bool ConfirmCancel(Form owner) { if (owner != null) { owner.Activate(); owner.BringToFront(); } return ConfirmMessage(BvMessages.Get("msgCancelPrompt", "Do you want to cancel all the changes and close the form?"), BvMessages.Get("Confirmation")); } /// <summary> /// </summary> /// <returns></returns> public static bool ConfirmSave() { return ConfirmMessage(BvMessages.Get("msgSavePrompt", "Do you want to save changes?"), BvMessages.Get("Confirmation")); } /// <summary> /// </summary> /// <returns></returns> public static bool ConfirmOk() { return ConfirmMessage(BvMessages.Get("msgOKPrompt", "Do you want to save changes and close the form?"), BvMessages.Get("Confirmation")); } /// <summary> /// </summary> /// <returns></returns> public static DialogResult ConfirmSaveForTranslationTool() { return MessageForm.Show( BvMessages.Get("msgSaveTranslationToolPrompt", "Do you want to save changes and close the form?") , BvMessages.Get("Confirmation") , MessageBoxButtons.YesNoCancel , MessageBoxIcon.Question); } /// <summary> /// </summary> public static void SwitchInputLanguage() { foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages) { if (lang.Culture.TwoLetterISOLanguageName == Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName) { InputLanguage.CurrentInputLanguage = lang; return; } } } private static readonly Regex m_ControlLanguageRegExp = new Regex("\\[(?<lng>.*)\\]", RegexOptions.IgnoreCase); private static string GetLanguageTag(Control c) { if (c != null && (c.Tag) is string) { Match m = m_ControlLanguageRegExp.Match(Convert.ToString(c.Tag)); if (m.Success) { return m.Result("${lng}"); } } return null; } public static void SetControlLanguage(Control c, out string lastInputLanguage) { lastInputLanguage = Localizer.GetLanguageID(InputLanguage.CurrentInputLanguage.Culture); string s = GetLanguageTag(c); if (!String.IsNullOrEmpty(s)) { SystemLanguages.SwitchInputLanguage(s); } } public static void SetControlLanguageEn(Control c) { string s = GetLanguageTag(c); if (!String.IsNullOrEmpty(s)) { SystemLanguages.SwitchInputLanguage(s); } } public static string GetControlLanguage(Control c) { string lang = GetLanguageTag(c); if (!String.IsNullOrEmpty(lang)) { string res = ""; if (lang == "def") { lang = BaseSettings.DefaultLanguage; } if (Localizer.SupportedLanguages.ContainsKey(lang)) { res = Convert.ToString(Localizer.SupportedLanguages[lang]); } if (res != "") { foreach (InputLanguage language in InputLanguage.InstalledInputLanguages) { if (language.Culture.Name == res) { return language.Culture.TwoLetterISOLanguageName; } } } } return ""; //return InputLanguage.CurrentInputLanguage.Culture.TwoLetterISOLanguageName; } public static bool HasControlAssignedLanguage(Control c) { if (c.Tag != null) { Match m = m_ControlLanguageRegExp.Match(Convert.ToString(c.Tag)); return m.Success; } return false; } public static void RemoveClearButton(LookUpEdit lookUpEdit) { int index = -1; foreach (EditorButton button in lookUpEdit.Properties.Buttons) { if (button.Kind == ButtonPredefines.Delete) { index = button.Index; break; } } if (index > 0) { lookUpEdit.Properties.Buttons.RemoveAt(index); } } public static void AddClearButton(ButtonEdit ctl) { IEnumerable<EditorButton> buttons = ctl.Properties.Buttons.Cast<EditorButton>(); if (buttons.All(button => button.Kind != ButtonPredefines.Delete)) { ctl.ButtonClick += ClearButtonClick; var btn = new EditorButton(ButtonPredefines.Delete, BvMessages.Get("btnClear", "Clear the field contents")); ctl.Properties.Buttons.Add(btn); } } public static void AddClearButtons(Control container) { foreach (Control ctl in container.Controls) { if ((ctl) is ButtonEdit) { AddClearButton((ButtonEdit) ctl); } } } private static void ClearButtonClick(object sender, ButtonPressedEventArgs e) { if (e.Button.Kind == ButtonPredefines.Delete) { ((BaseEdit) sender).EditValue = null; } } public static bool IsComponentInDesignMode(IComponent component) { if (component == null) { return false; } //' if all is simple if (component.Site != null) { return component.Site.DesignMode; } //' not so simple... Type smInterfaceMatch = typeof (IDesignerHost); var stack = new StackTrace(); int frameCount = stack.FrameCount - 1; //' look up in stack trace for type that implements interface IDesignerHost for (int frame = StartFrame; frame <= frameCount; frame++) { Type typeFromStack = stack.GetFrame(frame).GetMethod().DeclaringType; if (smInterfaceMatch.IsAssignableFrom(typeFromStack)) { return true; } } //' small stack trace or IDesignerHost absence is not characteristic of designers return false; } public static bool CheckMandatoryField(string fieldName, object value) { if (Utils.IsEmpty(value)) { ErrorForm.ShowWarningFormat("ErrMandatoryFieldRequired", "The field '{0}' is mandatory. You must enter data to this field before form saving", fieldName); return false; } return true; } public static bool ValidateDateInRange(object date, object startDate, object endDate) { if (Utils.IsEmpty(date)) { return true; } if ((!Utils.IsEmpty(startDate) && ((DateTime) date).Date < ((DateTime) startDate).Date) || (!Utils.IsEmpty(endDate) && ((DateTime) date).Date > ((DateTime) endDate).Date)) { return false; } return true; } public static void SetClearTooltip(BaseEdit ctl) { string tooltip = BvMessages.Get("msgClearControl", "Press Ctrl-Del to clear value."); if (ctl.ToolTip == null || !ctl.ToolTip.Contains(tooltip)) { ctl.ToolTip = tooltip; ctl.ToolTipIconType = ToolTipIconType.None; } } public static Point GetAbsoluteLocation(Control parent, Point location) { return parent == null ? location : GetAbsoluteLocation(parent.Parent, new Point(parent.Left + location.X, parent.Top + location.Y)); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.IO; using NLog.Config; using NLog.Common; /// <summary> /// Writes log messages to the console with customizable coloring. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso> [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default.In multithreaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private bool _disableColors; private IColoredConsolePrinter _consolePrinter; /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public ColoredConsoleTarget() { WordHighlightingRules = new List<ConsoleWordHighlightingRule>(); RowHighlightingRules = new List<ConsoleRowHighlightingRule>(); UseDefaultRowHighlightingRules = true; OptimizeBufferReuse = true; _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ColoredConsoleTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout). /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool ErrorStream { get; set; } /// <summary> /// Gets or sets a value indicating whether to use default row highlighting rules. /// </summary> /// <remarks> /// The default rules are: /// <table> /// <tr> /// <th>Condition</th> /// <th>Foreground Color</th> /// <th>Background Color</th> /// </tr> /// <tr> /// <td>level == LogLevel.Fatal</td> /// <td>Red</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Error</td> /// <td>Yellow</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Warn</td> /// <td>Magenta</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Info</td> /// <td>White</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Debug</td> /// <td>Gray</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Trace</td> /// <td>DarkGray</td> /// <td>NoChange</td> /// </tr> /// </table> /// </remarks> /// <docgen category='Highlighting Rules' order='9' /> [DefaultValue(true)] public bool UseDefaultRowHighlightingRules { get; set; } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> /// <docgen category='Console Options' order='10' /> public Encoding Encoding { get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging); set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging)) _encoding = value; } } private Encoding _encoding; #endif /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available. /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-check if the console has been redirected to file /// - Disables coloring logic when System.Console.IsOutputRedirected = true /// </summary> /// <docgen category='Console Options' order='11' /> [DefaultValue(false)] public bool DetectOutputRedirected { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-flush after <see cref="Console.WriteLine()"/> /// </summary> /// <remarks> /// Normally not required as standard Console.Out will have <see cref="StreamWriter.AutoFlush"/> = true, but not when pipe to file /// </remarks> /// <docgen category='Console Options' order='11' /> [DefaultValue(false)] public bool AutoFlush { get; set; } /// <summary> /// Enables output using ANSI Color Codes /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool EnableAnsiOutput { get; set; } /// <summary> /// Gets the row highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; } /// <summary> /// Gets the word highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='11' /> [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { _pauseLogging = false; _disableColors = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("ColoredConsole(Name={0}): Console detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {1}", Name, reason); } } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ if (_encoding != null) ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, true, _pauseLogging); #endif #if NET4_5 if (DetectOutputRedirected) { try { _disableColors = ErrorStream ? Console.IsErrorRedirected : Console.IsOutputRedirected; if (_disableColors) { InternalLogger.Info("ColoredConsole(Name={0}): Console output is redirected so no colors. Disable DetectOutputRedirected to skip detection.", Name); if (!AutoFlush && GetOutput() is StreamWriter streamWriter && !streamWriter.AutoFlush) { AutoFlush = true; } } } catch (Exception ex) { InternalLogger.Error(ex, "ColoredConsole(Name={0}): Failed checking if Console Output Redirected.", Name); } } #endif base.InitializeTarget(); if (Header != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Header, lei)); } _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } private static IColoredConsolePrinter CreateConsolePrinter(bool enableAnsiOutput) { #if !__IOS__ && !__ANDROID__ if (!enableAnsiOutput) return new ColoredConsoleSystemPrinter(); else #endif return new ColoredConsoleAnsiPrinter(); } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { if (Footer != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Footer, lei)); } ExplicitConsoleFlush(); base.CloseTarget(); } /// <inheritdoc /> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception ex) { asyncContinuation(ex); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { var output = GetOutput(); output.Flush(); } } /// <summary> /// Writes the specified log event to the console highlighting entries /// and words based on a set of defined rules. /// </summary> /// <param name="logEvent">Log event.</param> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance (See also DetectConsoleAvailable) return; } WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent)); } private void WriteToOutput(LogEventInfo logEvent, string message) { try { WriteToOutputWithColor(logEvent, message ?? string.Empty); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { // This is a bug and will therefore stop the logging. For docs, see the PauseLogging property. _pauseLogging = true; InternalLogger.Warn(ex, "ColoredConsole(Name={0}): {1} has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", Name, ex.GetType()); } } private void WriteToOutputWithColor(LogEventInfo logEvent, string message) { string colorMessage = message; ConsoleColor? newForegroundColor = null; ConsoleColor? newBackgroundColor = null; if (!_disableColors) { var matchingRule = GetMatchingRowHighlightingRule(logEvent); if (WordHighlightingRules.Count > 0) { colorMessage = GenerateColorEscapeSequences(logEvent, message); } newForegroundColor = matchingRule.ForegroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.ForegroundColor : default(ConsoleColor?); newBackgroundColor = matchingRule.BackgroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.BackgroundColor : default(ConsoleColor?); } var consoleStream = GetOutput(); if (ReferenceEquals(colorMessage, message) && !newForegroundColor.HasValue && !newBackgroundColor.HasValue) { ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, message, AutoFlush); } else { bool wordHighlighting = !ReferenceEquals(colorMessage, message); if (!wordHighlighting && message.IndexOf('\n') >= 0) { wordHighlighting = true; // Newlines requires additional handling when doing colors colorMessage = EscapeColorCodes(message); } WriteToOutputWithPrinter(consoleStream, colorMessage, newForegroundColor, newBackgroundColor, wordHighlighting); } } private void WriteToOutputWithPrinter(TextWriter consoleStream, string colorMessage, ConsoleColor? newForegroundColor, ConsoleColor? newBackgroundColor, bool wordHighlighting) { using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None) { TextWriter consoleWriter = _consolePrinter.AcquireTextWriter(consoleStream, targetBuilder.Result); ConsoleColor? oldForegroundColor = null; ConsoleColor? oldBackgroundColor = null; try { if (wordHighlighting) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor); oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor); var rowForegroundColor = newForegroundColor ?? oldForegroundColor; var rowBackgroundColor = newBackgroundColor ?? oldBackgroundColor; ColorizeEscapeSequences(_consolePrinter, consoleWriter, colorMessage, oldForegroundColor, oldBackgroundColor, rowForegroundColor, rowBackgroundColor); _consolePrinter.WriteLine(consoleWriter, string.Empty); } else { if (newForegroundColor.HasValue) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor.Value); if (oldForegroundColor == newForegroundColor) oldForegroundColor = null; // No color restore is needed } if (newBackgroundColor.HasValue) { oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor.Value); if (oldBackgroundColor == newBackgroundColor) oldBackgroundColor = null; // No color restore is needed } _consolePrinter.WriteLine(consoleWriter, colorMessage); } } finally { _consolePrinter.ReleaseTextWriter(consoleWriter, consoleStream, oldForegroundColor, oldBackgroundColor, AutoFlush); } } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { var matchingRule = GetMatchingRowHighlightingRule(RowHighlightingRules, logEvent); if (matchingRule == null && UseDefaultRowHighlightingRules) { matchingRule = GetMatchingRowHighlightingRule(_consolePrinter.DefaultConsoleRowHighlightingRules, logEvent); } return matchingRule ?? ConsoleRowHighlightingRule.Default; } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(IList<ConsoleRowHighlightingRule> rules, LogEventInfo logEvent) { for (int i = 0; i < rules.Count; ++i) { var rule = rules[i]; if (rule.CheckCondition(logEvent)) return rule; } return null; } private string GenerateColorEscapeSequences(LogEventInfo logEvent, string message) { if (string.IsNullOrEmpty(message)) return message; message = EscapeColorCodes(message); using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None) { StringBuilder sb = targetBuilder.Result; for (int i = 0; i < WordHighlightingRules.Count; ++i) { var hl = WordHighlightingRules[i]; var matches = hl.Matches(logEvent, message); if (matches == null || matches.Count == 0) continue; if (sb != null) sb.Length = 0; int previousIndex = 0; foreach (System.Text.RegularExpressions.Match match in matches) { sb = sb ?? new StringBuilder(message.Length + 5); sb.Append(message, previousIndex, match.Index - previousIndex); sb.Append('\a'); sb.Append((char)((int)hl.ForegroundColor + 'A')); sb.Append((char)((int)hl.BackgroundColor + 'A')); sb.Append(match.Value); sb.Append('\a'); sb.Append('X'); previousIndex = match.Index + match.Length; } if (sb?.Length > 0) { sb.Append(message, previousIndex, message.Length - previousIndex); message = sb.ToString(); } } } return message; } private static string EscapeColorCodes(string message) { if (message.IndexOf("\a", StringComparison.Ordinal) >= 0) message = message.Replace("\a", "\a\a"); return message; } private static void ColorizeEscapeSequences( IColoredConsolePrinter consolePrinter, TextWriter consoleWriter, string message, ConsoleColor? defaultForegroundColor, ConsoleColor? defaultBackgroundColor, ConsoleColor? rowForegroundColor, ConsoleColor? rowBackgroundColor) { var colorStack = new Stack<KeyValuePair<ConsoleColor?, ConsoleColor?>>(); colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(rowForegroundColor, rowBackgroundColor)); int p0 = 0; while (p0 < message.Length) { int p1 = p0; while (p1 < message.Length && message[p1] >= 32) { p1++; } // text if (p1 != p0) { consolePrinter.WriteSubString(consoleWriter, message, p0, p1); } if (p1 >= message.Length) { p0 = p1; break; } // control characters char c1 = message[p1]; if (c1 == '\r' || c1 == '\n') { // Newline control characters var currentColorConfig = colorStack.Peek(); var resetForegroundColor = currentColorConfig.Key != defaultForegroundColor ? defaultForegroundColor : null; var resetBackgroundColor = currentColorConfig.Value != defaultBackgroundColor ? defaultBackgroundColor : null; consolePrinter.ResetDefaultColors(consoleWriter, resetForegroundColor, resetBackgroundColor); if (p1 + 1 < message.Length && message[p1 + 1] == '\n') { consolePrinter.WriteSubString(consoleWriter, message, p1, p1 + 2); p0 = p1 + 2; } else { consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; } consolePrinter.ChangeForegroundColor(consoleWriter, currentColorConfig.Key, defaultForegroundColor); consolePrinter.ChangeBackgroundColor(consoleWriter, currentColorConfig.Value, defaultBackgroundColor); continue; } if (c1 != '\a' || p1 + 1 >= message.Length) { // Other control characters consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; continue; } // coloring control characters char c2 = message[p1 + 1]; if (c2 == '\a') { consolePrinter.WriteChar(consoleWriter, '\a'); p0 = p1 + 2; continue; } if (c2 == 'X') { var oldColorConfig = colorStack.Pop(); var newColorConfig = colorStack.Peek(); if (newColorConfig.Key != oldColorConfig.Key || newColorConfig.Value != oldColorConfig.Value) { if ((oldColorConfig.Key.HasValue && !newColorConfig.Key.HasValue) || (oldColorConfig.Value.HasValue && !newColorConfig.Value.HasValue)) { consolePrinter.ResetDefaultColors(consoleWriter, defaultForegroundColor, defaultBackgroundColor); } consolePrinter.ChangeForegroundColor(consoleWriter, newColorConfig.Key, oldColorConfig.Key); consolePrinter.ChangeBackgroundColor(consoleWriter, newColorConfig.Value, oldColorConfig.Value); } p0 = p1 + 2; continue; } var currentForegroundColor = colorStack.Peek().Key; var currentBackgroundColor = colorStack.Peek().Value; var foreground = (ConsoleOutputColor)(c2 - 'A'); var background = (ConsoleOutputColor)(message[p1 + 2] - 'A'); if (foreground != ConsoleOutputColor.NoChange) { currentForegroundColor = (ConsoleColor)foreground; consolePrinter.ChangeForegroundColor(consoleWriter, currentForegroundColor); } if (background != ConsoleOutputColor.NoChange) { currentBackgroundColor = (ConsoleColor)background; consolePrinter.ChangeBackgroundColor(consoleWriter, currentBackgroundColor); } colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(currentForegroundColor, currentBackgroundColor)); p0 = p1 + 3; } if (p0 < message.Length) { consolePrinter.WriteSubString(consoleWriter, message, p0, message.Length); } } private TextWriter GetOutput() { return ErrorStream ? Console.Error : Console.Out; } } } #endif
// ZipHelperStream.cs // // Copyright 2006 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This class assists with writing/reading from Zip files. /// </summary> internal class ZipHelperStream : Stream { #region Constructors /// <summary> /// Initialise an instance of this class. /// </summary> /// <param name="name">The name of the file to open.</param> public ZipHelperStream(string name) { stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); isOwner_ = true; } /// <summary> /// Initialise a new instance of <see cref="ZipHelperStream"/>. /// </summary> /// <param name="stream">The stream to use.</param> public ZipHelperStream(Stream stream) { stream_ = stream; } #endregion /// <summary> /// Get / set a value indicating wether the the underlying stream is owned or not. /// </summary> /// <remarks>If the stream is owned it is closed when this instance is closed.</remarks> public bool IsStreamOwner { get { return isOwner_; } set { isOwner_ = value; } } #region Base Stream Methods public override bool CanRead { get { return stream_.CanRead; } } public override bool CanSeek { get { return stream_.CanSeek; } } #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 public override bool CanTimeout { get { return stream_.CanTimeout; } } #endif public override long Length { get { return stream_.Length; } } public override long Position { get { return stream_.Position; } set { stream_.Position = value; } } public override bool CanWrite { get { return stream_.CanWrite; } } public override void Flush() { stream_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return stream_.Seek(offset, origin); } public override void SetLength(long value) { stream_.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return stream_.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { stream_.Write(buffer, offset, count); } #endregion // NOTE this returns the offset of the first byte after the signature. public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) { long pos = endLocation - minimumBlockSize; if ( pos < 0 ) { return -1; } long giveUpMarker = Math.Max(pos - maximumVariableData, 0); // TODO: This loop could be optimised for speed. do { if ( pos < giveUpMarker ) { return -1; } Seek(pos--, SeekOrigin.Begin); } while ( ReadLEInt() != signature ); return Position; } /// <summary> /// Write Zip64 end of central directory records (File header and locator). /// </summary> /// <param name="noOfEntries">The number of entries in the central directory.</param> /// <param name="sizeEntries">The size of entries in the central directory.</param> /// <param name="centralDirOffset">The offset of the dentral directory.</param> public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) { long centralSignatureOffset = stream_.Position; WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) WriteLEShort(ZipConstants.VersionMadeBy); // Version made by WriteLEShort(ZipConstants.VersionZip64); // Version to extract WriteLEInt(0); // Number of this disk WriteLEInt(0); // number of the disk with the start of the central directory WriteLELong(noOfEntries); // No of entries on this disk WriteLELong(noOfEntries); // Total No of entries in central directory WriteLELong(sizeEntries); // Size of the central directory WriteLELong(centralDirOffset); // offset of start of central directory // zip64 extensible data sector not catered for here (variable size) // Write the Zip64 end of central directory locator WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); // no of the disk with the start of the zip64 end of central directory WriteLEInt(0); // relative offset of the zip64 end of central directory record WriteLELong(centralSignatureOffset); // total number of disks WriteLEInt(1); } /// <summary> /// Write the required records to end the central directory. /// </summary> /// <param name="noOfEntries">The number of entries in the directory.</param> /// <param name="sizeEntries">The size of the entries in the directory.</param> /// <param name="startOfCentralDirectory">The start of the central directory.</param> /// <param name="comment">The archive comment. (This can be null).</param> public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, long startOfCentralDirectory, byte[] comment) { if ( (noOfEntries >= 0xffff) || (startOfCentralDirectory >= 0xffffffff) || (sizeEntries >= 0xffffffff) ) { WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); } WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); // TODO: ZipFile Multi disk handling not done WriteLEShort(0); // number of this disk WriteLEShort(0); // no of disk with start of central dir // Zip64 if ( noOfEntries >= 0xffff ) { WriteLEUshort(0xffff); WriteLEUshort(0xffff); } else { WriteLEShort(( short )noOfEntries); // entries in central dir for this disk WriteLEShort(( short )noOfEntries); // total entries in central directory } // Zip64 if ( sizeEntries >= 0xffffffff ) { WriteLEUint(0xffffffff); } else { WriteLEInt(( int )sizeEntries); // size of the central directory } // Zip64 if ( startOfCentralDirectory >= 0xffffffff ) { WriteLEUint(0xffffffff); // offset of start of central dir } else { WriteLEInt(( int )startOfCentralDirectory); // offset of start of central dir } int commentLength = (comment != null) ? comment.Length : 0; if ( commentLength > 0xffff ) { throw new ZipException(string.Format("Comment length({0}) is too long", commentLength)); } WriteLEShort(commentLength); if ( commentLength > 0 ) { Write(comment, 0, comment.Length); } } #region LE value reading/writing /// <summary> /// Read an unsigned short in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEShort() { return stream_.ReadByte() | (stream_.ReadByte() << 8); } /// <summary> /// Read an int in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="System.IO.EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEInt() { return ReadLEShort() | (ReadLEShort() << 16); } /// <summary> /// Read a long in little endian byte order. /// </summary> /// <returns>The value read.</returns> public long ReadLELong() { return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); } /// <summary> /// Write an unsigned short in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEShort(int value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )((value >> 8) & 0xff)); } /// <summary> /// Write a ushort in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUshort(ushort value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )(value >> 8)); } /// <summary> /// Write an int in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEInt(int value) { WriteLEShort(value); WriteLEShort(value >> 16); } /// <summary> /// Write a uint in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUint(uint value) { WriteLEUshort(( ushort )(value & 0xffff)); WriteLEUshort(( ushort )(value >> 16)); } /// <summary> /// Write a long in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLELong(long value) { WriteLEInt(( int )value); WriteLEInt(( int )(value >> 32)); } /// <summary> /// Write a ulong in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUlong(ulong value) { WriteLEUint(( uint )(value & 0xffffffff)); WriteLEUint(( uint )(value >> 32)); } /// <summary> /// Close the stream. /// </summary> override public void Close() { Stream toClose = stream_; stream_ = null; if ( isOwner_ && (toClose != null) ) { isOwner_ = false; toClose.Close(); } } #endregion #region Instance Fields bool isOwner_; Stream stream_; #endregion } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon 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. */ namespace OpenSim.GridLaunch.GUI.WinForm { partial class ProcessPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProcessPanel)); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabLogs = new System.Windows.Forms.TabPage(); this.btnShutdown = new System.Windows.Forms.Button(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.tabSettings = new System.Windows.Forms.TabPage(); this.cblStartupComponents = new System.Windows.Forms.CheckedListBox(); this.gbStartupComponents = new System.Windows.Forms.GroupBox(); this.btnSave = new System.Windows.Forms.Button(); this.ucLogWindow1 = new OpenSim.GridLaunch.GUI.WinForm.ucLogWindow(); this.label1 = new System.Windows.Forms.Label(); this.tabControl1.SuspendLayout(); this.tabLogs.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.tabSettings.SuspendLayout(); this.gbStartupComponents.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.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.tabControl1.Controls.Add(this.tabSettings); this.tabControl1.Controls.Add(this.tabLogs); this.tabControl1.Location = new System.Drawing.Point(-1, 123); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(632, 275); this.tabControl1.TabIndex = 0; // // tabLogs // this.tabLogs.Controls.Add(this.ucLogWindow1); this.tabLogs.Location = new System.Drawing.Point(4, 22); this.tabLogs.Name = "tabLogs"; this.tabLogs.Padding = new System.Windows.Forms.Padding(3); this.tabLogs.Size = new System.Drawing.Size(624, 249); this.tabLogs.TabIndex = 0; this.tabLogs.Text = "Logs"; this.tabLogs.UseVisualStyleBackColor = true; // // btnShutdown // this.btnShutdown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnShutdown.Location = new System.Drawing.Point(542, 400); this.btnShutdown.Name = "btnShutdown"; this.btnShutdown.Size = new System.Drawing.Size(75, 23); this.btnShutdown.TabIndex = 1; this.btnShutdown.Text = "Shutdown"; this.btnShutdown.UseVisualStyleBackColor = true; this.btnShutdown.Click += new System.EventHandler(this.btnShutdown_Click); // // pictureBox2 // this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(585, -1); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(46, 124); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 3; this.pictureBox2.TabStop = false; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(-1, -1); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(586, 124); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 2; this.pictureBox1.TabStop = false; // // pictureBox3 // this.pictureBox3.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.pictureBox3.Image = global::OpenSim.GridLaunch.Properties.Resources.OpenSim_Bottom_Border; this.pictureBox3.Location = new System.Drawing.Point(-1, 120); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(632, 310); this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox3.TabIndex = 4; this.pictureBox3.TabStop = false; // // tabSettings // this.tabSettings.Controls.Add(this.label1); this.tabSettings.Controls.Add(this.btnSave); this.tabSettings.Controls.Add(this.gbStartupComponents); this.tabSettings.Location = new System.Drawing.Point(4, 22); this.tabSettings.Name = "tabSettings"; this.tabSettings.Padding = new System.Windows.Forms.Padding(3); this.tabSettings.Size = new System.Drawing.Size(624, 249); this.tabSettings.TabIndex = 1; this.tabSettings.Text = "Settings"; this.tabSettings.UseVisualStyleBackColor = true; // // cblStartupComponents // this.cblStartupComponents.CheckOnClick = true; this.cblStartupComponents.FormattingEnabled = true; this.cblStartupComponents.Location = new System.Drawing.Point(6, 19); this.cblStartupComponents.Name = "cblStartupComponents"; this.cblStartupComponents.Size = new System.Drawing.Size(202, 109); this.cblStartupComponents.TabIndex = 0; // // gbStartupComponents // this.gbStartupComponents.Controls.Add(this.cblStartupComponents); this.gbStartupComponents.Location = new System.Drawing.Point(9, 6); this.gbStartupComponents.Name = "gbStartupComponents"; this.gbStartupComponents.Size = new System.Drawing.Size(214, 136); this.gbStartupComponents.TabIndex = 1; this.gbStartupComponents.TabStop = false; this.gbStartupComponents.Text = "Startup components"; // // btnSave // this.btnSave.Location = new System.Drawing.Point(9, 148); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(92, 23); this.btnSave.TabIndex = 2; this.btnSave.Text = "Save settings"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // ucLogWindow1 // this.ucLogWindow1.Dock = System.Windows.Forms.DockStyle.Fill; this.ucLogWindow1.Location = new System.Drawing.Point(3, 3); this.ucLogWindow1.Name = "ucLogWindow1"; this.ucLogWindow1.Size = new System.Drawing.Size(618, 243); this.ucLogWindow1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(108, 149); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(259, 13); this.label1.TabIndex = 3; this.label1.Text = "* You have to restart app before changes take effect."; // // ProcessPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(629, 428); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.btnShutdown); this.Controls.Add(this.tabControl1); this.Controls.Add(this.pictureBox3); this.Name = "ProcessPanel"; this.Text = "OpenSim GUI alpha"; this.Load += new System.EventHandler(this.ProcessPanel_Load); this.tabControl1.ResumeLayout(false); this.tabLogs.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.tabSettings.ResumeLayout(false); this.tabSettings.PerformLayout(); this.gbStartupComponents.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabLogs; private System.Windows.Forms.Button btnShutdown; private ucLogWindow ucLogWindow1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.TabPage tabSettings; private System.Windows.Forms.GroupBox gbStartupComponents; private System.Windows.Forms.CheckedListBox cblStartupComponents; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Label label1; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.SymbolMapping; using Microsoft.CodeAnalysis.FindReferences; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.FindReferences { internal abstract partial class AbstractFindReferencesService : ForegroundThreadAffinitizedObject, IFindReferencesService, IStreamingFindReferencesService { private readonly IEnumerable<IDefinitionsAndReferencesPresenter> _referenceSymbolPresenters; private readonly IEnumerable<INavigableItemsPresenter> _navigableItemPresenters; private readonly IEnumerable<IFindReferencesResultProvider> _externalReferencesProviders; protected AbstractFindReferencesService( IEnumerable<IDefinitionsAndReferencesPresenter> referenceSymbolPresenters, IEnumerable<INavigableItemsPresenter> navigableItemPresenters, IEnumerable<IFindReferencesResultProvider> externalReferencesProviders) { _referenceSymbolPresenters = referenceSymbolPresenters; _navigableItemPresenters = navigableItemPresenters; _externalReferencesProviders = externalReferencesProviders; } /// <summary> /// Common helper for both the synchronous and streaming versions of FAR. /// It returns the symbol we want to search for and the solution we should /// be searching. /// /// Note that the <see cref="Solution"/> returned may absolutely *not* be /// the same as <code>document.Project.Solution</code>. This is because /// there may be symbol mapping involved (for example in Metadata-As-Source /// scenarios). /// </summary> private async Task<Tuple<ISymbol, Project>> GetRelevantSymbolAndProjectAtPositionAsync( Document document, int position, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken: cancellationToken).ConfigureAwait(false); if (symbol == null) { return null; } // If this document is not in the primary workspace, we may want to search for results // in a solution different from the one we started in. Use the starting workspace's // ISymbolMappingService to get a context for searching in the proper solution. var mappingService = document.Project.Solution.Workspace.Services.GetService<ISymbolMappingService>(); var mapping = await mappingService.MapSymbolAsync(document, symbol, cancellationToken).ConfigureAwait(false); if (mapping == null) { return null; } return Tuple.Create(mapping.Symbol, mapping.Project); } /// <summary> /// Finds references using the externally defined <see cref="IFindReferencesResultProvider"/>s. /// </summary> private async Task AddExternalReferencesAsync(Document document, int position, ArrayBuilder<INavigableItem> builder, CancellationToken cancellationToken) { // CONSIDER: Do the computation in parallel. foreach (var provider in _externalReferencesProviders) { var references = await provider.FindReferencesAsync(document, position, cancellationToken).ConfigureAwait(false); if (references != null) { builder.AddRange(references.WhereNotNull()); } } } private async Task<Tuple<IEnumerable<ReferencedSymbol>, Solution>> FindReferencedSymbolsAsync( Document document, int position, IWaitContext waitContext) { var cancellationToken = waitContext.CancellationToken; var symbolAndProject = await GetRelevantSymbolAndProjectAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); if (symbolAndProject == null) { return null; } var symbol = symbolAndProject.Item1; var project = symbolAndProject.Item2; var displayName = GetDisplayName(symbol); waitContext.Message = string.Format( EditorFeaturesResources.Finding_references_of_0, displayName); var result = await SymbolFinder.FindReferencesAsync(symbol, project.Solution, cancellationToken).ConfigureAwait(false); return Tuple.Create(result, project.Solution); } private static string GetDisplayName(ISymbol symbol) { return symbol.IsConstructor() ? symbol.ContainingType.Name : symbol.Name; } public bool TryFindReferences(Document document, int position, IWaitContext waitContext) { var cancellationToken = waitContext.CancellationToken; var workspace = document.Project.Solution.Workspace; // First see if we have any external navigable item references. // If so, we display the results as navigable items. var succeeded = TryFindAndDisplayNavigableItemsReferencesAsync(document, position, waitContext).WaitAndGetResult(cancellationToken); if (succeeded) { return true; } // Otherwise, fall back to displaying SymbolFinder based references. var result = this.FindReferencedSymbolsAsync(document, position, waitContext).WaitAndGetResult(cancellationToken); return TryDisplayReferences(result); } /// <summary> /// Attempts to find and display navigable item references, including the references provided by external providers. /// </summary> /// <returns>False if there are no external references or display was not successful.</returns> private async Task<bool> TryFindAndDisplayNavigableItemsReferencesAsync(Document document, int position, IWaitContext waitContext) { var foundReferences = false; if (_externalReferencesProviders.Any()) { var cancellationToken = waitContext.CancellationToken; var builder = ArrayBuilder<INavigableItem>.GetInstance(); await AddExternalReferencesAsync(document, position, builder, cancellationToken).ConfigureAwait(false); // TODO: Merging references from SymbolFinder and external providers might lead to duplicate or counter-intuitive results. // TODO: For now, we avoid merging and just display the results either from SymbolFinder or the external result providers but not both. if (builder.Count > 0 && TryDisplayReferences(builder)) { foundReferences = true; } builder.Free(); } return foundReferences; } private bool TryDisplayReferences(IEnumerable<INavigableItem> result) { if (result != null && result.Any()) { var title = result.First().DisplayTaggedParts.JoinText(); foreach (var presenter in _navigableItemPresenters) { presenter.DisplayResult(title, result); return true; } } return false; } private bool TryDisplayReferences(Tuple<IEnumerable<ReferencedSymbol>, Solution> result) { if (result != null && result.Item1 != null) { var solution = result.Item2; var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>(); var definitionsAndReferences = factory.CreateDefinitionsAndReferences( solution, result.Item1); foreach (var presenter in _referenceSymbolPresenters) { presenter.DisplayResult(definitionsAndReferences); return true; } } return false; } public async Task FindReferencesAsync( Document document, int position, FindReferencesContext context) { // NOTE: All ConFigureAwaits in this method need to pass 'true' so that // we return to the caller's context. that's so the call to // CallThirdPartyExtensionsAsync will happen on the UI thread. We need // this to maintain the threading guarantee we had around that method // from pre-Roslyn days. var findReferencesProgress = await FindReferencesWorkerAsync( document, position, context).ConfigureAwait(true); if (findReferencesProgress == null) { return; } // After the FAR engine is done call into any third party extensions to see // if they want to add results. await findReferencesProgress.CallThirdPartyExtensionsAsync().ConfigureAwait(true); } private async Task<ProgressAdapter> FindReferencesWorkerAsync( Document document, int position, FindReferencesContext context) { var cancellationToken = context.CancellationToken; cancellationToken.ThrowIfCancellationRequested(); // Find the symbol we want to search and the solution we want to search in. var symbolAndProject = await GetRelevantSymbolAndProjectAtPositionAsync( document, position, cancellationToken).ConfigureAwait(false); if (symbolAndProject == null) { return null; } var symbol = symbolAndProject.Item1; var project = symbolAndProject.Item2; var displayName = GetDisplayName(symbol); context.SetSearchLabel(displayName); var progressAdapter = new ProgressAdapter(project.Solution, context); // Now call into the underlying FAR engine to find reference. The FAR // engine will push results into the 'progress' instance passed into it. // We'll take those results, massage them, and forward them along to the // FindReferencesContext instance we were given. await SymbolFinder.FindReferencesAsync( SymbolAndProjectId.Create(symbol, project.Id), project.Solution, progressAdapter, documents: null, cancellationToken: cancellationToken).ConfigureAwait(false); return progressAdapter; } } }