context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL) #region License /* * Cookie.cs * * This code is derived from System.Net.Cookie.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Lawrence Pit <loz@cable.a2000.nl> * - Gonzalo Paniagua Javier <gonzalo@ximian.com> * - Daniel Nauck <dna@mono-project.de> * - Sebastien Pouliot <sebastien@ximian.com> */ #endregion using System; using System.Globalization; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides a set of methods and properties used to manage an HTTP Cookie. /// </summary> /// <remarks> /// <para> /// The Cookie class supports the following cookie formats: /// <see href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">Netscape specification</see>, /// <see href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</see>, and /// <see href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</see> /// </para> /// <para> /// The Cookie class cannot be inherited. /// </para> /// </remarks> [Serializable] public sealed class Cookie { #region Private Fields private string _comment; private Uri _commentUri; private bool _discard; private string _domain; private DateTime _expires; private bool _httpOnly; private string _name; private string _path; private string _port; private int[] _ports; private static readonly char[] _reservedCharsForName; private static readonly char[] _reservedCharsForValue; private bool _secure; private DateTime _timestamp; private string _value; private int _version; #endregion #region Static Constructor static Cookie () { _reservedCharsForName = new[] { ' ', '=', ';', ',', '\n', '\r', '\t' }; _reservedCharsForValue = new[] { ';', ',' }; } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class. /// </summary> public Cookie () { _comment = String.Empty; _domain = String.Empty; _expires = DateTime.MinValue; _name = String.Empty; _path = String.Empty; _port = String.Empty; _ports = new int[0]; _timestamp = DateTime.Now; _value = String.Empty; _version = 0; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/> and <paramref name="value"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value) : this () { Name = name; Value = value; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/>, <paramref name="value"/>, and <paramref name="path"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <param name="path"> /// A <see cref="string"/> that represents the value of the Path attribute of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value, string path) : this (name, value) { Path = path; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/>, <paramref name="value"/>, <paramref name="path"/>, and /// <paramref name="domain"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <param name="path"> /// A <see cref="string"/> that represents the value of the Path attribute of the cookie. /// </param> /// <param name="domain"> /// A <see cref="string"/> that represents the value of the Domain attribute of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value, string path, string domain) : this (name, value, path) { Domain = domain; } #endregion #region Internal Properties internal bool ExactDomain { get; set; } internal int MaxAge { get { if (_expires == DateTime.MinValue) return 0; var expires = _expires.Kind != DateTimeKind.Local ? _expires.ToLocalTime () : _expires; var span = expires - DateTime.Now; return span > TimeSpan.Zero ? (int) span.TotalSeconds : 0; } } internal int[] Ports { get { return _ports; } } #endregion #region Public Properties /// <summary> /// Gets or sets the value of the Comment attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the comment to document intended use of the cookie. /// </value> public string Comment { get { return _comment; } set { _comment = value ?? String.Empty; } } /// <summary> /// Gets or sets the value of the CommentURL attribute of the cookie. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the URI that provides the comment to document intended /// use of the cookie. /// </value> public Uri CommentUri { get { return _commentUri; } set { _commentUri = value; } } /// <summary> /// Gets or sets a value indicating whether the client discards the cookie unconditionally /// when the client terminates. /// </summary> /// <value> /// <c>true</c> if the client discards the cookie unconditionally when the client terminates; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> public bool Discard { get { return _discard; } set { _discard = value; } } /// <summary> /// Gets or sets the value of the Domain attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the URI for which the cookie is valid. /// </value> public string Domain { get { return _domain; } set { if (value.IsNullOrEmpty ()) { _domain = String.Empty; ExactDomain = true; } else { _domain = value; ExactDomain = value[0] != '.'; } } } /// <summary> /// Gets or sets a value indicating whether the cookie has expired. /// </summary> /// <value> /// <c>true</c> if the cookie has expired; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool Expired { get { return _expires != DateTime.MinValue && _expires <= DateTime.Now; } set { _expires = value ? DateTime.Now : DateTime.MinValue; } } /// <summary> /// Gets or sets the value of the Expires attribute of the cookie. /// </summary> /// <value> /// A <see cref="DateTime"/> that represents the date and time at which the cookie expires. /// The default value is <see cref="DateTime.MinValue"/>. /// </value> public DateTime Expires { get { return _expires; } set { _expires = value; } } /// <summary> /// Gets or sets a value indicating whether non-HTTP APIs can access the cookie. /// </summary> /// <value> /// <c>true</c> if non-HTTP APIs cannot access the cookie; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool HttpOnly { get { return _httpOnly; } set { _httpOnly = value; } } /// <summary> /// Gets or sets the Name of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the Name of the cookie. /// </value> /// <exception cref="CookieException"> /// <para> /// The value specified for a set operation is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// The value specified for a set operation contains an invalid character. /// </para> /// </exception> public string Name { get { return _name; } set { string msg; if (!canSetName (value, out msg)) throw new CookieException (msg); _name = value; } } /// <summary> /// Gets or sets the value of the Path attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the subset of URI on the origin server /// to which the cookie applies. /// </value> public string Path { get { return _path; } set { _path = value ?? String.Empty; } } /// <summary> /// Gets or sets the value of the Port attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the list of TCP ports to which the cookie applies. /// </value> /// <exception cref="CookieException"> /// The value specified for a set operation isn't enclosed in double quotes or /// couldn't be parsed. /// </exception> public string Port { get { return _port; } set { if (value.IsNullOrEmpty ()) { _port = String.Empty; _ports = new int[0]; return; } if (!value.IsEnclosedIn ('"')) throw new CookieException ( "The value specified for the Port attribute isn't enclosed in double quotes."); string err; if (!tryCreatePorts (value, out _ports, out err)) throw new CookieException ( String.Format ( "The value specified for the Port attribute contains an invalid value: {0}", err)); _port = value; } } /// <summary> /// Gets or sets a value indicating whether the security level of the cookie is secure. /// </summary> /// <remarks> /// When this property is <c>true</c>, the cookie may be included in the HTTP request /// only if the request is transmitted over the HTTPS. /// </remarks> /// <value> /// <c>true</c> if the security level of the cookie is secure; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool Secure { get { return _secure; } set { _secure = value; } } /// <summary> /// Gets the time when the cookie was issued. /// </summary> /// <value> /// A <see cref="DateTime"/> that represents the time when the cookie was issued. /// </value> public DateTime TimeStamp { get { return _timestamp; } } /// <summary> /// Gets or sets the Value of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the Value of the cookie. /// </value> /// <exception cref="CookieException"> /// <para> /// The value specified for a set operation is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// The value specified for a set operation contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public string Value { get { return _value; } set { string msg; if (!canSetValue (value, out msg)) throw new CookieException (msg); _value = value.Length > 0 ? value : "\"\""; } } /// <summary> /// Gets or sets the value of the Version attribute of the cookie. /// </summary> /// <value> /// An <see cref="int"/> that represents the version of the HTTP state management /// to which the cookie conforms. /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation isn't 0 or 1. /// </exception> public int Version { get { return _version; } set { if (value < 0 || value > 1) throw new ArgumentOutOfRangeException ("value", "Not 0 or 1."); _version = value; } } #endregion #region Private Methods private static bool canSetName (string name, out string message) { if (name.IsNullOrEmpty ()) { message = "The value specified for the Name is null or empty."; return false; } if (name[0] == '$' || name.Contains (_reservedCharsForName)) { message = "The value specified for the Name contains an invalid character."; return false; } message = String.Empty; return true; } private static bool canSetValue (string value, out string message) { if (value == null) { message = "The value specified for the Value is null."; return false; } if (value.Contains (_reservedCharsForValue) && !value.IsEnclosedIn ('"')) { message = "The value specified for the Value contains an invalid character."; return false; } message = String.Empty; return true; } private static int hash (int i, int j, int k, int l, int m) { return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25) ^ (m << 20 | m >> 12); } private string toResponseStringVersion0 () { var output = new StringBuilder (64); output.AppendFormat ("{0}={1}", _name, _value); if (_expires != DateTime.MinValue) output.AppendFormat ( "; Expires={0}", _expires.ToUniversalTime ().ToString ( "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", CultureInfo.CreateSpecificCulture ("en-US"))); if (!_path.IsNullOrEmpty ()) output.AppendFormat ("; Path={0}", _path); if (!_domain.IsNullOrEmpty ()) output.AppendFormat ("; Domain={0}", _domain); if (_secure) output.Append ("; Secure"); if (_httpOnly) output.Append ("; HttpOnly"); return output.ToString (); } private string toResponseStringVersion1 () { var output = new StringBuilder (64); output.AppendFormat ("{0}={1}; Version={2}", _name, _value, _version); if (_expires != DateTime.MinValue) output.AppendFormat ("; Max-Age={0}", MaxAge); if (!_path.IsNullOrEmpty ()) output.AppendFormat ("; Path={0}", _path); if (!_domain.IsNullOrEmpty ()) output.AppendFormat ("; Domain={0}", _domain); if (!_port.IsNullOrEmpty ()) { if (_port == "\"\"") output.Append ("; Port"); else output.AppendFormat ("; Port={0}", _port); } if (!_comment.IsNullOrEmpty ()) output.AppendFormat ("; Comment={0}", _comment.UrlEncode ()); if (_commentUri != null) { var url = _commentUri.OriginalString; output.AppendFormat ("; CommentURL={0}", url.IsToken () ? url : url.Quote ()); } if (_discard) output.Append ("; Discard"); if (_secure) output.Append ("; Secure"); return output.ToString (); } private static bool tryCreatePorts (string value, out int[] result, out string parseError) { var ports = value.Trim ('"').Split (','); var len = ports.Length; var res = new int[len]; for (var i = 0; i < len; i++) { res[i] = Int32.MinValue; var port = ports[i].Trim (); if (port.Length == 0) continue; if (!Int32.TryParse (port, out res[i])) { result = new int[0]; parseError = port; return false; } } result = res; parseError = String.Empty; return true; } #endregion #region Internal Methods // From client to server internal string ToRequestString (Uri uri) { if (_name.Length == 0) return String.Empty; if (_version == 0) return String.Format ("{0}={1}", _name, _value); var output = new StringBuilder (64); output.AppendFormat ("$Version={0}; {1}={2}", _version, _name, _value); if (!_path.IsNullOrEmpty ()) output.AppendFormat ("; $Path={0}", _path); else if (uri != null) output.AppendFormat ("; $Path={0}", uri.GetAbsolutePath ()); else output.Append ("; $Path=/"); var appendDomain = uri == null || uri.Host != _domain; if (appendDomain && !_domain.IsNullOrEmpty ()) output.AppendFormat ("; $Domain={0}", _domain); if (!_port.IsNullOrEmpty ()) { if (_port == "\"\"") output.Append ("; $Port"); else output.AppendFormat ("; $Port={0}", _port); } return output.ToString (); } // From server to client internal string ToResponseString () { return _name.Length > 0 ? (_version == 0 ? toResponseStringVersion0 () : toResponseStringVersion1 ()) : String.Empty; } #endregion #region Public Methods /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to the current /// <see cref="Cookie"/>. /// </summary> /// <param name="comparand"> /// An <see cref="Object"/> to compare with the current <see cref="Cookie"/>. /// </param> /// <returns> /// <c>true</c> if <paramref name="comparand"/> is equal to the current <see cref="Cookie"/>; /// otherwise, <c>false</c>. /// </returns> public override bool Equals (Object comparand) { var cookie = comparand as Cookie; return cookie != null && _name.Equals (cookie.Name, StringComparison.InvariantCultureIgnoreCase) && _value.Equals (cookie.Value, StringComparison.InvariantCulture) && _path.Equals (cookie.Path, StringComparison.InvariantCulture) && _domain.Equals (cookie.Domain, StringComparison.InvariantCultureIgnoreCase) && _version == cookie.Version; } /// <summary> /// Serves as a hash function for a <see cref="Cookie"/> object. /// </summary> /// <returns> /// An <see cref="int"/> that represents the hash code for the current <see cref="Cookie"/>. /// </returns> public override int GetHashCode () { return hash ( StringComparer.InvariantCultureIgnoreCase.GetHashCode (_name), _value.GetHashCode (), _path.GetHashCode (), StringComparer.InvariantCultureIgnoreCase.GetHashCode (_domain), _version); } /// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="Cookie"/>. /// </summary> /// <remarks> /// This method returns a <see cref="string"/> to use to send an HTTP Cookie to /// an origin server. /// </remarks> /// <returns> /// A <see cref="string"/> that represents the current <see cref="Cookie"/>. /// </returns> public override string ToString () { // i.e., only used for clients // See para 4.2.2 of RFC 2109 and para 3.3.4 of RFC 2965 // See also bug #316017 return ToRequestString (null); } #endregion } } #endif
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC 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 Tiraggo.Interfaces; namespace Tiraggo.LoaderMT { public class tgDataProviderFactory : IDataProviderFactory { /// <summary> /// Called by the tgProviderFactory to get the proper data provider to carry /// out a particular request agains the database /// </summary> /// <param name="providerName">This is the "provider" element from an EntitySpaces connection entry</param> /// <param name="providerClass">This is the "providerClass" element from an EntitySpaces connection entry</param> /// <returns></returns> public IDataProvider GetDataProvider(string providerName, string providerClass) { IDataProvider provider = null; // This may seem like a funny way to write this routine however, by calling to these // sub functions this LoaderMT can run without the actual unused providers being present // even though we are bound to them. This is because the assemblies are loaded when they // are first accessed. And this first access occurs when a method is called that uses // code from a given assembly. Therefore, these sub functions such as LoadSqlClientProvider() // make sure our GetDataProvider doesn't actually itself "new" any of the providers. switch (providerName) { case "Tiraggo.SqlClientProvider": try { return LoadSqlClientProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.SqlServerCeProvider": try { return LoadSqlServerCeProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.SqlServerCe4Provider": try { return LoadSqlServerCe4Provider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.OracleClientProvider": try { return LoadOracleClientProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.MSAccessProvider": try { return LoadMSAccessProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.MySqlClientProvider": try { return LoadMySqlClientProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.VistaDB4Provider": try { return LoadVistaDB4Provider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.Npgsql2Provider": try { return LoadNpgsql2Provider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.SybaseSqlAnywhereProvider": try { return LoadSybaseSQLAnywhereProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } case "Tiraggo.SQLiteProvider": try { return this.LoadSQLiteProvider(providerClass); } catch { throw new Exception("Unable to Find " + providerName + ".dll"); } } return provider; } private IDataProvider LoadSqlClientProvider(string providerClass) { if(sqlClientProvider == null) sqlClientProvider = new Tiraggo.SqlClientProvider.DataProvider(); return sqlClientProvider; } private IDataProvider LoadSqlServerCeProvider(string providerClass) { if (sqlCeDesktopProvider == null) sqlCeDesktopProvider = new Tiraggo.SqlServerCeProvider.DataProvider(); return sqlCeDesktopProvider; } private IDataProvider LoadSqlServerCe4Provider(string providerClass) { if (sqlCe4DesktopProvider == null) sqlCe4DesktopProvider = new Tiraggo.SqlServerCe4Provider.DataProvider(); return sqlCe4DesktopProvider; } private IDataProvider LoadOracleClientProvider(string providerClass) { if (oracleClientProvider == null) oracleClientProvider = new Tiraggo.OracleClientProvider.DataProvider(); return oracleClientProvider; } private IDataProvider LoadMSAccessProvider(string providerClass) { if (msAccessProvider == null) msAccessProvider = new Tiraggo.MSAccessProvider.DataProvider(); return msAccessProvider; } private IDataProvider LoadMySqlClientProvider(string providerClass) { if (mySqlClientProvider == null) mySqlClientProvider = new Tiraggo.MySqlClientProvider.DataProvider(); return mySqlClientProvider; } private IDataProvider LoadVistaDB4Provider(string providerClass) { if (vistaDB4Provider == null) vistaDB4Provider = new Tiraggo.VistaDB4Provider.DataProvider(); return vistaDB4Provider; } private IDataProvider LoadNpgsql2Provider(string providerClass) { if (npgsql2Provider == null) npgsql2Provider = new Tiraggo.Npgsql2Provider.DataProvider(); return npgsql2Provider; } private IDataProvider LoadSybaseSQLAnywhereProvider(string providerClass) { if (sybaseProvider == null) sybaseProvider = new Tiraggo.SybaseSqlAnywhereProvider.DataProvider(); return sybaseProvider; } private IDataProvider LoadSQLiteProvider(string providerClass) { if (sqliteProvider == null) sqliteProvider = new Tiraggo.SQLiteProvider.DataProvider(); return sqliteProvider; } private IDataProvider sqlClientProvider; private IDataProvider sqlCeDesktopProvider; private IDataProvider sqlCe4DesktopProvider; private IDataProvider msAccessProvider; private IDataProvider oracleClientProvider; private IDataProvider mySqlClientProvider; private IDataProvider vistaDB4Provider; private IDataProvider npgsql2Provider; private IDataProvider sybaseProvider; private IDataProvider sqliteProvider; } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kinesis-2013-12-02.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.Kinesis; using Amazon.Kinesis.Model; using Amazon.Kinesis.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class KinesisMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("kinesis-2013-12-02.normal.json", "kinesis.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void AddTagsToStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<AddTagsToStreamRequest>(); var marshaller = new AddTagsToStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AddTagsToStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void CreateStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateStreamRequest>(); var marshaller = new CreateStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void DecreaseStreamRetentionPeriodMarshallTest() { var request = InstantiateClassGenerator.Execute<DecreaseStreamRetentionPeriodRequest>(); var marshaller = new DecreaseStreamRetentionPeriodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DecreaseStreamRetentionPeriodRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void DeleteStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteStreamRequest>(); var marshaller = new DeleteStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void DescribeStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeStreamRequest>(); var marshaller = new DescribeStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStreamRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeStream").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeStreamResponseUnmarshaller.Instance.Unmarshall(context) as DescribeStreamResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void GetRecordsMarshallTest() { var request = InstantiateClassGenerator.Execute<GetRecordsRequest>(); var marshaller = new GetRecordsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetRecordsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetRecords").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetRecordsResponseUnmarshaller.Instance.Unmarshall(context) as GetRecordsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void GetShardIteratorMarshallTest() { var request = InstantiateClassGenerator.Execute<GetShardIteratorRequest>(); var marshaller = new GetShardIteratorRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetShardIteratorRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetShardIterator").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetShardIteratorResponseUnmarshaller.Instance.Unmarshall(context) as GetShardIteratorResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void IncreaseStreamRetentionPeriodMarshallTest() { var request = InstantiateClassGenerator.Execute<IncreaseStreamRetentionPeriodRequest>(); var marshaller = new IncreaseStreamRetentionPeriodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<IncreaseStreamRetentionPeriodRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void ListStreamsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListStreamsRequest>(); var marshaller = new ListStreamsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListStreamsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListStreams").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListStreamsResponseUnmarshaller.Instance.Unmarshall(context) as ListStreamsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void ListTagsForStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<ListTagsForStreamRequest>(); var marshaller = new ListTagsForStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTagsForStreamRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListTagsForStream").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListTagsForStreamResponseUnmarshaller.Instance.Unmarshall(context) as ListTagsForStreamResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void MergeShardsMarshallTest() { var request = InstantiateClassGenerator.Execute<MergeShardsRequest>(); var marshaller = new MergeShardsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<MergeShardsRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void PutRecordMarshallTest() { var request = InstantiateClassGenerator.Execute<PutRecordRequest>(); var marshaller = new PutRecordRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutRecordRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutRecord").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutRecordResponseUnmarshaller.Instance.Unmarshall(context) as PutRecordResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void PutRecordsMarshallTest() { var request = InstantiateClassGenerator.Execute<PutRecordsRequest>(); var marshaller = new PutRecordsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutRecordsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutRecords").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutRecordsResponseUnmarshaller.Instance.Unmarshall(context) as PutRecordsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void RemoveTagsFromStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<RemoveTagsFromStreamRequest>(); var marshaller = new RemoveTagsFromStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<RemoveTagsFromStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("Kinesis")] public void SplitShardMarshallTest() { var request = InstantiateClassGenerator.Execute<SplitShardRequest>(); var marshaller = new SplitShardRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SplitShardRequest>(request,jsonRequest); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Streams { [Serializable] [Immutable] [GenerateSerializer] [SerializationCallbacks(typeof(OnDeserializedCallbacks))] internal sealed class StreamImpl<T> : IAsyncStream<T>, IStreamControl, IOnDeserialized { [Id(1)] private readonly InternalStreamId streamId; [Id(2)] private readonly bool isRewindable; [NonSerialized] private IInternalStreamProvider provider; [NonSerialized] private volatile IInternalAsyncBatchObserver<T> producerInterface; [NonSerialized] private IInternalAsyncObservable<T> consumerInterface; [NonSerialized] private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo. [NonSerialized] private IRuntimeClient runtimeClient; internal InternalStreamId InternalStreamId { get { return streamId; } } public StreamId StreamId => streamId; public bool IsRewindable { get { return isRewindable; } } public string ProviderName { get { return streamId.ProviderName; } } // IMPORTANT: This constructor needs to be public for Json deserialization to work. public StreamImpl() { initLock = new object(); } internal StreamImpl(InternalStreamId streamId, IInternalStreamProvider provider, bool isRewindable, IRuntimeClient runtimeClient) { this.streamId = streamId; this.provider = provider ?? throw new ArgumentNullException(nameof(provider)); this.runtimeClient = runtimeClient ?? throw new ArgumentNullException(nameof(runtimeClient)); producerInterface = null; consumerInterface = null; initLock = new object(); this.isRewindable = isRewindable; } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return GetConsumerInterface().SubscribeAsync(observer, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token, string filterData = null) { return GetConsumerInterface().SubscribeAsync(observer, token, filterData); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver) { return GetConsumerInterface().SubscribeAsync(batchObserver); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token) { return GetConsumerInterface().SubscribeAsync(batchObserver, token); } public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers) { // Cleanup producers if (cleanupProducers && producerInterface != null) { await producerInterface.Cleanup(); producerInterface = null; } // Cleanup consumers if (cleanupConsumers && consumerInterface != null) { await consumerInterface.Cleanup(); consumerInterface = null; } } public Task OnNextAsync(T item, StreamSequenceToken token = null) { return GetProducerInterface().OnNextAsync(item, token); } public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token) { return GetProducerInterface().OnNextBatchAsync(batch, token); } public Task OnCompletedAsync() { IInternalAsyncBatchObserver<T> producerInterface = GetProducerInterface(); return producerInterface.OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { IInternalAsyncBatchObserver<T> producerInterface = GetProducerInterface(); return producerInterface.OnErrorAsync(ex); } internal Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token) { return GetConsumerInterface().ResumeAsync(handle, observer, token); } internal Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncBatchObserver<T> observer, StreamSequenceToken token) { return GetConsumerInterface().ResumeAsync(handle, observer, token); } public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles() { return GetConsumerInterface().GetAllSubscriptions(); } internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { return GetConsumerInterface().UnsubscribeAsync(handle); } internal IInternalAsyncBatchObserver<T> GetProducerInterface() { if (producerInterface != null) return producerInterface; lock (initLock) { if (producerInterface != null) return producerInterface; if (provider == null) provider = GetStreamProvider(); producerInterface = provider.GetProducerInterface(this); } return producerInterface; } internal IInternalAsyncObservable<T> GetConsumerInterface() { if (consumerInterface == null) { lock (initLock) { if (consumerInterface == null) { if (provider == null) provider = GetStreamProvider(); consumerInterface = provider.GetConsumerInterface(this); } } } return consumerInterface; } private IInternalStreamProvider GetStreamProvider() { return this.runtimeClient.ServiceProvider.GetRequiredServiceByName<IStreamProvider>(streamId.ProviderName) as IInternalStreamProvider; } public int CompareTo(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o == null ? 1 : streamId.CompareTo(o.streamId); } public bool Equals(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } public override bool Equals(object obj) { var o = obj as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } public override int GetHashCode() { return streamId.GetHashCode(); } public override string ToString() { return streamId.ToString(); } void IOnDeserialized.OnDeserialized(DeserializationContext context) { this.runtimeClient = context?.RuntimeClient as IRuntimeClient; } } }
//----------------------------------------------------------------------- // <copyright file="ResultsDialog.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Windows.Forms; using TQVaultAE.GUI.Tooltip; using TQVaultAE.GUI.Models; using TQVaultAE.Entities; using TQVaultAE.Presentation; using TQVaultAE.Presentation.Html; using TQVaultAE.Services.Models.Search; namespace TQVaultAE.GUI { /// <summary> /// Results dialog form class /// </summary> internal partial class ResultsDialog : VaultForm { /// <summary> /// List of all results /// </summary> private List<Result> resultsList; /// <summary> /// User selected result from the list /// </summary> private Result selectedResult; /// <summary> /// Search string passed from user /// </summary> private string searchString; /// <summary> /// Instance of the popup tool tip. /// </summary> private TTLib tooltip; /// <summary> /// Text for Tooltip control /// </summary> private string tooltipText; /// <summary> /// Initializes a new instance of the ResultsDialog class. /// </summary> public ResultsDialog() { this.InitializeComponent(); #region Apply custom font this.resultsDataGridView.ColumnHeadersDefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.item.DefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.quality.DefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.containerName.DefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.containerType.DefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.level.DefaultCellStyle.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Font = FontHelper.GetFontAlbertusMT(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); #endregion this.tooltip = new TTLib(); this.resultsList = new List<Result>(); ////this.selectedResult = new Result(); this.item.HeaderText = Resources.ResultsItem; this.containerName.HeaderText = Resources.ResultsContainer; this.containerType.HeaderText = Resources.ResultsContainerType; this.quality.HeaderText = Resources.ResultsQuality; this.level.HeaderText = Resources.ResultsLevel; this.DrawCustomBorder = true; this.FormDesignRatio = 0.0F; //// (float)this.Height / (float)this.Width; ////this.FormMaximumSize = new Size(this.Width * 2, this.Height * 2); ////this.FormMinimumSize = new Size( ////Convert.ToInt32((float)this.Width * 0.4F), ////Convert.ToInt32((float)this.Height * 0.4F)); this.OriginalFormSize = this.Size; this.OriginalFormScale = 1.0F; this.LastFormSize = this.Size; } /// <summary> /// Event Handler for the ResultChanged event. /// </summary> /// <typeparam name="ResultChangedEventArgs">ResultChangedEventArgs type</typeparam> /// <param name="sender">sender object</param> /// <param name="e">ResultChangedEventArgs data</param> public delegate void EventHandler<ResultChangedEventArgs>(object sender, ResultChangedEventArgs e); /// <summary> /// Event for changing to a different highlighted result. /// </summary> public event EventHandler<ResultChangedEventArgs> ResultChanged; /// <summary> /// Gets the list of results collection /// </summary> public List<Result> ResultsList { get { return this.resultsList; } } /// <summary> /// Sets the user search string /// </summary> public string SearchString { set { this.searchString = value; } } /// <summary> /// Gets the string name for the corresponding SackType /// </summary> /// <param name="containterType">SackType which we are looking up</param> /// <returns>string containing the sack type</returns> private static string GetContainerTypeString(SackType containterType) { switch (containterType) { case SackType.Vault: return Resources.ResultsContainerVault; case SackType.Player: return Resources.ResultsContainerPlayer; case SackType.Equipment: return Resources.ResultsContainerEquip; case SackType.Stash: return Resources.ResultsContainerStash; case SackType.TransferStash: return Resources.GlobalTransferStash; case SackType.RelicVaultStash: return Resources.GlobalRelicVaultStash; default: return "Unknown"; } } /// <summary> /// Handler for showing the results dialog. /// Populates the data grid view. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ResultsDialogShown(object sender, EventArgs e) { this.PopulateDataGridView(); int totalWidth = 0; foreach (DataGridViewColumn column in this.resultsDataGridView.Columns) { totalWidth += column.Width; } totalWidth += this.resultsDataGridView.Margin.Horizontal; int totalHeight = 0; foreach (DataGridViewRow row in this.resultsDataGridView.Rows) { totalHeight += row.Height; } totalHeight += this.Padding.Vertical; if (totalHeight > this.Height) { totalWidth += SystemInformation.VerticalScrollBarWidth; } this.Width = Math.Min(Screen.PrimaryScreen.WorkingArea.Width, totalWidth + this.Padding.Horizontal); this.Height = Math.Max(this.Height, Math.Min(Screen.PrimaryScreen.WorkingArea.Height - SystemInformation.HorizontalScrollBarHeight, totalHeight - SystemInformation.HorizontalScrollBarHeight)); this.Location = new Point(this.Location.X, (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2); this.selectedResult = null; // the tooltip must be initialized after the main form is shown and active. this.tooltip.Initialize(this); this.tooltip.ActivateCallback = new TTLibToolTipActivate(this.ToolTipCallback); } /// <summary> /// Tooltip callback /// </summary> /// <param name="windowHandle">handle of this window form</param> /// <returns>tooltip string</returns> private string ToolTipCallback(int windowHandle) { // see if this is us if (this.resultsDataGridView.Handle.ToInt32() == windowHandle) { // yep. return this.GetToolTip(this.selectedResult); } return null; } /// <summary> /// Returns a string containing the tool tip text for the highlighted result. /// </summary> /// <param name="selectedResult">Currently selected Result</param> /// <returns>String containing the tool tip for the Result.</returns> private string GetToolTip(Result selectedResult) { if (selectedResult == null || selectedResult.Item == null) { // hide the tooltip this.tooltipText = null; } else { var result = ItemHtmlHelper.NewItemHighlightedTooltip(selectedResult.Item); // show tooltip this.tooltipText = result.TooltipText; } return this.tooltipText; } /// <summary> /// Populates the data grid view from the results list. /// </summary> private void PopulateDataGridView() { if (this.resultsList == null || this.resultsList.Count < 1) { return; } // Update the dialog text. this.Text = string.Format(CultureInfo.CurrentCulture, Resources.ResultsText, this.resultsList.Count, this.searchString); for (int i = 0; i < this.resultsList.Count; i++) { Result result = this.resultsList[i]; // Add the result to the DataGridView int currentRow = this.resultsDataGridView.Rows.Add( result.ItemName, result.ItemStyle, result.ContainerName, GetContainerTypeString(result.SackType), result.RequiredLevel ); // Change the text color of the item string and style to match the style color. if (currentRow > -1) { this.resultsDataGridView.Rows[currentRow].Cells[0].Style.ForeColor = result.Color; this.resultsDataGridView.Rows[currentRow].Cells[1].Style.ForeColor = result.Color; this.resultsDataGridView.Rows[currentRow].Cells[4].Style.Alignment = DataGridViewContentAlignment.MiddleRight; this.resultsDataGridView.Rows[currentRow].Tag = i; } } } /// <summary> /// Handler for user clicking on one of the result cells /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DataGridViewCellEventArgs data</param> private void ResultsDataGridViewCellDoubleClick(object sender, DataGridViewCellEventArgs e) { // Ignore double click on the header. if (e.RowIndex < 0) { return; } this.Close(); } /// <summary> /// Handler for pressing a key /// </summary> /// <param name="sender">sender object</param> /// <param name="e">KeyPressEventArgs data</param> private void ResultsDataGridViewKeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 27) { // Escape key this.Close(); } /*if (e.KeyChar == 13) { // Enter key if (this.resultsList.Count == 1) { this.selectedResult = this.resultsList[0]; this.Close(); } else { int index = this.resultsDataGridView.SelectedRows[0].Index - 1; if (index > -1 && index < this.resultsDataGridView.Rows.Count) { this.selectedResult = this.resultsList[index]; if (this.selectedResult.Item != null) { this.Close(); } } } }*/ } /// <summary> /// Handler for the focus changing to a different row. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DataGridViewCellEventArgs data</param> private void ResultsDataGridViewRowEnter(object sender, DataGridViewCellEventArgs e) { // Ignore click on the header. if (e.RowIndex < 0) { return; } var currentRow = this.resultsDataGridView.Rows[e.RowIndex]; if (currentRow.Tag == null) { return; } this.selectedResult = this.resultsList[(int)currentRow.Tag]; if (this.selectedResult.Item != null && this.ResultChanged != null) { this.ResultChanged(this, new ResultChangedEventArgs(this.selectedResult)); } ////if (!string.IsNullOrEmpty(this.tooltipText)) ////{ ////this.tooltip.ChangeText(this.GetToolTip()); ////} } /// <summary> /// Handler for the mouse leaving the DataGridView. Used to clear the tooltip. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ResultsDataGridViewMouseLeave(object sender, EventArgs e) { this.tooltipText = null; this.tooltip.ChangeText(this.tooltipText); } /// <summary> /// Handler for entering a cell in the DataGridView. /// Used to highlight the row under the mouse and updating the tool tip text. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DataGridViewCellEventArgs data</param> private void ResultsDataGridViewCellMouseEnter(object sender, DataGridViewCellEventArgs e) { // Ignore click on the header. if (e.RowIndex < 0) { return; } var currentRow = this.resultsDataGridView.Rows[e.RowIndex]; if (currentRow.Tag == null) { return; } this.selectedResult = this.resultsList[(int)currentRow.Tag]; this.resultsDataGridView.CurrentCell = currentRow.Cells[e.ColumnIndex]; this.tooltip.ChangeText(this.GetToolTip(this.selectedResult)); } /// <summary> /// Handler for the mouse leaving a DataGridView cell. /// Used to clear the tool tip and the selected result. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DataGridViewCellEventArgs data</param> private void ResultsDataGridViewCellMouseLeave(object sender, DataGridViewCellEventArgs e) { this.selectedResult = null; this.tooltipText = null; this.tooltip.ChangeText(this.tooltipText); } /// <summary> /// Handler for leaving a DataGridView row. /// Used to clear the tool tip and the selected result. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DataGridViewCellEventArgs data</param> private void ResultsDataGridViewRowLeave(object sender, DataGridViewCellEventArgs e) { this.selectedResult = null; this.tooltipText = null; this.tooltip.ChangeText(this.tooltipText); } /// <summary> /// Handler for Resizing the Results Dialog Form. Resizes the DataGridView based on the Results Dialog size. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ResultsDialog_Resize(object sender, EventArgs e) { this.resultsDataGridView.Size = new Size( Math.Max(this.Padding.Horizontal + 1, this.Width - this.Padding.Horizontal), Math.Max(this.Padding.Vertical + 1, this.Height - this.Padding.Vertical)); } } }
// 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.IO; using System.Linq; using System.Security; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType { internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged { private Document _document; private INotificationService _notificationService; private IProjectManagementService _projectManagementService; private ISyntaxFactsService _syntaxFactsService; private IGeneratedCodeRecognitionService _generatedCodeService; private GenerateTypeDialogOptions _generateTypeDialogOptions; private string _typeName; private bool _isNewFile; private Dictionary<string, Accessibility> _accessListMap; private Dictionary<string, TypeKind> _typeKindMap; private List<string> _csharpAccessList; private List<string> _visualBasicAccessList; private List<string> _csharpTypeKindList; private List<string> _visualBasicTypeKindList; private string _csharpExtension = ".cs"; private string _visualBasicExtension = ".vb"; // reserved names that cannot be a folder name or filename private string[] _reservedKeywords = new string[] { "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$" }; // Below code details with the Access List and the manipulation public List<string> AccessList { get; private set; } private int _accessSelectIndex; public int AccessSelectIndex { get { return _accessSelectIndex; } set { SetProperty(ref _accessSelectIndex, value); } } private string _selectedAccessibilityString; public string SelectedAccessibilityString { get { return _selectedAccessibilityString; } set { SetProperty(ref _selectedAccessibilityString, value); } } public Accessibility SelectedAccessibility { get { Contract.Assert(_accessListMap.ContainsKey(SelectedAccessibilityString), "The Accessibility Key String not present"); return _accessListMap[SelectedAccessibilityString]; } } private List<string> _kindList; public List<string> KindList { get { return _kindList; } set { SetProperty(ref _kindList, value); } } private int _kindSelectIndex; public int KindSelectIndex { get { return _kindSelectIndex; } set { SetProperty(ref _kindSelectIndex, value); } } private string _selectedTypeKindString; public string SelectedTypeKindString { get { return _selectedTypeKindString; } set { SetProperty(ref _selectedTypeKindString, value); } } public TypeKind SelectedTypeKind { get { Contract.Assert(_typeKindMap.ContainsKey(SelectedTypeKindString), "The TypeKind Key String not present"); return _typeKindMap[SelectedTypeKindString]; } } private void PopulateTypeKind(TypeKind typeKind, string csharpkKey, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _typeKindMap.Add(csharpkKey, typeKind); _csharpTypeKindList.Add(csharpkKey); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateTypeKind(TypeKind typeKind, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateAccessList(string key, Accessibility accessibility, string languageName = null) { if (languageName == null) { _csharpAccessList.Add(key); _visualBasicAccessList.Add(key); } else if (languageName == LanguageNames.CSharp) { _csharpAccessList.Add(key); } else { Contract.Assert(languageName == LanguageNames.VisualBasic, "Currently only C# and VB are supported"); _visualBasicAccessList.Add(key); } _accessListMap.Add(key, accessibility); } private void InitialSetup(string languageName) { _accessListMap = new Dictionary<string, Accessibility>(); _typeKindMap = new Dictionary<string, TypeKind>(); _csharpAccessList = new List<string>(); _visualBasicAccessList = new List<string>(); _csharpTypeKindList = new List<string>(); _visualBasicTypeKindList = new List<string>(); // Populate the AccessListMap if (!_generateTypeDialogOptions.IsPublicOnlyAccessibility) { PopulateAccessList("Default", Accessibility.NotApplicable); PopulateAccessList("internal", Accessibility.Internal, LanguageNames.CSharp); PopulateAccessList("Friend", Accessibility.Internal, LanguageNames.VisualBasic); } PopulateAccessList("public", Accessibility.Public, LanguageNames.CSharp); PopulateAccessList("Public", Accessibility.Public, LanguageNames.VisualBasic); // Populate the TypeKind PopulateTypeKind(); } private void PopulateTypeKind() { Contract.Assert(_generateTypeDialogOptions.TypeKindOptions != TypeKindOptions.None); if (TypeKindOptionsHelper.IsClass(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Class, "class", "Class"); } if (TypeKindOptionsHelper.IsEnum(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Enum, "enum", "Enum"); } if (TypeKindOptionsHelper.IsStructure(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Structure, "struct", "Structure"); } if (TypeKindOptionsHelper.IsInterface(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Interface, "interface", "Interface"); } if (TypeKindOptionsHelper.IsDelegate(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Delegate, "delegate", "Delegate"); } if (TypeKindOptionsHelper.IsModule(_generateTypeDialogOptions.TypeKindOptions)) { _shouldChangeTypeKindListSelectedIndex = true; PopulateTypeKind(TypeKind.Module, "Module"); } } internal bool TrySubmit() { if (this.IsNewFile) { var trimmedFileName = FileName.Trim(); // Case : \\Something if (trimmedFileName.StartsWith("\\\\")) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } // Case : something\ if (string.IsNullOrWhiteSpace(trimmedFileName) || trimmedFileName.EndsWith("\\")) { SendFailureNotification(ServicesVSResources.PathCannotHaveEmptyFileName); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } var isRootOfTheProject = trimmedFileName.StartsWith("\\"); string implicitFilePath = null; // Construct the implicit file path if (isRootOfTheProject || this.SelectedProject != _document.Project) { if (!TryGetImplicitFilePath(this.SelectedProject.FilePath ?? string.Empty, ServicesVSResources.IllegalPathForProject, out implicitFilePath)) { return false; } } else { if (!TryGetImplicitFilePath(_document.FilePath, ServicesVSResources.IllegalPathForDocument, out implicitFilePath)) { return false; } } // Remove the '\' at the beginning if present trimmedFileName = trimmedFileName.StartsWith("\\") ? trimmedFileName.Substring(1) : trimmedFileName; // Construct the full path of the file to be created this.FullFilePath = implicitFilePath + "\\" + trimmedFileName; try { this.FullFilePath = Path.GetFullPath(this.FullFilePath); } catch (ArgumentNullException e) { SendFailureNotification(e.Message); return false; } catch (ArgumentException e) { SendFailureNotification(e.Message); return false; } catch (SecurityException e) { SendFailureNotification(e.Message); return false; } catch (NotSupportedException e) { SendFailureNotification(e.Message); return false; } catch (PathTooLongException e) { SendFailureNotification(e.Message); return false; } // Path.GetFullPath does not remove the spaces infront of the filename or folder name . So remove it var lastIndexOfSeparatorInFullPath = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparatorInFullPath != -1) { var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart())); } string projectRootPath = null; if (this.SelectedProject.FilePath == null) { projectRootPath = string.Empty; } else if (!TryGetImplicitFilePath(this.SelectedProject.FilePath, ServicesVSResources.IllegalPathForProject, out projectRootPath)) { return false; } if (this.FullFilePath.StartsWith(projectRootPath)) { // The new file will be within the root of the project var folderPath = this.FullFilePath.Substring(projectRootPath.Length); var containers = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // Folder name was mentioned if (containers.Count() > 1) { _fileName = containers.Last(); Folders = new List<string>(containers); Folders.RemoveAt(Folders.Count - 1); if (Folders.Any(folder => !(_syntaxFactsService.IsValidIdentifier(folder) || _syntaxFactsService.IsVerbatimIdentifier(folder)))) { _areFoldersValidIdentifiers = false; } } else if (containers.Count() == 1) { // File goes at the root of the Directory _fileName = containers[0]; Folders = null; } else { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } } else { // The new file will be outside the root of the project and folders will be null Folders = null; var lastIndexOfSeparator = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparator == -1) { SendFailureNotification(ServicesVSResources.IllegalCharactersInPath); return false; } _fileName = this.FullFilePath.Substring(lastIndexOfSeparator + 1); } // Check for reserved words in the folder or filename if (this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Any(s => _reservedKeywords.Contains(s, StringComparer.OrdinalIgnoreCase))) { SendFailureNotification(ServicesVSResources.FilePathCannotUseReservedKeywords); return false; } // We check to see if file path of the new file matches the filepath of any other existing file or if the Folders and FileName matches any of the document then // we say that the file already exists. if (this.SelectedProject.Documents.Where(n => n != null).Where(n => n.FilePath == FullFilePath).Any() || (this.Folders != null && this.FileName != null && this.SelectedProject.Documents.Where(n => n.Name != null && n.Folders.Count > 0 && n.Name == this.FileName && this.Folders.SequenceEqual(n.Folders)).Any()) || File.Exists(FullFilePath)) { SendFailureNotification(ServicesVSResources.FileAlreadyExists); return false; } } return true; } private bool TryGetImplicitFilePath(string implicitPathContainer, string message, out string implicitPath) { var indexOfLastSeparator = implicitPathContainer.LastIndexOf('\\'); if (indexOfLastSeparator == -1) { SendFailureNotification(message); implicitPath = null; return false; } implicitPath = implicitPathContainer.Substring(0, indexOfLastSeparator); return true; } private void SendFailureNotification(string message) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); } private Project _selectedProject; public Project SelectedProject { get { return _selectedProject; } set { var previousProject = _selectedProject; if (SetProperty(ref _selectedProject, value)) { NotifyPropertyChanged("DocumentList"); this.DocumentSelectIndex = 0; this.ProjectSelectIndex = this.ProjectList.FindIndex(p => p.Project == _selectedProject); if (_selectedProject != _document.Project) { // Restrict the Access List Options // 3 in the list represent the Public. 1-based array. this.AccessSelectIndex = this.AccessList.IndexOf("public") == -1 ? this.AccessList.IndexOf("Public") : this.AccessList.IndexOf("public"); Contract.Assert(this.AccessSelectIndex != -1); this.IsAccessListEnabled = false; } else { // Remove restriction this.IsAccessListEnabled = true; } if (previousProject != null && _projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } // Update the TypeKindList if required if (previousProject != null && previousProject.Language != _selectedProject.Language) { if (_selectedProject.Language == LanguageNames.CSharp) { var previousSelectedIndex = _kindSelectIndex; this.KindList = _csharpTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } else { var previousSelectedIndex = _kindSelectIndex; this.KindList = _visualBasicTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } } // Update File Extension UpdateFileNameExtension(); } } } private int _projectSelectIndex; public int ProjectSelectIndex { get { return _projectSelectIndex; } set { SetProperty(ref _projectSelectIndex, value); } } public List<ProjectSelectItem> ProjectList { get; private set; } private Project _previouslyPopulatedProject = null; private List<DocumentSelectItem> _previouslyPopulatedDocumentList = null; public IEnumerable<DocumentSelectItem> DocumentList { get { if (_previouslyPopulatedProject == _selectedProject) { return _previouslyPopulatedDocumentList; } _previouslyPopulatedProject = _selectedProject; _previouslyPopulatedDocumentList = new List<DocumentSelectItem>(); // Check for the current project if (_selectedProject == _document.Project) { // populate the current document _previouslyPopulatedDocumentList.Add(new DocumentSelectItem(_document, "<Current File>")); // Set the initial selected Document this.SelectedDocument = _document; // Populate the rest of the documents for the project _previouslyPopulatedDocumentList.AddRange(_document.Project.Documents .Where(d => d != _document && !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); } else { _previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents .Where(d => !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); this.SelectedDocument = _selectedProject.Documents.FirstOrDefault(); } this.IsExistingFileEnabled = _previouslyPopulatedDocumentList.Count == 0 ? false : true; this.IsNewFile = this.IsExistingFileEnabled ? this.IsNewFile : true; return _previouslyPopulatedDocumentList; } } private bool _isExistingFileEnabled = true; public bool IsExistingFileEnabled { get { return _isExistingFileEnabled; } set { SetProperty(ref _isExistingFileEnabled, value); } } private int _documentSelectIndex; public int DocumentSelectIndex { get { return _documentSelectIndex; } set { SetProperty(ref _documentSelectIndex, value); } } private Document _selectedDocument; public Document SelectedDocument { get { return _selectedDocument; } set { SetProperty(ref _selectedDocument, value); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } public List<string> Folders; public string TypeName { get { return _typeName; } set { SetProperty(ref _typeName, value); } } public bool IsNewFile { get { return _isNewFile; } set { SetProperty(ref _isNewFile, value); } } public bool IsExistingFile { get { return !_isNewFile; } set { SetProperty(ref _isNewFile, !value); } } private bool _isAccessListEnabled; private bool _shouldChangeTypeKindListSelectedIndex = false; public bool IsAccessListEnabled { get { return _isAccessListEnabled; } set { SetProperty(ref _isAccessListEnabled, value); } } private bool _areFoldersValidIdentifiers = true; public bool AreFoldersValidIdentifiers { get { if (_areFoldersValidIdentifiers) { var workspace = this.SelectedProject.Solution.Workspace as VisualStudioWorkspaceImpl; var project = workspace?.GetHostProject(this.SelectedProject.Id) as AbstractProject; return !(project?.IsWebSite == true); } return false; } } public IList<string> ProjectFolders { get; private set; } public string FullFilePath { get; private set; } internal void UpdateFileNameExtension() { var currentFileName = this.FileName.Trim(); if (!string.IsNullOrWhiteSpace(currentFileName) && !currentFileName.EndsWith("\\")) { if (this.SelectedProject.Language == LanguageNames.CSharp) { // For CSharp currentFileName = UpdateExtension(currentFileName, _csharpExtension, _visualBasicExtension); } else { // For Visual Basic currentFileName = UpdateExtension(currentFileName, _visualBasicExtension, _csharpExtension); } } this.FileName = currentFileName; } private string UpdateExtension(string currentFileName, string desiredFileExtension, string undesiredFileExtension) { if (currentFileName.EndsWith(desiredFileExtension, StringComparison.OrdinalIgnoreCase)) { // No change required return currentFileName; } // Remove the undesired extension if (currentFileName.EndsWith(undesiredFileExtension, StringComparison.OrdinalIgnoreCase)) { currentFileName = currentFileName.Substring(0, currentFileName.Length - undesiredFileExtension.Length); } // Append the desired extension return currentFileName + desiredFileExtension; } internal GenerateTypeDialogViewModel( Document document, INotificationService notificationService, IProjectManagementService projectManagementService, ISyntaxFactsService syntaxFactsService, IGeneratedCodeRecognitionService generatedCodeService, GenerateTypeDialogOptions generateTypeDialogOptions, string typeName, string fileExtension, bool isNewFile, string accessSelectString, string typeKindSelectString) { _generateTypeDialogOptions = generateTypeDialogOptions; InitialSetup(document.Project.Language); var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph(); // Initialize the dependencies var projectListing = new List<ProjectSelectItem>(); // Populate the project list // Add the current project projectListing.Add(new ProjectSelectItem(document.Project)); // Add the rest of the projects // Adding dependency graph to avoid cyclic dependency projectListing.AddRange(document.Project.Solution.Projects .Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id)) .Select(p => new ProjectSelectItem(p))); this.ProjectList = projectListing; _typeName = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith("Attribute") ? typeName + "Attribute" : typeName; this.FileName = typeName + fileExtension; _document = document; this.SelectedProject = document.Project; this.SelectedDocument = document; _notificationService = notificationService; _generatedCodeService = generatedCodeService; this.AccessList = document.Project.Language == LanguageNames.CSharp ? _csharpAccessList : _visualBasicAccessList; this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ? this.AccessList.IndexOf(accessSelectString) : 0; this.IsAccessListEnabled = true; this.KindList = document.Project.Language == LanguageNames.CSharp ? _csharpTypeKindList : _visualBasicTypeKindList; this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ? this.KindList.IndexOf(typeKindSelectString) : 0; this.ProjectSelectIndex = 0; this.DocumentSelectIndex = 0; _isNewFile = isNewFile; _syntaxFactsService = syntaxFactsService; _projectManagementService = projectManagementService; if (projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } else { this.ProjectFolders = SpecializedCollections.EmptyList<string>(); } } public class ProjectSelectItem { private Project _project; public string Name { get { return _project.Name; } } public Project Project { get { return _project; } } public ProjectSelectItem(Project project) { _project = project; } } public class DocumentSelectItem { private Document _document; public Document Document { get { return _document; } } private string _name; public string Name { get { return _name; } } public DocumentSelectItem(Document document, string documentName) { _document = document; _name = documentName; } public DocumentSelectItem(Document document) { _document = document; if (document.Folders.Count == 0) { _name = document.Name; } else { _name = string.Join("\\", document.Folders) + "\\" + document.Name; } } } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.IO; using System.Drawing.Imaging; using SoftLogik.Win.UI; namespace SoftLogik.Win.UI { public partial class RecordForm { public RecordForm() { InitializeComponent(); } //Navigation Events public delegate void NavigationChangedEventHandler(System.Object sender, SPFormNavigateEventArgs e); private NavigationChangedEventHandler NavigationChangedEvent; public event NavigationChangedEventHandler NavigationChanged { add { NavigationChangedEvent = (NavigationChangedEventHandler) System.Delegate.Combine(NavigationChangedEvent, value); } remove { NavigationChangedEvent = (NavigationChangedEventHandler) System.Delegate.Remove(NavigationChangedEvent, value); } } public delegate void RecordBindingEventHandler(System.Object sender, SPFormRecordBindingEventArgs e); private RecordBindingEventHandler RecordBindingEvent; public event RecordBindingEventHandler RecordBinding { add { RecordBindingEvent = (RecordBindingEventHandler) System.Delegate.Combine(RecordBindingEvent, value); } remove { RecordBindingEvent = (RecordBindingEventHandler) System.Delegate.Remove(RecordBindingEvent, value); } } public delegate void DataboundEventHandler(System.Object sender, System.EventArgs e); private DataboundEventHandler DataboundEvent; public event DataboundEventHandler Databound { add { DataboundEvent = (DataboundEventHandler) System.Delegate.Combine(DataboundEvent, value); } remove { DataboundEvent = (DataboundEventHandler) System.Delegate.Remove(DataboundEvent, value); } } public delegate void RecordChangedEventHandler(System.Object sender, SPFormRecordUpdateEventArgs e); private RecordChangedEventHandler RecordChangedEvent; public event RecordChangedEventHandler RecordChanged { add { RecordChangedEvent = (RecordChangedEventHandler) System.Delegate.Combine(RecordChangedEvent, value); } remove { RecordChangedEvent = (RecordChangedEventHandler) System.Delegate.Remove(RecordChangedEvent, value); } } public delegate void RecordValidatingEventHandler(System.Object sender, SPFormValidatingEventArgs e); private RecordValidatingEventHandler RecordValidatingEvent; public event RecordValidatingEventHandler RecordValidating { add { RecordValidatingEvent = (RecordValidatingEventHandler) System.Delegate.Combine(RecordValidatingEvent, value); } remove { RecordValidatingEvent = (RecordValidatingEventHandler) System.Delegate.Remove(RecordValidatingEvent, value); } } #region Properties protected DataTable _DataSource = null; protected SPRecordBindingSettings _BindingSettings; protected SPFormRecordStateManager _RecordState = new SPFormRecordStateManager(); protected LookupForm _LookupForm; protected Control _FirstField = null; protected NewRecordCallback _NewRecordProc; public LookupForm LookupForm { set { _LookupForm = value; } } #endregion #region Form Overrides protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); //WindowState = FormWindowState.Maximized if (! DesignMode) { SPFormRecordBindingEventArgs dataBindSettings = new SPFormRecordBindingEventArgs(); OnRecordBinding(dataBindSettings); this._RecordState.CurrentState = SPFormRecordModes.EditMode; //By Default Form is in Edit Mode this._RecordState.BindingData = true; _DataSource = dataBindSettings.DataSource; _BindingSettings = dataBindSettings.BindingSettings; _NewRecordProc = _BindingSettings.NewRecordProc; SPFormSupport.BindControls(this.Controls, ref DetailBinding, ref _RecordState, new SoftLogik.Win.UI.EventHandler(OnFieldChanged)); MyTabOrderManager = new UI.VisualTabOrderManager(this); MyTabOrderManager.SetTabOrder(UI.VisualTabOrderManager.TabScheme.DownFirst); // set tab order } } protected override void OnActivated(System.EventArgs e) { base.OnActivated(e); } protected override void OnFormClosing(System.Windows.Forms.FormClosingEventArgs e) { if (_RecordState.CurrentState == SPFormRecordModes.DirtyMode || _RecordState.CurrentState == SPFormRecordModes.InsertMode) { DialogResult msgResult = MessageBox.Show("Save Changes made to " + this.Text + "?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); switch (msgResult) { case System.Windows.Forms.DialogResult.Yes: OnSaveRecord(); //Save Changes break; case System.Windows.Forms.DialogResult.No: break; case System.Windows.Forms.DialogResult.Cancel: e.Cancel = true; break; } } base.OnFormClosing(e); } protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { base.OnKeyDown(e); if (e.Control) { switch (e.KeyCode) { case Keys.N: NewRecord.PerformClick(); break; case Keys.S: SaveRecord.PerformClick(); break; case Keys.Delete: DeleteRecord.PerformClick(); break; } } if (e.KeyCode == Keys.Escape) { if (_RecordState.CurrentState == SPFormRecordModes.DirtyMode) { UndoRecord.PerformClick(); } else { CloseWindow.PerformClick(); } } } #endregion #region Protected Overrides protected virtual void OnRecordBinding(SPFormRecordBindingEventArgs e) { if (RecordBindingEvent != null) //let client respond RecordBindingEvent(this, e); } protected virtual void OnRecordChanged(SPFormRecordUpdateEventArgs e) { if (RecordChangedEvent != null) RecordChangedEvent(this, e); } #endregion #region Private Methods protected virtual void OnFieldChanged(System.Object sender, System.EventArgs e) { if (_RecordState.ShowingData == false) { if (_RecordState.CurrentState == SPFormRecordModes.EditMode && _RecordState.CurrentState != SPFormRecordModes.DirtyMode && (! _RecordState.BindingData)) { _RecordState.CurrentState = SPFormRecordModes.DirtyMode; UpdateFormCaption(false); ToolbarSupport.ToolbarToggleSave(tbrMain, null); } } _RecordState.BindingData = false; } protected virtual void OnNewRecord() { try { DetailBinding.AddNew(); DetailBinding.MoveFirst(); this._RecordState.CurrentState = SPFormRecordModes.InsertMode; ToolbarSupport.ToolbarToggleSave(tbrMain, null); FirstFieldFocus(); } catch (Exception) { } } protected virtual void OnRefreshRecord() { try { this._RecordState.CurrentState = SPFormRecordModes.EditMode; FirstFieldFocus(); } catch (Exception) { } } protected virtual void OnSortRecord() { try { this._RecordState.CurrentState = SPFormRecordModes.EditMode; FirstFieldFocus(); } catch (Exception) { } } protected virtual void OnSaveRecord() { this.Validate(); try { _RecordState.ShowingData = true; DetailBinding.EndEdit(); _RecordState.ShowingData = false; } catch (Exception) { return; } if (DetailBinding.Current != null) { if (this._RecordState.CurrentState == SPFormRecordModes.InsertMode) { OnRecordChanged(new SPFormRecordUpdateEventArgs(_RecordState.NewRecordData, @SPFormDataStates.New)); _RecordState.NewRecordData = null; } else { OnRecordChanged(new SPFormRecordUpdateEventArgs(((DataRowView) DetailBinding.Current).Row, SPFormDataStates.Edited)); } _RecordState.CurrentState = SPFormRecordModes.EditMode; UpdateFormCaption(true); } } protected virtual void OnUndoRecord() { //On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C# if (DetailBinding.Current != null) { if (((DataRowView) DetailBinding.Current).IsNew) { DetailBinding.RemoveCurrent(); } else { DetailBinding.CancelEdit(); } } _RecordState.CurrentState = SPFormRecordModes.EditMode; UpdateFormCaption(true); } protected virtual void OnDeleteRecord() { try { if (MessageBox.Show("Are you sure you want to Delete \'" + ((DataRowView) DetailBinding.Current).Row(_BindingSettings.DisplayMember).ToString() + "\' ?", "Delete Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { OnRecordChanged(new SPFormRecordUpdateEventArgs(((DataRowView) DetailBinding.Current).Row, SPFormDataStates.Deleted)); _RecordState.ShowingData = true; DetailBinding.RemoveCurrent(); _RecordState.ShowingData = false; } } catch (Exception) { } } protected virtual void OnSearchRecord() { if (_LookupForm != null) { _LookupForm.ShowDialog(this); //.SearchResults() } } protected virtual void OnCopyRecord() { if (DetailBinding.Current != null) { //_RecordState.ShowingData = True DataRowView clonedDataRow = (DataRowView) DetailBinding.Current; DataRowView newDataRow = (DataRowView) (DetailBinding.AddNew()); DuplicateRecord(clonedDataRow, ref newDataRow); DetailBinding.ResetBindings(false); _RecordState.CurrentState = SPFormRecordModes.InsertMode; //_RecordState.ShowingData = False } } protected virtual void OnNavigate(SPRecordNavigateDirections direction) { DataRow lastRecord; DataRow currentRecord; //On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C# _RecordState.ShowingData = true; lastRecord = ((DataRowView) DetailBinding.Current).Row; switch (direction) { case SPRecordNavigateDirections.First: SelectNameInList(0); break; case SPRecordNavigateDirections.Last: SelectNameInList(DetailBinding.Count - 1); break; case SPRecordNavigateDirections.Next: SelectNameInList(DetailBinding.Position + 1); break; case SPRecordNavigateDirections.Previous: SelectNameInList(DetailBinding.Position - 1); break; } _RecordState.ShowingData = false; currentRecord = ((DataRowView) DetailBinding.Current).Row; if (NavigationChangedEvent != null) NavigationChangedEvent(tbrMain, new SPFormNavigateEventArgs(direction, lastRecord, currentRecord)); } protected virtual void OnCloseWindow() { this.Close(); } #endregion #region Support Methods protected virtual void UpdateFormCaption(bool Clear) { string strText = this.Text; if (! Clear) { strText += ((strText.EndsWith("*")) ? Constants.vbNullString : "*").ToString(); this.Text = strText; } else { this.Text = strText.Replace("*", Constants.vbNullString); } } protected virtual void FirstFieldFocus() { int lastTabIndex; try { Control firstControl = this.GetNextControl(this, true); if (firstControl != null) { lastTabIndex = firstControl.TabIndex; FindFirstField(firstControl, ref lastTabIndex); } } catch (Exception) { return; } } private void FindFirstField(Control OuterControl, ref int lastTabIndex) { Control ctl = OuterControl; while (ctl != null) { if ((! ctl.HasChildren) && (ctl.CanFocus && ctl.CanSelect)) { ctl.Focus(); return; } else { ctl = ctl.GetNextControl(ctl, true); FindFirstField(ctl, ref lastTabIndex); } } } private void DuplicateRecord(DataRowView SourceRow, ref DataRowView TargetRow) { _RecordState.DuplicatingData = true; TargetRow.Row.ItemArray = SourceRow.Row.ItemArray; foreach (DataColumn itm in TargetRow.Row.Table.Columns) { if (itm.ReadOnly) { if (itm.AutoIncrement) { TargetRow[itm.ColumnName] = 0; } } } _RecordState.DuplicatingData = false; } #endregion #region List and Toolbar Events protected virtual void ToolbarOperation(System.Object sender, System.EventArgs e) { if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarNew) { OnNewRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarSave) { OnSaveRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarDelete) { OnDeleteRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarUndo) { OnUndoRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarSearch) { OnSearchRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarCopy) { OnCopyRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarRefresh) { OnRefreshRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarSort) { OnSortRecord(); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarFirst) { OnNavigate(SPRecordNavigateDirections.First); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarPrevious) { OnNavigate(SPRecordNavigateDirections.Previous); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarNext) { OnNavigate(SPRecordNavigateDirections.Next); } else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarLast) { OnNavigate(SPRecordNavigateDirections.Last); } //Close Window else if (((ToolStripItem) sender).Name == ToolbarSupport.MasterToolbarButtonNames.ToolbarClose) { OnCloseWindow(); } } public void tbrMain_ItemClicked(System.Object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e) { ToolbarOperation(e.ClickedItem, e); } protected virtual void SelectNameInList(int Index) { int selectedRow = Index; DataRow lastRecord = null; DataRow currentRecord = null; if (selectedRow != - 1) { _RecordState.ShowingData = true; if (DetailBinding.Current != null) { lastRecord = ((DataRowView) DetailBinding.Current).Row; } DetailBinding.Position = selectedRow; _RecordState.ShowingData = false; if (DetailBinding.Current != null) { currentRecord = ((DataRowView) DetailBinding.Current).Row; } if (NavigationChangedEvent != null) NavigationChangedEvent(tbrMain, new SPFormNavigateEventArgs(SPRecordNavigateDirections.None, lastRecord, currentRecord)); } } #endregion public void DetailBinding_BindingComplete(object sender, System.Windows.Forms.BindingCompleteEventArgs e) { this._RecordState.BindingData = false; } public void DetailBinding_DataSourceChanged(object sender, System.EventArgs e) { this._RecordState.BindingData = true; } public void DetailBinding_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) { if (e.ListChangedType == System.ComponentModel.ListChangedType.ItemAdded) { if ((_NewRecordProc != null)&& _RecordState.DuplicatingData == false && _RecordState.ShowingData == false) { ((DataRowView) (DetailBinding[e.NewIndex])).Row.ItemArray = _NewRecordProc.Invoke.Row.ItemArray; _RecordState.NewRecordData = ((DataRowView) (DetailBinding[e.NewIndex])).Row; } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ManifestBasedResourceGroveler ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Searches for resources in Assembly manifest, used ** for assembly-based resource lookup. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Diagnostics.Contracts; using Microsoft.Win32; #if !FEATURE_CORECLR using System.Diagnostics.Tracing; #endif // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // internal class ManifestBasedResourceGroveler : IResourceGroveler { private ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. Contract.Requires(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { Contract.Assert(culture != null, "culture shouldn't be null; check caller"); Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; RuntimeAssembly satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); // 2. Look for satellite assembly or main assembly, as appropriate if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { // don't bother looking in satellites in this case satellite = _mediator.MainAssembly; } #if RESOURCE_SATELLITE_CONFIG // If our config file says the satellite isn't here, don't ask for it. else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture)) { satellite = null; } #endif else { satellite = GetSatelliteAssembly(lookForCulture, ref stackMark); if (satellite == null) { bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)); #if FEATURE_SPLIT_RESOURCES raiseException &= !_mediator.IsDebugSatellite; #endif // didn't find satellite, give error if necessary if (raiseException) { HandleSatelliteMissing(); } } } // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. String fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) { // Handle case in here where someone added a callback for assembly load events. // While no other threads have called into GetResourceSet, our own thread can! // At that point, we could already have an RS in our hash table, and we don't // want to add it twice. lock (localResourceSets) { if (localResourceSets.TryGetValue(culture.Name, out rs)) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } #endif } } stream = GetManifestResourceStream(satellite, fileName, ref stackMark); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (stream != null) { FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } else { FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } } #endif // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName); } #endif rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) { // 4b. Didn't find stream; give error if necessary bool raiseException = culture.HasInvariantCultureName; #if FEATURE_SPLIT_RESOURCES raiseException &= !_mediator.IsDebugSatellite; #endif // FEATURE_SPLIT_RESOURCES if (raiseException) { HandleResourceStreamMissing(fileName); } } #if !FEATURE_CORECLR if (!createIfNotExists && stream != null && rs == null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } } #endif return rs; } #if !FEATURE_CORECLR // Returns whether or not the main assembly contains a particular resource // file in it's assembly manifest. Used to verify that the neutral // Culture's .resources file is present in the main assembly public bool HasNeutralResources(CultureInfo culture, String defaultResName) { String resName = defaultResName; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName; String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames(); foreach(String s in resourceFiles) if (s.Equals(resName)) return true; return false; } #endif private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { #if FEATURE_SPLIT_RESOURCES // special-case for mscorlib debug resources only if (_mediator.IsDebugSatellite) { if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { return _mediator.NeutralResourcesCulture; } return lookForCulture; } #endif CultureInfo returnCulture = lookForCulture; // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name); } #endif returnCulture = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { returnCulture = _mediator.NeutralResourcesCulture; } return returnCulture; } [System.Security.SecurityCritical] internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { #if FEATURE_LEGACYNETCF // Windows Phone 7.0/7.1 ignore NeutralResourceLanguage attribute and // defaults fallbackLocation to MainAssembly if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } #endif Contract.Assert(a != null, "assembly != null"); string cultureName = null; short fallback = 0; if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref cultureName), out fallback)) { if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback)); } fallbackLocation = (UltimateResourceFallbackLocation)fallback; } else { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a); } #endif fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } try { CultureInfo c = CultureInfo.GetCultureInfo(cultureName); return c; } catch (ArgumentException e) { // we should catch ArgumentException only. // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. if (a == typeof(Object).Assembly) { Contract.Assert(false, "mscorlib's NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e); } } // Constructs a new ResourceSet for a given file name. The logic in // here avoids a ReflectionPermission check for our RuntimeResourceSet // for perf and working set reasons. // Use the assembly to resolve assembly manifest resource references. // Note that is can be null, but probably shouldn't be. // This method could use some refactoring. One thing at a time. [System.Security.SecurityCritical] internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { Contract.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) { long startPos = store.Position; // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); // Look for our magic number as a little endian Int32. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); String readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); } else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber) { // Assume that the future ResourceManager headers will // have two strings for us - the reader type name and // resource set type name. Read those, then use the num // bytes to skip field to correct our position. int numBytesToSkip = br.ReadInt32(); long endPosition = br.BaseStream.Position + numBytesToSkip; readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); br.BaseStream.Seek(endPosition, SeekOrigin.Begin); } else { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName())); } store.Position = startPos; // Perf optimization - Don't use Reflection for our defaults. // Note there are two different sets of strings here - the // assembly qualified strings emitted by ResourceWriter, and // the abbreviated ones emitted by InternalResGen. if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName)) { RuntimeResourceSet rs; #if LOOSELY_LINKED_RESOURCE_REFERENCE rs = new RuntimeResourceSet(store, assembly); #else rs = new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } else { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); Object[] args = new Object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); Object[] resourceSetArgs = #if LOOSELY_LINKED_RESOURCE_REFERENCE new Object[2]; #else new Object[1]; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[0] = reader; #if LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[1] = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE Type resSetType; if (_mediator.UserResourceSet == null) { Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else resSetType = _mediator.UserResourceSet; ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, null); return rs; } } else { store.Position = startPos; } } if (_mediator.UserResourceSet == null) { // Explicitly avoid CreateInstance if possible, because it // requires ReflectionPermission to call private & protected // constructors. #if LOOSELY_LINKED_RESOURCE_REFERENCE return new RuntimeResourceSet(store, assembly); #else return new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE } else { Object[] args = new Object[2]; args[0] = store; args[1] = assembly; try { ResourceSet rs = null; // Add in a check for a constructor taking in an assembly first. try { rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException) { } args = new Object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); #if LOOSELY_LINKED_RESOURCE_REFERENCE rs.Assembly = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } catch (MissingMethodException e) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e); } } } [System.Security.SecurityCritical] private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(fileName != null, "fileName shouldn't be null; check caller"); // If we're looking in the main assembly AND if the main assembly was the person who // created the ResourceManager, skip a security check for private manifest resources. bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite) && (_mediator.CallingAssembly == _mediator.MainAssembly); Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } return stream; } // Looks up a .resources file in the assembly manifest using // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(name != null, "name shouldn't be null; check caller"); StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) { String nameSpace = _mediator.LocationInfo.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } sb.Append(name); String givenName = sb.ToString(); CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; String canonicalName = null; foreach (String existingName in satellite.GetManifestResourceNames()) { if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0) { if (canonicalName == null) { canonicalName = existingName; } else { throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString())); } } } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (canonicalName != null) { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } else { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } } #endif if (canonicalName == null) { return null; } // If we're looking in the main assembly AND if the main // assembly was the person who created the ResourceManager, // skip a security check for private manifest resources. bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck); // GetManifestResourceStream will return null if we don't have // permission to read this stream from the assembly. For example, // if the stream is private and we're trying to access it from another // assembly (ie, ResMgr in mscorlib accessing anything else), we // require Reflection TypeInformation permission to be able to read // this. <STRIP>This meaning of private in satellite assemblies is a really // odd concept, and is orthogonal to the ResourceManager. // We should not assume we can skip this security check, // which means satellites must always use public manifest resources // if you want to support semi-trusted code. </STRIP> #if !FEATURE_CORECLR if (s!=null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName); } } #endif return s; } [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } RuntimeAssembly satellite = null; String satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. // Yet also somehow log this error for a developer. try { satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark); } // Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback. // catch (FileLoadException fle) { // Ignore cases where the loader gets an access // denied back from the OS. This showed up for // href-run exe's at one point. int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (satellite != null) { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } else { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } } #endif return satellite; } // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can // creating a ResourceReader via Reflection. This would incur // a security check (since the link-time check on the constructor that // takes a String is turned into a full demand with a stack walk) // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) { Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; // Ignore the actual version of the ResourceReader and // RuntimeResourceSet classes. Let those classes deal with // versioning themselves. AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); if (readerTypeName != null) { if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib)) return false; } if (resSetTypeName != null) { if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib)) return false; } return true; } [System.Security.SecurityCritical] private String GetSatelliteAssemblyName() { String satAssemblyName = _mediator.MainAssembly.GetSimpleName(); #if FEATURE_SPLIT_RESOURCES if (_mediator.IsDebugSatellite) { satAssemblyName = satAssemblyName + ".debug"; } if (!satAssemblyName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { #endif satAssemblyName += ".resources"; #if FEATURE_SPLIT_RESOURCES } #endif return satAssemblyName; } [System.Security.SecurityCritical] private void HandleSatelliteMissing() { String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); } AssemblyName an = new AssemblyName(); an.SetPublicKey(_mediator.MainAssembly.GetPublicKey()); byte[] token = an.GetPublicKeyToken(); int iLen = token.Length; StringBuilder publicKeyTok = new StringBuilder(iLen * 2); for (int i = 0; i < iLen; i++) { publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture)); } satAssemName += ", PublicKeyToken=" + publicKeyTok; String missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = "<invariant>"; } throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } [System.Security.SecurityCritical] // auto-generated private void HandleResourceStreamMissing(String fileName) { // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals("mscorlib")) { // This would break CultureInfo & all our exceptions. Contract.Assert(false, "Couldn't get mscorlib" + ResourceManager.ResFileExtension + " from mscorlib's assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = "mscorlib" + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; System.Environment.FailFast(mesgFailFast); } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. String resName = String.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName())); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods. [ResourceExposure(ResourceScope.None)] [System.Security.SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation); } }
using System; using System.Collections.Generic; using System.Linq; using MonoGame.PortableUI.Common; namespace MonoGame.PortableUI.Controls { public class Grid : Panel { private struct GridPosition { public int Row { get; set; } public int Column { get; set; } public int RowSpan { get; set; } public int ColumnSpan { get; set; } } public Grid() { RowDefinitions = new RowDefinitionCollection(); ColumnDefinitions = new ColumnDefinitionCollection(); } public RowDefinitionCollection RowDefinitions { get; } public ColumnDefinitionCollection ColumnDefinitions { get; } private static readonly Dictionary<Control, GridPosition> ControlGridPositionDictionary = new Dictionary<Control, GridPosition>(); private static GridPosition GetGridPosition(Control control) { GridPosition gridPosition = new GridPosition(); if (ControlGridPositionDictionary.ContainsKey(control)) gridPosition = ControlGridPositionDictionary[control]; return gridPosition; } public static void SetRow(Control control, int row) { var gridPosition = GetGridPosition(control); gridPosition.Row = row; ControlGridPositionDictionary[control] = gridPosition; } public static void SetColumn(Control control, int column) { var gridPosition = GetGridPosition(control); gridPosition.Column = column; ControlGridPositionDictionary[control] = gridPosition; } public static void SetRowSpan(Control control, int rowSpan) { var gridPosition = GetGridPosition(control); gridPosition.RowSpan = rowSpan; ControlGridPositionDictionary[control] = gridPosition; } public static void SetColumnSpan(Control control, int columnSpan) { var gridPosition = GetGridPosition(control); gridPosition.ColumnSpan = columnSpan; ControlGridPositionDictionary[control] = gridPosition; } public static int GetRow(Control control) { return GetGridPosition(control).Row; } public static int GetColumn(Control control) { return GetGridPosition(control).Column; } public static int GetRowSpan(Control control) { return GetGridPosition(control).RowSpan; } public static int GetColumnSpan(Control control) { return GetGridPosition(control).ColumnSpan; } public void AddChild(Control child, int row = 0, int column = 0, int rowSpan = 1, int columnSpan = 1) { Children.Add(child); SetRow(child, row); SetColumn(child, column); SetRowSpan(child, rowSpan); SetColumnSpan(child, columnSpan); } private Rect GetRect(Rect rect, Control child) { var coloumnCount = ColumnDefinitions.Count > 0 ? ColumnDefinitions.Count : 1; var rowCount = RowDefinitions.Count > 0 ? RowDefinitions.Count : 1; var rowHeights = GetRowHeights(rect); var columnWidths = GetColumnWidths(rect); var row = Math.Min(GetRow(child), rowCount); var column = Math.Min(GetColumn(child), coloumnCount); var rowSpan = Math.Max(GetRowSpan(child), 1); var columnSpan = Math.Max(GetColumnSpan(child), 1); var rectangle = new Rect( columnWidths.Take(column).Sum() + rect.Left, rowHeights.Take(row).Sum() + rect.Top, columnWidths.Skip(column).Take(columnSpan).Sum(), rowHeights.Skip(row).Take(rowSpan).Sum() ); return rectangle; } private List<int> GetRowHeights(Rect rect) { var autoRows = 0f; var starRows = 0f; var absoluteRows = 0f; var rowDefinitions = RowDefinitions; foreach (var gridLength in rowDefinitions.Select((row, i) => new {row.Height, Index = i })) { switch (gridLength.Height.Unit) { case GridLengthUnit.Auto: var max = 0f; foreach (var child in Children) { var row = GetRow(child); if (row == gridLength.Index) { var size = child.MeasureLayout(); if (size.Height > max) max = size.Height; } } // Ignore now autoRows += max; break; case GridLengthUnit.Absolute: absoluteRows += gridLength.Height.Value; break; case GridLengthUnit.Relative: starRows += gridLength.Height.Value; break; } } var starLeftover = Math.Max(0, rect.Height - absoluteRows - autoRows); if (!starLeftover.IsFixed()) starLeftover = 0; var starSingleValue = starLeftover / starRows; var result = new List<int>(); foreach (var gridLength in rowDefinitions.Select((row, i) => new { row.Height, Index = i })) { switch (gridLength.Height.Unit) { case GridLengthUnit.Auto: var max = 0f; foreach (var child in Children) { var row = GetRow(child); if (row == gridLength.Index) { var size = child.MeasureLayout(); if (size.Height > max) max = size.Height; } } // Ignore now result.Add((int) max); break; case GridLengthUnit.Absolute: result.Add((int)gridLength.Height.Value); break; case GridLengthUnit.Relative: result.Add((int)(gridLength.Height.Value * starSingleValue)); break; } } var f = (int)rect.Height - result.Sum(); if (f > 0) result[result.Count - 1] += f; return result; } public override void UpdateLayout(Rect rect) { base.UpdateLayout(rect); foreach (var child in Children) { child.UpdateLayout(GetRect(BoundingRect - Margin, child)); } } public override Size MeasureLayout() { return base.MeasureLayout(); } private List<int> GetColumnWidths(Rect rect) { // floats var autoColumns = 0f; var starColumns = 0f; var absoluteColumns = 0f; var columnDefinitions = ColumnDefinitions; foreach (var gridLength in columnDefinitions.Select((column, i) => new { column.Width, Index = i })) { switch (gridLength.Width.Unit) { case GridLengthUnit.Auto: var max = 0f; foreach (var child in Children) { var row = GetColumn(child); if (row == gridLength.Index) { var size = child.MeasureLayout(); if (size.Width > max) max = size.Width; } } autoColumns += max; break; case GridLengthUnit.Absolute: absoluteColumns += gridLength.Width.Value; break; case GridLengthUnit.Relative: starColumns += gridLength.Width.Value; break; } } var starLeftover = Math.Max(0, rect.Width - absoluteColumns - autoColumns); if (!starLeftover.IsFixed()) starLeftover = 0; var starSingleValue = starLeftover / starColumns; var result = new List<int>(); foreach (var gridLength in columnDefinitions.Select((column, i) => new { column.Width, Index = i })) { switch (gridLength.Width.Unit) { case GridLengthUnit.Auto: var max = 0f; foreach (var child in Children) { var row = GetColumn(child); if (row == gridLength.Index) { var size = child.MeasureLayout(); if (size.Width > max) max = size.Width; } } // Ignore now result.Add((int)max); break; case GridLengthUnit.Absolute: result.Add((int)gridLength.Width.Value); break; case GridLengthUnit.Relative: result.Add((int)(gridLength.Width.Value * starSingleValue)); break; } } var f = (int)rect.Width - result.Sum(); if (f > 0) result[result.Count - 1] += f; return result; } } }
/************************************************************************************ Filename : ONSPAudioSource.cs Content : Interface into the Oculus Native Spatializer Plugin Created : September 14, 2015 Authors : Peter Giokaris Copyright : Copyright 2015 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.1 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ #if UNITY_5 && !UNITY_5_0 && !UNITY_5_1 // The spatialization API is only supported by the final Unity 5.2 version and newer. // If you get script compile errors in this file, comment out the line below. // // Note: When Unity 6 is a thing, we will need to add that into the mix // #define ENABLE_SPATIALIZER_API #endif using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class ONSPAudioSource : MonoBehaviour { #if ENABLE_SPATIALIZER_API // Import functions public const string strONSPS = "AudioPluginOculusSpatializer"; [DllImport(strONSPS)] private static extern void ONSP_GetGlobalRoomReflectionValues(ref bool reflOn, ref bool reverbOn, ref float width, ref float height, ref float length); // Public [SerializeField] private bool enableSpatialization = true; public bool EnableSpatialization { get { return enableSpatialization; } set { enableSpatialization = value; } } [SerializeField] private float gain = 0.0f; public float Gain { get { return gain; } set { gain = Mathf.Clamp(value, 0.0f, 24.0f); } } [SerializeField] private bool useInvSqr = false; public bool UseInvSqr { get { return useInvSqr; } set { useInvSqr = value; } } [SerializeField] private float near = 1.0f; public float Near { get { return near; } set { near = Mathf.Clamp(value, 0.0f, 1000000.0f); } } [SerializeField] private float far = 10.0f; public float Far { get { return far; } set { far = Mathf.Clamp(value, 0.0f, 1000000.0f); } } [SerializeField] private bool enableRfl = false; public bool EnableRfl { get { return enableRfl; } set { enableRfl = value; } } #endif /// <summary> /// Awake this instance. /// </summary> void Awake() { // We might iterate through multiple sources / game object var source = GetComponent<AudioSource>(); SetParameters(ref source); } /// <summary> /// Start this instance. /// </summary> void Start() { } /// <summary> /// Update this instance. /// </summary> void Update() { // We might iterate through multiple sources / game object var source = GetComponent<AudioSource>(); // Check to see if we should disable spatializion if ((Application.isPlaying == false) || (AudioListener.pause == true) || (source.isPlaying == false) || (source.isActiveAndEnabled == false) ) { source.spatialize = false; return; } else { SetParameters(ref source); } } /// <summary> /// Sets the parameters. /// </summary> /// <param name="source">Source.</param> public void SetParameters(ref AudioSource source) { #if ENABLE_SPATIALIZER_API // See if we should enable spatialization source.spatialize = enableSpatialization; source.SetSpatializerFloat(0, gain); // All inputs are floats; convert bool to 0.0 and 1.0 if(useInvSqr == true) source.SetSpatializerFloat(1, 1.0f); else source.SetSpatializerFloat(1, 0.0f); source.SetSpatializerFloat(2, near); source.SetSpatializerFloat(3, far); if(enableRfl == true) source.SetSpatializerFloat(4, 0.0f); else source.SetSpatializerFloat(4, 1.0f); #endif } // Only draw gizmos if spatializer exists #if ENABLE_SPATIALIZER_API private static ONSPAudioSource RoomReflectionGizmoAS = null; /// <summary> /// /// </summary> void OnDrawGizmos() { // Are we the first one created? make sure to set our static ONSPAudioSource // for drawing out room parameters once if(RoomReflectionGizmoAS == null) { RoomReflectionGizmoAS = this; } Color c; const float colorSolidAlpha = 0.1f; // Draw the near/far spheres // Near (orange) c.r = 1.0f; c.g = 0.5f; c.b = 0.0f; c.a = 1.0f; Gizmos.color = c; Gizmos.DrawWireSphere(transform.position, Near); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawSphere(transform.position, Near); // Far (red) c.r = 1.0f; c.g = 0.0f; c.b = 0.0f; c.a = 1.0f; Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, Far); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawSphere(transform.position, Far); // Draw room parameters ONCE only, provided reflection engine is on if (RoomReflectionGizmoAS == this) { // Get global room parameters (write new C api to get reflection values) bool reflOn = false; bool reverbOn = false; float width = 1.0f; float height = 1.0f; float length = 1.0f; ONSP_GetGlobalRoomReflectionValues(ref reflOn, ref reverbOn, ref width, ref height, ref length); // TO DO: Get the room reflection values and render those out as well (like we do in the VST) if((Camera.main != null) && (reflOn == true)) { // Set color of cube (cyan is early reflections only, white is with reverb on) if(reverbOn == true) c = Color.white; else c = Color.cyan; Gizmos.color = c; Gizmos.DrawWireCube(Camera.main.transform.position, new Vector3(width, height, length)); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawCube(Camera.main.transform.position, new Vector3(width, height, length)); } } } /// <summary> /// /// </summary> void OnDestroy() { // We will null out single pointer instance // of the room reflection gizmo since we are being destroyed. // Any ONSPAS that is alive or born will re-set this pointer // so that we only draw it once if(RoomReflectionGizmoAS == this) { RoomReflectionGizmoAS = null; } } #endif }
using System; using System.Collections.Generic; using System.Linq; namespace Klocman.Tools { /// <summary> /// Algorithm by Siderite /// https://siderite.blogspot.com/2014/11/super-fast-and-accurate-string-distance.html#at2217133354 /// </summary> public class Sift4 { private readonly Options _options; public Sift4(Options options) { if (options == null) options = new Options(); if (options.Tokenizer == null) { options.Tokenizer = s => s == null ? new string[0] : s.ToCharArray().Select(c => c.ToString()).ToArray(); } if (options.TokenMatcher == null) { options.TokenMatcher = (t1, t2) => t1 == t2; } if (options.MatchingEvaluator == null) { options.MatchingEvaluator = (t1, t2) => 1; } if (options.LocalLengthEvaluator == null) { options.LocalLengthEvaluator = l => l; } if (options.TranspositionCostEvaluator == null) { options.TranspositionCostEvaluator = (c1, c2) => 1; } if (options.TranspositionsEvaluator == null) { options.TranspositionsEvaluator = (l, t) => l - t; } _options = options; } /// <summary> /// General distance algorithm uses all the parameters in the options object and works on tokens /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <param name="maxOffset"></param> /// <returns></returns> public double GeneralDistance(string s1, string s2, int maxOffset) { var t1 = _options.Tokenizer(s1); var t2 = _options.Tokenizer(s2); var l1 = t1.Length; var l2 = t2.Length; if (l1 == 0) return _options.LocalLengthEvaluator(l2); if (l2 == 0) return _options.LocalLengthEvaluator(l1); var c1 = 0; //cursor for string 1 var c2 = 0; //cursor for string 2 var lcss = 0.0; //largest common subsequence var localCs = 0.0; //local common substring var trans = 0.0; //cost of transpositions ('axb' vs 'xba') var offsetArr = new LinkedList<OffsetPair>(); //offset pair array, for computing the transpositions while ((c1 < l1) && (c2 < l2)) { if (_options.TokenMatcher(t1[c1], t2[c2])) { localCs += _options.MatchingEvaluator(t1[c1], t2[c2]); var isTransposition = false; var op = offsetArr.First; while (op != null) { //see if current match is a transposition var ofs = op.Value; if (c1 <= ofs.C1 || c2 <= ofs.C2) { // when two matches cross, the one considered a transposition is the one with the largest difference in offsets isTransposition = Math.Abs(c2 - c1) >= Math.Abs(ofs.C2 - ofs.C1); if (isTransposition) { trans += _options.TranspositionCostEvaluator(c1, c2); } else { if (!ofs.IsTransposition) { ofs.IsTransposition = true; trans += _options.TranspositionCostEvaluator(ofs.C1, ofs.C2); } } break; } var nextOp = op.Next; if (c1 > ofs.C2 && c2 > ofs.C1) { offsetArr.Remove(op); } op = nextOp; } offsetArr.AddLast(new OffsetPair(c1, c2) { IsTransposition = isTransposition }); } else { lcss += _options.LocalLengthEvaluator(localCs); localCs = 0; if (c1 != c2) { c1 = c2 = Math.Min(c1, c2); //using min allows the computation of transpositions } //if matching tokens are found, remove 1 from both cursors (they get incremented at the end of the loop) //so that we can have only one code block handling matches for (var i = 0; i < maxOffset && (c1 + i < l1 || c2 + i < l2); i++) { if ((c1 + i < l1) && _options.TokenMatcher(t1[c1 + i], t2[c2])) { c1 += i - 1; c2--; break; } if ((c2 + i < l2) && _options.TokenMatcher(t1[c1], t2[c2 + i])) { c1--; c2 += i - 1; break; } } } c1++; c2++; if (_options.MaxDistance != null) { var temporaryDistance = _options.LocalLengthEvaluator(Math.Max(c1, c2)) - _options.TranspositionsEvaluator(lcss, trans); if (temporaryDistance >= _options.MaxDistance) return Math.Round(temporaryDistance, MidpointRounding.AwayFromZero); } // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly if ((c1 >= l1) || (c2 >= l2)) { lcss += _options.LocalLengthEvaluator(localCs); localCs = 0; c1 = c2 = Math.Min(c1, c2); } } lcss += _options.LocalLengthEvaluator(localCs); return Math.Round(_options.LocalLengthEvaluator(Math.Max(l1, l2)) - _options.TranspositionsEvaluator(lcss, trans), MidpointRounding.AwayFromZero); //apply transposition cost to the final result } /// <summary> /// Static distance algorithm working on strings, computing transpositions as well as stopping when maxDistance was reached. /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <param name="maxOffset"></param> /// <param name="maxDistance"></param> /// <returns></returns> public static double CommonDistance(string s1, string s2, int maxOffset, int maxDistance = 0) { var l1 = s1 == null ? 0 : s1.Length; var l2 = s2 == null ? 0 : s2.Length; if (l1 == 0) return l2; if (l2 == 0) return l1; var c1 = 0; //cursor for string 1 var c2 = 0; //cursor for string 2 var lcss = 0; //largest common subsequence var localCs = 0; //local common substring var trans = 0; //number of transpositions ('axb' vs 'xba') var offsetArr = new LinkedList<OffsetPair>(); //offset pair array, for computing the transpositions while ((c1 < l1) && (c2 < l2)) { if (s1[c1] == s2[c2]) { localCs++; var isTransposition = false; var op = offsetArr.First; while (op != null) { //see if current match is a transposition var ofs = op.Value; if (c1 <= ofs.C1 || c2 <= ofs.C2) { // when two matches cross, the one considered a transposition is the one with the largest difference in offsets isTransposition = Math.Abs(c2 - c1) >= Math.Abs(ofs.C2 - ofs.C1); if (isTransposition) { trans++; } else { if (!ofs.IsTransposition) { ofs.IsTransposition = true; trans++; } } break; } var nextOp = op.Next; if (c1 > ofs.C2 && c2 > ofs.C1) { offsetArr.Remove(op); } op = nextOp; } offsetArr.AddLast(new OffsetPair(c1, c2) { IsTransposition = isTransposition }); } else { lcss += localCs; localCs = 0; if (c1 != c2) { c1 = c2 = Math.Min(c1, c2); //using min allows the computation of transpositions } //if matching tokens are found, remove 1 from both cursors (they get incremented at the end of the loop) //so that we can have only one code block handling matches for (var i = 0; i < maxOffset && (c1 + i < l1 || c2 + i < l2); i++) { if ((c1 + i < l1) && s1[c1 + i] == s2[c2]) { c1 += i - 1; c2--; break; } if ((c2 + i < l2) && s1[c1] == s2[c2 + i]) { c1--; c2 += i - 1; break; } } } c1++; c2++; if (maxDistance > 0) { var temporaryDistance = Math.Max(c1, c2) - (lcss - trans); if (temporaryDistance >= maxDistance) return temporaryDistance; } // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly if ((c1 >= l1) || (c2 >= l2)) { lcss += localCs; localCs = 0; c1 = c2 = Math.Min(c1, c2); } } lcss += localCs; return Math.Max(l1, l2) - (lcss - trans); //apply transposition cost to the final result } /// <summary> /// Standard Sift algorithm, using strings and taking only maxOffset as a parameter /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <param name="maxOffset"></param> /// <returns></returns> public static int SimplestDistance(string s1, string s2, int maxOffset) { var l1 = s1 == null ? 0 : s1.Length; var l2 = s2 == null ? 0 : s2.Length; if (l1 == 0) return l2; if (l2 == 0) return l1; var c1 = 0; //cursor for string 1 var c2 = 0; //cursor for string 2 var lcss = 0; //largest common subsequence var localCs = 0; //local common substring while ((c1 < l1) && (c2 < l2)) { if (s1[c1] == s2[c2]) { localCs++; } else { lcss += localCs; localCs = 0; if (c1 != c2) { c1 = c2 = Math.Max(c1, c2); } //if matching tokens are found, remove 1 from both cursors (they get incremented at the end of the loop) //so that we can have only one code block handling matches for (var i = 0; i < maxOffset && (c1 + i < l1 && c2 + i < l2); i++) { if ((c1 + i < l1) && s1[c1 + i] == s2[c2]) { c1 += i - 1; c2--; break; } if ((c2 + i < l2) && s1[c1] == s2[c2 + i]) { c1--; c2 += i - 1; break; } } } c1++; c2++; } lcss += localCs; return Math.Max(l1, l2) - lcss; } private class OffsetPair { public int C1 { get; set; } public int C2 { get; set; } public bool IsTransposition { get; set; } public OffsetPair(int c1, int c2) { C1 = c1; C2 = c2; IsTransposition = false; } } public class Options { /// <summary> /// If set, the algorithm will stop if the distance reaches this value /// </summary> public int? MaxDistance { get; set; } /// <summary> /// The function that turns strings into a list of tokens (also strings) /// </summary> public Func<string, string[]> Tokenizer { get; set; } /// <summary> /// The function that determines if two tokens are matching (similar to characters being the same in the simple algorithm) /// </summary> public Func<string, string, bool> TokenMatcher { get; set; } /// <summary> /// The function that determines the value of a match of two tokens (the equivalent of adding 1 to the lcss when two characters match) /// This assumes that the TokenMatcher function is a lot less expensive than this evaluator. If that is not the case, /// you can optimize the speed of the algorithm by using only the matching evaluator and then calculating if two tokens match on the returned value. /// </summary> public Func<string, string, double> MatchingEvaluator { get; set; } /// <summary> /// Determines if the local value (computed on subsequent matched tokens) must be modified. /// In case one wants to reward longer matched substrings, for example, this is what you need to change. /// </summary> public Func<double, double> LocalLengthEvaluator { get; set; } /// <summary> /// The function determining the cost of an individual transposition, based on its counter positions. /// </summary> public Func<int, int, double> TranspositionCostEvaluator { get; set; } /// <summary> /// The function determining how the cost of transpositions affects the final result /// Change it if it doesn't suit you. /// </summary> public Func<double, double, double> TranspositionsEvaluator { get; set; } } } }
// Copyright 2007-2014 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.Tests { using System; using System.Threading.Tasks; using NUnit.Framework; using Shouldly; using TestFramework; using TestFramework.Messages; [TestFixture] public class Sending_a_message_to_a_queue : InMemoryTestFixture { [Test] public async Task Should_have_an_empty_fault_address() { ConsumeContext<PingMessage> ping = await _ping; ping.FaultAddress.ShouldBe(null); } [Test] public async Task Should_have_an_empty_response_address() { ConsumeContext<PingMessage> ping = await _ping; ping.ResponseAddress.ShouldBe(null); } [Test] public async Task Should_include_the_correlation_id() { ConsumeContext<PingMessage> ping = await _ping; ping.CorrelationId.ShouldBe(_correlationId); } [Test] public async Task Should_include_the_destination_address() { ConsumeContext<PingMessage> ping = await _ping; ping.DestinationAddress.ShouldBe(InputQueueAddress); } [Test] public async Task Should_include_the_header() { ConsumeContext<PingMessage> ping = await _ping; object header; ping.Headers.TryGetHeader("One", out header); header.ShouldBe("1"); } [Test] public async Task Should_include_the_source_address() { ConsumeContext<PingMessage> ping = await _ping; ping.SourceAddress.ShouldBe(BusAddress); } Task<ConsumeContext<PingMessage>> _ping; Guid _correlationId; [TestFixtureSetUp] public void Setup() { _correlationId = Guid.NewGuid(); InputQueueSendEndpoint.Send(new PingMessage(), Pipe.New<SendContext<PingMessage>>(x => x.UseExecute(context => { context.CorrelationId = _correlationId; context.Headers.Set("One", "1"); }))) .Wait(TestCancellationToken); } protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _ping = Handled<PingMessage>(configurator); } } [TestFixture] public class Sending_a_request_to_a_queue : InMemoryTestFixture { [Test] public async Task Should_have_received_the_response_on_the_handler() { PongMessage message = await _response; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_have_the_matching_correlation_id() { ConsumeContext<PongMessage> context = await _responseHandler; context.Message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_include_the_destination_address() { ConsumeContext<PingMessage> ping = await _ping; ping.DestinationAddress.ShouldBe(InputQueueAddress); } [Test] public async Task Should_include_the_response_address() { ConsumeContext<PingMessage> ping = await _ping; ping.ResponseAddress.ShouldBe(BusAddress); } [Test] public async Task Should_include_the_source_address() { ConsumeContext<PingMessage> ping = await _ping; ping.SourceAddress.ShouldBe(BusAddress); } [Test] public async Task Should_receive_the_response() { ConsumeContext<PongMessage> context = await _responseHandler; context.ConversationId.ShouldBe(_conversationId); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Guid? _conversationId; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _conversationId = NewId.NextGuid(); _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { x.ConversationId = _conversationId; _response = x.Handle<PongMessage>(async context => { Console.WriteLine("Response received"); }); x.Timeout = TestTimeout; }); Await(() => _request); } protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PongMessage(x.Message.CorrelationId))); } } [TestFixture] public class Sending_a_request_with_two_handlers : InMemoryTestFixture { [Test] public async Task Should_have_received_the_actual_response() { PingNotSupported message = await _notSupported; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_not_complete_the_handler() { await _notSupported; await BusSendEndpoint.Send(new PongMessage((await _ping).Message.CorrelationId)); Assert.Throws<TaskCanceledException>(async () => { await _response; }); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Task<PingNotSupported> _notSupported; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { _response = x.Handle<PongMessage>(async _ => { }); _notSupported = x.Handle<PingNotSupported>(async _ => { }); }); Await(() => _request); } protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PingNotSupported(x.Message.CorrelationId))); } } [TestFixture] public class Publishing_a_request: InMemoryTestFixture { [Test] public async Task Should_have_received_the_response_on_the_handler() { PongMessage message = await _response; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Task<PingNotSupported> _notSupported; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _request = Bus.PublishRequest(new PingMessage(), x => { _response = x.Handle<PongMessage>(async _ => { }); }); Await(() => _request); } protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PongMessage(x.Message.CorrelationId))); } } [TestFixture] public class Sending_a_request_with_no_handler : InMemoryTestFixture { [Test] public async Task Should_receive_a_request_timeout_exception_on_the_handler() { Assert.Throws<RequestTimeoutException>(async () => await _response); } [Test] public async Task Should_receive_a_request_timeout_exception_on_the_request() { Assert.Throws<RequestTimeoutException>(async () => { Request<PingMessage> request = await _request; await request.Task; }); } Task<Request<PingMessage>> _request; Task<PongMessage> _response; [TestFixtureSetUp] public void Setup() { _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { x.Timeout = TimeSpan.FromSeconds(1); _response = x.Handle<PongMessage>(async _ => { }); }); Await(() => _request); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Creates an Azure Data Lake Store filesystem client. /// </summary> public partial class DataLakeStoreFileSystemManagementClient : ServiceClient<DataLakeStoreFileSystemManagementClient>, IDataLakeStoreFileSystemManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> internal string BaseUri {get; set;} /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public string AdlsFileSystemDnsSuffix { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IFileSystemOperations. /// </summary> public virtual IFileSystemOperations FileSystem { get; private set; } /// <summary> /// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreFileSystemManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreFileSystemManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.FileSystem = new FileSystemOperations(this); this.BaseUri = "https://{accountName}.{adlsFileSystemDnsSuffix}"; this.ApiVersion = "2015-10-01-preview"; this.AdlsFileSystemDnsSuffix = "azuredatalakestore.net"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<AdlsRemoteException>("exception")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<AdlsRemoteException>("exception")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to comnplete. /// </summary> [Serializable] [XmlRoot] public partial class SignalPdu : RadioCommunicationsPdu, IEquatable<SignalPdu> { /// <summary> /// encoding scheme used, and enumeration /// </summary> private ushort _encodingScheme; /// <summary> /// tdl type /// </summary> private ushort _tdlType; /// <summary> /// sample rate /// </summary> private uint _sampleRate; /// <summary> /// length od data /// </summary> private short _dataLength; /// <summary> /// number of samples /// </summary> private short _samples; /// <summary> /// Initializes a new instance of the <see cref="SignalPdu"/> class. /// </summary> public SignalPdu() { PduType = (byte)26; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(SignalPdu left, SignalPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(SignalPdu left, SignalPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 2; // this._encodingScheme marshalSize += 2; // this._tdlType marshalSize += 4; // this._sampleRate marshalSize += 2; // this._dataLength marshalSize += 2; // this._samples return marshalSize; } /// <summary> /// Gets or sets the encoding scheme used, and enumeration /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "encodingScheme")] public ushort EncodingScheme { get { return this._encodingScheme; } set { this._encodingScheme = value; } } /// <summary> /// Gets or sets the tdl type /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "tdlType")] public ushort TdlType { get { return this._tdlType; } set { this._tdlType = value; } } /// <summary> /// Gets or sets the sample rate /// </summary> [XmlElement(Type = typeof(uint), ElementName = "sampleRate")] public uint SampleRate { get { return this._sampleRate; } set { this._sampleRate = value; } } /// <summary> /// Gets or sets the length od data /// </summary> [XmlElement(Type = typeof(short), ElementName = "dataLength")] public short DataLength { get { return this._dataLength; } set { this._dataLength = value; } } /// <summary> /// Gets or sets the number of samples /// </summary> [XmlElement(Type = typeof(short), ElementName = "samples")] public short Samples { get { return this._samples; } set { this._samples = value; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedShort((ushort)this._encodingScheme); dos.WriteUnsignedShort((ushort)this._tdlType); dos.WriteUnsignedInt((uint)this._sampleRate); dos.WriteShort((short)this._dataLength); dos.WriteShort((short)this._samples); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._encodingScheme = dis.ReadUnsignedShort(); this._tdlType = dis.ReadUnsignedShort(); this._sampleRate = dis.ReadUnsignedInt(); this._dataLength = dis.ReadShort(); this._samples = dis.ReadShort(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<SignalPdu>"); base.Reflection(sb); try { sb.AppendLine("<encodingScheme type=\"ushort\">" + this._encodingScheme.ToString(CultureInfo.InvariantCulture) + "</encodingScheme>"); sb.AppendLine("<tdlType type=\"ushort\">" + this._tdlType.ToString(CultureInfo.InvariantCulture) + "</tdlType>"); sb.AppendLine("<sampleRate type=\"uint\">" + this._sampleRate.ToString(CultureInfo.InvariantCulture) + "</sampleRate>"); sb.AppendLine("<dataLength type=\"short\">" + this._dataLength.ToString(CultureInfo.InvariantCulture) + "</dataLength>"); sb.AppendLine("<samples type=\"short\">" + this._samples.ToString(CultureInfo.InvariantCulture) + "</samples>"); sb.AppendLine("</SignalPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as SignalPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(SignalPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._encodingScheme != obj._encodingScheme) { ivarsEqual = false; } if (this._tdlType != obj._tdlType) { ivarsEqual = false; } if (this._sampleRate != obj._sampleRate) { ivarsEqual = false; } if (this._dataLength != obj._dataLength) { ivarsEqual = false; } if (this._samples != obj._samples) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._encodingScheme.GetHashCode(); result = GenerateHash(result) ^ this._tdlType.GetHashCode(); result = GenerateHash(result) ^ this._sampleRate.GetHashCode(); result = GenerateHash(result) ^ this._dataLength.GetHashCode(); result = GenerateHash(result) ^ this._samples.GetHashCode(); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Xml; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== ValidateAttribute ===================== public class TCValidateAttribute : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCValidateAttribute(ITestOutputHelper output) : base(output) { _output = output; } [Theory] [InlineData(null, "")] [InlineData("attr", null)] public void PassNull_LocalName_NameSpace__Invalid(String localName, String nameSpace) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute(localName, nameSpace, StringGetter("foo"), info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullValueGetter__Invalid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute("attr", "", (XmlValueGetter)null, info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullXmlSchemaInfo__Valid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); val.ValidateAttribute("attr", "", StringGetter("foo"), null); return; } [Theory] [InlineData("RequiredAttribute")] [InlineData("OptionalAttribute")] [InlineData("DefaultAttribute")] [InlineData("FixedAttribute")] [InlineData("FixedRequiredAttribute")] public void Validate_Required_Optional_Default_Fixed_FixedRequired_Attribute(String attrType) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement(attrType + "Element", "", null); val.ValidateAttribute(attrType, "", StringGetter("foo"), info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName(attrType)); Assert.Equal(info.Validity, XmlSchemaValidity.Valid); Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.String); return; } [Fact] public void ValidateAttributeWithNamespace() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("NamespaceAttributeElement", "", null); val.ValidateAttribute("attr1", "uri:tempuri", StringGetter("123"), info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName("attr1", "uri:tempuri")); Assert.Equal(info.Validity, XmlSchemaValidity.Valid); Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.Int); return; } [Fact] public void ValidateAnyAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("AnyAttributeElement", "", null); val.ValidateAttribute("SomeAttribute", "", StringGetter("foo"), info); Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown); return; } [Fact] public void AskForDefaultAttributesAndValidateThem() { XmlSchemaValidator val = CreateValidator(XSDFILE_200_DEF_ATTRIBUTES); XmlSchemaInfo info = new XmlSchemaInfo(); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("StressElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); foreach (XmlSchemaAttribute a in atts) { val.ValidateAttribute(a.QualifiedName.Name, a.QualifiedName.Namespace, StringGetter(a.DefaultValue), info); Assert.Equal(info.SchemaAttribute, a); } atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); Assert.Equal(atts.Count, 0); return; } [Fact] public void ValidateTopLevelAttribute() { XmlSchemaValidator val; XmlSchemaSet schemas = new XmlSchemaSet(); XmlSchemaInfo info = new XmlSchemaInfo(); schemas.Add("", TestData + XSDFILE_200_DEF_ATTRIBUTES); schemas.Compile(); val = CreateValidator(schemas); val.Initialize(); val.ValidateAttribute("BasicAttribute", "", StringGetter("foo"), info); Assert.Equal(info.SchemaAttribute, schemas.GlobalAttributes[new XmlQualifiedName("BasicAttribute")]); return; } [Fact] public void ValidateSameAttributeTwice() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("RequiredAttributeElement", "", null); val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info); try { val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info); } catch (XmlSchemaValidationException) { //XmlExceptionVerifier.IsExceptionOk(e, "Sch_DuplicateAttribute", new string[] { "RequiredAttribute" }); return; } Assert.True(false); } } // ===================== GetUnspecifiedDefaultAttributes ===================== public class TCGetUnspecifiedDefaultAttributes : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCGetUnspecifiedDefaultAttributes(ITestOutputHelper output) : base(output) { _output = output; } [Fact] public void PassNull__Invalid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.GetUnspecifiedDefaultAttributes(null); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void CallTwice() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void NestBetweenValidateAttributeCalls() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); val.ValidateAttribute("req1", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); val.ValidateAttribute("req2", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void CallAfterGetExpectedAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.ValidateAttribute("req1", "", StringGetter("foo"), null); val.GetExpectedAttributes(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void CallAfterValidatingSomeDefaultAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.ValidateAttribute("def1", "", StringGetter("foo"), null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def2" }); val.ValidateAttribute("def2", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { }); return; } [Fact] public void CallOnElementWithFixedAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("FixedAttributeElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "FixedAttribute" }); return; } [Fact] public void v6a() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("FixedRequiredAttributeElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { }); return; } private void CheckDefaultAttributes(ArrayList actual, string[] expected) { int nFound; Assert.Equal(actual.Count, expected.Length); foreach (string str in expected) { nFound = 0; foreach (XmlSchemaAttribute attr in actual) { if (attr.QualifiedName.Name == str) nFound++; } Assert.Equal(nFound, 1); } } } // ===================== ValidateEndOfAttributes ===================== public class TCValidateEndOfAttributes : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCValidateEndOfAttributes(ITestOutputHelper output) : base(output) { _output = output; } [Fact] public void CallOnELementWithNoAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement("NoAttributesElement", "", null); val.ValidateEndOfAttributes(null); return; } [Fact] public void CallAfterValidationOfAllAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); foreach (string attr in new string[] { "req1", "req2", "def1", "def2" }) val.ValidateAttribute(attr, "", StringGetter("foo"), null); val.ValidateEndOfAttributes(null); return; } [Theory] [InlineData("OptionalAttribute")] [InlineData("FixedAttribute")] public void CallWithoutValidationOf_Optional_Fixed_Attributes(String attrType) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement(attrType + "Element", "", null); val.ValidateEndOfAttributes(null); return; } [Theory] [InlineData(true)] [InlineData(false)] public void CallWithoutValidationOfDefaultAttributesGetUnspecifiedDefault_Called_NotCalled(bool call) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("DefaultAttributeElement", "", null); if (call) val.GetUnspecifiedDefaultAttributes(atts); val.ValidateEndOfAttributes(null); return; } [Fact] public void CallWithoutValidationOfRequiredAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("RequiredAttributeElement", "", null); try { val.ValidateEndOfAttributes(null); } catch (XmlSchemaValidationException) { //XmlExceptionVerifier.IsExceptionOk(e, "Sch_MissRequiredAttribute", new string[] { "RequiredAttribute" }); return; } Assert.True(false); } } }
using System; using NUnit.Framework; using System.Threading; using System.Globalization; namespace AbbyyLS.Payments { [TestFixture] public class MoneyTest { [Test] public void InvalidArgsInConstructor() { Assert.Throws<ArgumentNullException>(() => { var mu = new Money(99.99m, null); }); } [TestCase("USD", -0.991)] [TestCase("USD", 20.999)] [TestCase("BYR", 21.00001)] public void NotRounded(string code, decimal amount) { Assert.IsFalse(Iso4217.Parse(code).Money(amount).IsRounded); } [TestCase("USD", 20.95)] [TestCase("USD", 20.5)] [TestCase("USD", -20)] [TestCase("USD", -0.99)] [TestCase("BYR", 20)] [TestCase("BYR", 21)] [TestCase("XAU", 21.00001)] public void IsRounded(string code, decimal amount) { Assert.IsTrue(Iso4217.Parse(code).Money(amount).IsRounded); } [TestCase("USD", 20.95, 2095)] [TestCase("USD", 20.5, 2050)] [TestCase("USD", -20, -2000)] [TestCase("USD", -0.99, -99)] [TestCase("USD", -0.991, -99.1)] [TestCase("USD", 20.999, 2099.9)] [TestCase("BYR", 20, 20)] [TestCase("BYR", 21, 21)] [TestCase("BYR", 21.00001, 21.00001)] public void TotalMinorUnit(string code, decimal amount, decimal exp) { Assert.AreEqual(exp, Iso4217.Parse(code).Money(amount).TotalMinorUnit); } [TestCase("USD", 20.95, 20.95)] [TestCase("USD", 20.953, 20.95)] [TestCase("USD", -20.953, -20.96)] [TestCase("BYR", 20, 20)] [TestCase("BYR", 20.1, 20)] [TestCase("BYR", 20.00001, 20)] [TestCase("BYR", -20.00001, -21)] [TestCase("XDR", 20.00001, 20.00001)] public void FloorMinorUnit(string code, decimal amount, decimal exp) { Assert.AreEqual(exp, Iso4217.Parse(code).Money(amount).FloorMinorUnit().Amount); } [TestCase("USD", 20.95, 20.95)] [TestCase("USD", 20.953, 20.96)] [TestCase("USD", -20.953, -20.95)] [TestCase("BYR", 20, 20)] [TestCase("BYR", 20.1, 21)] [TestCase("BYR", 20.00001, 21)] [TestCase("BYR", -20.00001, -20)] [TestCase("XDR", 20.00001, 20.00001)] [TestCase("BYN", 20.001, 20.01)] public void CeilingMinorUnit(string code, decimal amount, decimal exp) { Assert.AreEqual(exp, Iso4217.Parse(code).Money(amount).CeilingMinorUnit().Amount); } [TestCase("USD", 20, 20)] [TestCase("USD", 20.953, 20)] [TestCase("USD", -20.953, -21)] [TestCase("BYR", 20, 20)] [TestCase("BYR", 20.1, 20)] [TestCase("BYR", 20.00001, 20)] [TestCase("BYR", -20.00001, -21)] [TestCase("BYN", 20.015, 20.01)] public void FloorMajorUnit(string code, decimal amount, decimal exp) { Assert.AreEqual(exp, Iso4217.Parse(code).Money(amount).FloorMajorUnit().Amount); } [TestCase("USD", 20, 20)] [TestCase("USD", 20.953, 21)] [TestCase("USD", -20.953, -20)] [TestCase("BYR", 20, 20)] [TestCase("BYR", 20.1, 21)] [TestCase("BYR", 20.00001, 21)] [TestCase("BYR", -20.00001, -20)] public void CeilingMajorUnit(string code, decimal amount, decimal exp) { Assert.AreEqual(exp, Iso4217.Parse(code).Money(amount).CeilingMajorUnit().Amount); } [Test] public void NoTotalMinorUnit() { Assert.Throws<InvalidOperationException>(() => { var mu = Iso4217.XAU.Money(99.99m).TotalMinorUnit; }); } [Test] public void Equal() { var m1 = Iso4217.RUB.Money(1.23m); var m1E = Iso4217.RUB.Money(1.23m); var m2 = Iso4217.RUB.Money(1.24m); var m3 = Iso4217.USD.Money(1.23m); Assert.AreEqual(m1, m1); Assert.AreNotEqual(m2, m1); Assert.AreNotEqual(m1, m3); Assert.IsTrue(m1 == m1E); Assert.IsFalse(m1 != m1E); Assert.IsTrue(m1 != m3); Assert.IsTrue(m2 != m1); Assert.IsFalse(m1.Equals((object)m3)); Assert.IsFalse(m1.Equals((object)"123")); Assert.IsTrue(m1.Equals((object)m1E)); } [Test] public void Division() { Assert.AreEqual(Iso4217.RUB.Money(1.23m), Iso4217.RUB.Money(2.46m) / 2); } [Test] public void Multiply() { Assert.AreEqual(Iso4217.RUB.Money(2.46m), Iso4217.RUB.Money(1.23m) * 2); Assert.AreEqual(Iso4217.RUB.Money(2.46m), 2 * Iso4217.RUB.Money(1.23m)); } [Test] public void MultiplyWithZero() { Assert.AreEqual(Iso4217.RUB, (Iso4217.RUB.Money(1.23m) * 0).Currency); Assert.AreEqual(Iso4217.RUB, (0 * Iso4217.RUB.Money(1.23m)).Currency); } [Test] public void Show() { CultureInfo ci = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; Assert.AreEqual("1.23 RUB", Iso4217.RUB.Money(1.23m).ToString()); Assert.AreEqual("1.123456789012345678900876523 USD", Iso4217.USD.Money(1.123456789012345678900876523m).ToString()); } [Test] public void InvalidMatch() { var l = Iso4217.EUR.Money(1.23m); var r = Iso4217.RUB.Money(2.23m); Assert.Throws<InvalidOperationException>(() => { var res = l < r; }); } [Test] public void InvalidMatchZero() { var l = Iso4217.EUR.Money(0m); var r = Iso4217.RUB.Money(0m); Assert.Throws<InvalidOperationException>(() => { var res = l < r; }); } [Test] public void MatchOperators() { var l = Iso4217.RUB.Money(1.23m); var r = Iso4217.RUB.Money(2.23m); var rE = Iso4217.RUB.Money(2.23m); Assert.IsTrue(l < r); Assert.IsTrue(l <= r); Assert.IsTrue(r <= rE); Assert.IsFalse(r < l); Assert.IsFalse(r <= l); Assert.IsFalse(l > r); Assert.IsFalse(l >= r); Assert.IsTrue(r >= rE); Assert.IsTrue(r > l); Assert.IsTrue(r >= l); } [Test] public void InvalidAdditional() { var m1 = Iso4217.EUR.Money(1m); var m2 = Iso4217.RUB.Money(2m); Assert.Throws<InvalidOperationException>(() => { var res = m1 + m2; }); } [Test] public void Additional() { var m1 = Iso4217.EUR.Money(1m); var m2 = Iso4217.EUR.Money(2m); var m3 = Iso4217.EUR.Money(3m); Assert.AreEqual(m3, m1 + m2); } [Test] public void InvalidSubtract() { var m1 = Iso4217.EUR.Money(1m); var m2 = Iso4217.RUB.Money(2m); Assert.Throws<InvalidOperationException>(() => { var res = m1 - m2; }); } [Test] public void Subtract() { var m1 = Iso4217.EUR.Money(1m); var m2 = Iso4217.EUR.Money(2m); var m3 = Iso4217.EUR.Money(-1m); Assert.AreEqual(m3, m1 - m2); Assert.AreEqual(Iso4217.EUR, (m1 - m1).Currency); } [Test] public void HashCode() { var m1 = Iso4217.RUB.Money(1m).GetHashCode(); var m1E = Iso4217.RUB.Money(1m).GetHashCode(); var m2 = Iso4217.EUR.Money(2m).GetHashCode(); var m3 = Iso4217.EUR.Money(-1m).GetHashCode(); Assert.AreEqual(m1, m1E); Assert.AreNotEqual(m1, m2); Assert.AreNotEqual(m3, m2); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.Rooms; using osu.Game.Rulesets; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Online { [HeadlessTest] public class TestSceneOnlinePlayBeatmapAvailabilityTracker : OsuTestScene { private RulesetStore rulesets; private TestBeatmapManager beatmaps; private string testBeatmapFile; private BeatmapInfo testBeatmapInfo; private BeatmapSetInfo testBeatmapSet; private readonly Bindable<PlaylistItem> selectedItem = new Bindable<PlaylistItem>(); private OnlinePlayBeatmapAvailabilityTracker availabilityTracker; [BackgroundDependencyLoader] private void load(AudioManager audio, GameHost host) { Dependencies.Cache(rulesets = new RulesetStore(ContextFactory)); Dependencies.CacheAs<BeatmapManager>(beatmaps = new TestBeatmapManager(LocalStorage, ContextFactory, rulesets, API, audio, Resources, host, Beatmap.Default)); } [SetUp] public void SetUp() => Schedule(() => { beatmaps.AllowImport = new TaskCompletionSource<bool>(); testBeatmapFile = TestResources.GetQuickTestBeatmapForImport(); testBeatmapInfo = getTestBeatmapInfo(testBeatmapFile); testBeatmapSet = testBeatmapInfo.BeatmapSet; var existing = beatmaps.QueryBeatmapSet(s => s.OnlineBeatmapSetID == testBeatmapSet.OnlineBeatmapSetID); if (existing != null) beatmaps.Delete(existing); selectedItem.Value = new PlaylistItem { Beatmap = { Value = testBeatmapInfo }, Ruleset = { Value = testBeatmapInfo.Ruleset }, }; Child = availabilityTracker = new OnlinePlayBeatmapAvailabilityTracker { SelectedItem = { BindTarget = selectedItem, } }; }); [Test] public void TestBeatmapDownloadingFlow() { AddAssert("ensure beatmap unavailable", () => !beatmaps.IsAvailableLocally(testBeatmapSet)); addAvailabilityCheckStep("state not downloaded", BeatmapAvailability.NotDownloaded); AddStep("start downloading", () => beatmaps.Download(testBeatmapSet)); addAvailabilityCheckStep("state downloading 0%", () => BeatmapAvailability.Downloading(0.0f)); AddStep("set progress 40%", () => ((TestDownloadRequest)beatmaps.GetExistingDownload(testBeatmapSet)).SetProgress(0.4f)); addAvailabilityCheckStep("state downloading 40%", () => BeatmapAvailability.Downloading(0.4f)); AddStep("finish download", () => ((TestDownloadRequest)beatmaps.GetExistingDownload(testBeatmapSet)).TriggerSuccess(testBeatmapFile)); addAvailabilityCheckStep("state importing", BeatmapAvailability.Importing); AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddUntilStep("wait for import", () => beatmaps.CurrentImportTask?.IsCompleted == true); addAvailabilityCheckStep("state locally available", BeatmapAvailability.LocallyAvailable); } [Test] public void TestTrackerRespectsSoftDeleting() { AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddStep("import beatmap", () => beatmaps.Import(testBeatmapFile).Wait()); addAvailabilityCheckStep("state locally available", BeatmapAvailability.LocallyAvailable); AddStep("delete beatmap", () => beatmaps.Delete(beatmaps.QueryBeatmapSet(b => b.OnlineBeatmapSetID == testBeatmapSet.OnlineBeatmapSetID))); addAvailabilityCheckStep("state not downloaded", BeatmapAvailability.NotDownloaded); AddStep("undelete beatmap", () => beatmaps.Undelete(beatmaps.QueryBeatmapSet(b => b.OnlineBeatmapSetID == testBeatmapSet.OnlineBeatmapSetID))); addAvailabilityCheckStep("state locally available", BeatmapAvailability.LocallyAvailable); } [Test] public void TestTrackerRespectsChecksum() { AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddStep("import altered beatmap", () => { beatmaps.Import(TestResources.GetTestBeatmapForImport(true)).Wait(); }); addAvailabilityCheckStep("state still not downloaded", BeatmapAvailability.NotDownloaded); AddStep("recreate tracker", () => Child = availabilityTracker = new OnlinePlayBeatmapAvailabilityTracker { SelectedItem = { BindTarget = selectedItem } }); addAvailabilityCheckStep("state not downloaded as well", BeatmapAvailability.NotDownloaded); } private void addAvailabilityCheckStep(string description, Func<BeatmapAvailability> expected) { AddAssert(description, () => availabilityTracker.Availability.Value.Equals(expected.Invoke())); } private static BeatmapInfo getTestBeatmapInfo(string archiveFile) { BeatmapInfo info; using (var archive = new ZipArchiveReader(File.OpenRead(archiveFile))) using (var stream = archive.GetStream("Soleily - Renatus (Gamu) [Insane].osu")) using (var reader = new LineBufferedReader(stream)) { var decoder = Decoder.GetDecoder<Beatmap>(reader); var beatmap = decoder.Decode(reader); info = beatmap.BeatmapInfo; info.BeatmapSet.Beatmaps = new List<BeatmapInfo> { info }; info.BeatmapSet.Metadata = info.Metadata; info.MD5Hash = stream.ComputeMD5Hash(); info.Hash = stream.ComputeSHA2Hash(); } return info; } private class TestBeatmapManager : BeatmapManager { public TaskCompletionSource<bool> AllowImport = new TaskCompletionSource<bool>(); public Task<ILive<BeatmapSetInfo>> CurrentImportTask { get; private set; } public TestBeatmapManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, [NotNull] AudioManager audioManager, IResourceStore<byte[]> resources, GameHost host = null, WorkingBeatmap defaultBeatmap = null) : base(storage, contextFactory, rulesets, api, audioManager, resources, host, defaultBeatmap) { } protected override BeatmapModelManager CreateBeatmapModelManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, GameHost host) { return new TestBeatmapModelManager(this, storage, contextFactory, rulesets, api, host); } protected override BeatmapModelDownloader CreateBeatmapModelDownloader(IBeatmapModelManager manager, IAPIProvider api, GameHost host) { return new TestBeatmapModelDownloader(manager, api, host); } internal class TestBeatmapModelDownloader : BeatmapModelDownloader { public TestBeatmapModelDownloader(IBeatmapModelManager modelManager, IAPIProvider apiProvider, GameHost gameHost) : base(modelManager, apiProvider, gameHost) { } protected override ArchiveDownloadRequest<BeatmapSetInfo> CreateDownloadRequest(BeatmapSetInfo set, bool minimiseDownloadSize) => new TestDownloadRequest(set); } internal class TestBeatmapModelManager : BeatmapModelManager { private readonly TestBeatmapManager testBeatmapManager; public TestBeatmapModelManager(TestBeatmapManager testBeatmapManager, Storage storage, IDatabaseContextFactory databaseContextFactory, RulesetStore rulesetStore, IAPIProvider apiProvider, GameHost gameHost) : base(storage, databaseContextFactory, rulesetStore, gameHost) { this.testBeatmapManager = testBeatmapManager; } public override async Task<ILive<BeatmapSetInfo>> Import(BeatmapSetInfo item, ArchiveReader archive = null, bool lowPriority = false, CancellationToken cancellationToken = default) { await testBeatmapManager.AllowImport.Task.ConfigureAwait(false); return await (testBeatmapManager.CurrentImportTask = base.Import(item, archive, lowPriority, cancellationToken)).ConfigureAwait(false); } } } private class TestDownloadRequest : ArchiveDownloadRequest<BeatmapSetInfo> { public new void SetProgress(float progress) => base.SetProgress(progress); public new void TriggerSuccess(string filename) => base.TriggerSuccess(filename); public TestDownloadRequest(BeatmapSetInfo model) : base(model) { } protected override string Target => null; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesPutSettings2 { public partial class IndicesPutSettings2YamlTests { public class IndicesPutSettings2AllPathOptionsYamlBase : YamlTestsBase { public IndicesPutSettings2AllPathOptionsYamlBase() : base() { //do indices.create this.Do(()=> _client.IndicesCreate("test_index1", null)); //do indices.create this.Do(()=> _client.IndicesCreate("test_index2", null)); //do indices.create this.Do(()=> _client.IndicesCreate("foo", null)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsPerIndex2Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsPerIndex2Test() { //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("test_index1", _body)); //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("test_index2", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //is_false _response.foo.settings.index.refresh_interval; this.IsFalse(_response.foo.settings.index.refresh_interval); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsInAllIndex3Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsInAllIndex3Test() { //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("_all", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //match _response.foo.settings.index.refresh_interval: this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsInIndex4Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsInIndex4Test() { //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("*", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //match _response.foo.settings.index.refresh_interval: this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsInPrefixIndex5Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsInPrefixIndex5Test() { //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("test*", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //is_false _response.foo.settings.index.refresh_interval; this.IsFalse(_response.foo.settings.index.refresh_interval); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsInListOfIndices6Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsInListOfIndices6Test() { //skip 1 - 999; this.Skip("1 - 999", "list of indices not implemented yet"); //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettings("test_index1, test_index2", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //is_false _response.foo.settings.index.refresh_interval; this.IsFalse(_response.foo.settings.index.refresh_interval); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class PutSettingsInBlankIndex7Tests : IndicesPutSettings2AllPathOptionsYamlBase { [Test] public void PutSettingsInBlankIndex7Test() { //do indices.put_settings _body = new { refresh_interval= "1s" }; this.Do(()=> _client.IndicesPutSettingsForAll(_body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettingsForAll()); //match _response.test_index1.settings.index.refresh_interval: this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s"); //match _response.test_index2.settings.index.refresh_interval: this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s"); //match _response.foo.settings.index.refresh_interval: this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s"); } } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.Drawing.Imaging; using System.ComponentModel; // ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** namespace SoftLogik.Win { namespace UI { namespace Docking { [ToolboxItem(false)]public class PopupButton : Button { private enum RepeatClickStatus { Disabled, Started, Repeating, Stopped } private class RepeatClickEventArgs : EventArgs { private static RepeatClickEventArgs _empty; static RepeatClickEventArgs() { _empty = new RepeatClickEventArgs(); } public static new RepeatClickEventArgs Empty { get { return _empty; } } } #region Private fields private IContainer components = new Container(); private bool m_isActivated = false; private int m_borderWidth = 1; private bool m_mouseOver = false; private bool m_mouseCapture = false; private bool m_isPopup = false; private Image m_imageEnabled = null; private Image m_imageDisabled = null; private int m_imageIndexEnabled = - 1; private int m_imageIndexDisabled = - 1; private bool m_monochrom = true; private ToolTip m_toolTip = null; private string m_toolTipText = ""; private Color m_borderColor = Color.Empty; private Color m_activeGradientBegin = Color.Empty; private Color m_activeGradientEnd = Color.Empty; private Color m_inactiveGradientBegin = Color.Empty; private Color m_inactiveGradientEnd = Color.Empty; private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled; private int m_repeatClickDelay = 500; private int m_repeatClickInterval = 100; private Timer m_timer; #endregion #region Public Methods public PopupButton() { InternalConstruct(null, null); } public PopupButton(Image c_imageEnabled) { InternalConstruct(c_imageEnabled, null); } public PopupButton(Image c_imageEnabled, Image c_imageDisabled) { InternalConstruct(c_imageEnabled, c_imageDisabled); } #endregion #region Private Methods private void InternalConstruct(Image c_imageEnabled, Image c_imageDisabled) { // Remember parameters this.ImageEnabled = c_imageEnabled; this.ImageDisabled = c_imageDisabled; // Prevent drawing flicker by blitting from memory in WM_PAINT SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // Prevent base class from trying to generate double click events and // so testing clicks against the double click time and rectangle. Getting // rid of this allows the user to press then release button very quickly. //SetStyle(ControlStyles.StandardDoubleClick, false); // Should not be allowed to select this control SetStyle(ControlStyles.Selectable, false); m_timer = new Timer(); m_timer.Enabled = false; m_timer.Tick += new System.EventHandler(Timer_Tick); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private bool ShouldSerializeBorderColor() { return (m_borderColor != Color.Empty); } private bool ShouldSerializeImageEnabled() { return (m_imageEnabled != null); } private bool ShouldSerializeImageDisabled() { return (m_imageDisabled != null); } private void DrawBackground(Graphics g) { if (m_mouseOver) { if (m_isActivated) { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(156, 182, 231), Color.FromArgb(156, 182, 231), LinearGradientMode.Vertical)) { g.FillRectangle(brush, ClientRectangle); } } else { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, Color.FromArgb(236, 233, 216), Color.FromArgb(236, 233, 216), LinearGradientMode.Vertical)) { g.FillRectangle(brush, ClientRectangle); } } } else { if (m_isActivated) { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, ActiveBackColorGradientBegin, ActiveBackColorGradientEnd, LinearGradientMode.Vertical)) { g.FillRectangle(brush, ClientRectangle); } } else { using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, InactiveBackColorGradientBegin, InactiveBackColorGradientEnd, LinearGradientMode.Vertical)) { g.FillRectangle(brush, ClientRectangle); } } } } private void DrawImage(Graphics g) { Image image; if (this.Enabled) { image = this.ImageEnabled; } else { if (ImageDisabled != null) { image = this.ImageDisabled; } else { image = this.ImageEnabled; } } ImageAttributes imageAttr = null; if (image == null) { return; } if (m_monochrom) { imageAttr = new ImageAttributes(); // transform the monochrom image // white -> BackColor // black -> ForeColor ColorMap[] myColorMap = new ColorMap[2]; myColorMap[0] = new ColorMap(); myColorMap[0].OldColor = Color.White; myColorMap[0].NewColor = Color.Transparent; myColorMap[1] = new ColorMap(); myColorMap[1].OldColor = Color.Black; myColorMap[1].NewColor = this.ForeColor; imageAttr.SetRemapTable(myColorMap); } Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); if ((! Enabled) && (ImageDisabled == null)) { using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size)) { if (imageAttr != null) { using (Graphics gMono = Graphics.FromImage(bitmapMono)) { gMono.DrawImage(image, new Point[3] {new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1)}, rect, GraphicsUnit.Pixel, imageAttr); } } ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor); } } else { // Three points provided are upper-left, upper-right and // lower-left of the destination parallelogram. Point[] pts = new Point[3](); if (Enabled && m_mouseOver && m_mouseCapture) { pts[0].X = 1; pts[0].Y = 1; } else { pts[0].X = 0; pts[0].Y = 0; } pts[1].X = pts[0].X + ClientRectangle.Width; pts[1].Y = pts[0].Y; pts[2].X = pts[0].X; pts[2].Y = pts[1].Y + ClientRectangle.Height; if (imageAttr == null) { g.DrawImage(image, pts, rect, GraphicsUnit.Pixel); } else { g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr); } } } private void DrawText(Graphics g) { if (Text == string.Empty) { return; } Rectangle rect = ClientRectangle; rect.X += BorderWidth; rect.Y += BorderWidth; rect.Width -= 2 * BorderWidth; rect.Height -= 2 * BorderWidth; StringFormat stringFormat = new StringFormat(); if (TextAlign == ContentAlignment.TopLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.TopCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.TopRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Near; } else if (TextAlign == ContentAlignment.MiddleLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.MiddleCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.MiddleRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Center; } else if (TextAlign == ContentAlignment.BottomLeft) { stringFormat.Alignment = StringAlignment.Near; stringFormat.LineAlignment = StringAlignment.Far; } else if (TextAlign == ContentAlignment.BottomCenter) { stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Far; } else if (TextAlign == ContentAlignment.BottomRight) { stringFormat.Alignment = StringAlignment.Far; stringFormat.LineAlignment = StringAlignment.Far; } using (Brush brush = new SolidBrush(ForeColor)) { g.DrawString(Text, Font, brush, rect, stringFormat); } } private void DrawBorder(Graphics g) { ButtonBorderStyle bs; // Decide on the type of border to draw around image if (! this.Enabled) { if (IsPopup) { bs = ButtonBorderStyle.Outset; } else { bs = ButtonBorderStyle.Solid; } } else if (m_mouseOver && m_mouseCapture) { bs = ButtonBorderStyle.Inset; } else if (IsPopup || m_mouseOver) { if (m_isActivated) { BorderColor = Color.FromArgb(60, 90, 170); } else { BorderColor = Color.FromArgb(140, 134, 123); } bs = ButtonBorderStyle.Solid; } else { bs = ButtonBorderStyle.Solid; } Color colorLeftTop; Color colorRightBottom; if (bs == ButtonBorderStyle.Solid) { colorLeftTop = this.BorderColor; colorRightBottom = this.BorderColor; } else if (bs == ButtonBorderStyle.Outset) { if (m_borderColor.IsEmpty) { colorLeftTop = this.BackColor; } else { colorLeftTop = m_borderColor; } colorRightBottom = this.BackColor; } else { colorLeftTop = this.BackColor; if (m_borderColor.IsEmpty) { colorRightBottom = this.BackColor; } else { colorRightBottom = m_borderColor; } } ControlPaint.DrawBorder(g, ClientRectangle, colorLeftTop, m_borderWidth, bs, colorLeftTop, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs, colorRightBottom, m_borderWidth, bs); } #endregion #region Properties public bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; } } [Category("Appearance")]public System.Drawing.Color ActiveBackColorGradientBegin { get { return m_activeGradientBegin; } set { m_activeGradientBegin = value; } } [Category("Appearance")]public System.Drawing.Color ActiveBackColorGradientEnd { get { return m_activeGradientEnd; } set { m_activeGradientEnd = value; } } [Category("Appearance")]public System.Drawing.Color InactiveBackColorGradientBegin { get { return m_inactiveGradientBegin; } set { m_inactiveGradientBegin = value; } } [Category("Appearance")]public System.Drawing.Color InactiveBackColorGradientEnd { get { return m_inactiveGradientEnd; } set { m_inactiveGradientEnd = value; } } [Category("Appearance")]public Color BorderColor { get { return m_borderColor; } set { if (m_borderColor != value) { m_borderColor = value; Invalidate(); } } } [Category("Appearance")][DefaultValue(1)]public int BorderWidth { get { return m_borderWidth; } set { if (value < 1) { value = 1; } if (m_borderWidth != value) { m_borderWidth = value; Invalidate(); } } } [Category("Appearance")]public Image ImageEnabled { get { if (m_imageEnabled != null) { return m_imageEnabled; } try { if (ImageList == null || ImageIndexEnabled == - 1) { return null; } else { return ImageList.Images[m_imageIndexEnabled]; } } catch { return null; } } set { if (!(value is m_imageEnabled)) { m_imageEnabled = value; Invalidate(); } } } [Category("Appearance")]public Image ImageDisabled { get { if (m_imageDisabled != null) { return m_imageDisabled; } try { if (ImageList == null || ImageIndexDisabled == - 1) { return null; } else { return ImageList.Images[m_imageIndexDisabled]; } } catch { return null; } } set { if (m_imageDisabled == value) { m_imageDisabled = value; Invalidate(); } } } [Category("Appearance")][DefaultValue(- 1)][Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design", "System.Drawing.Design.UITypeEditor,System.Drawing")][TypeConverter(typeof(System.Windows.Forms.ImageIndexConverter))][RefreshProperties(RefreshProperties.Repaint)]public int ImageIndexEnabled { get { return m_imageIndexEnabled; } set { if (m_imageIndexEnabled != value) { m_imageIndexEnabled = value; Invalidate(); } } } [Category("Appearance")][DefaultValue(- 1)][Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design", "System.Drawing.Design.UITypeEditor,System.Drawing")][TypeConverter(typeof(System.Windows.Forms.ImageIndexConverter))][RefreshProperties(RefreshProperties.Repaint)]public int ImageIndexDisabled { get { return m_imageIndexDisabled; } set { if (m_imageIndexDisabled != value) { m_imageIndexDisabled = value; Invalidate(); } } } [Category("Appearance")][DefaultValue(false)]public bool IsPopup { get { return m_isPopup; } set { if (m_isPopup != value) { m_isPopup = value; Invalidate(); } } } [Category("Appearance")][DefaultValue(true)]public bool Monochrome { get { return m_monochrom; } set { if (value != m_monochrom) { m_monochrom = value; Invalidate(); } } } [Category("Behavior")][DefaultValue(false)]public bool RepeatClick { get { return (ClickStatus != RepeatClickStatus.Disabled); } set { ClickStatus = RepeatClickStatus.Stopped; } } private RepeatClickStatus ClickStatus { get { return m_clickStatus; } set { if (m_clickStatus == value) { return; } m_clickStatus = value; if (ClickStatus == RepeatClickStatus.Started) { Timer.Interval = RepeatClickDelay; Timer.Enabled = true; } else if (ClickStatus == RepeatClickStatus.Repeating) { Timer.Interval = RepeatClickInterval; } else { Timer.Enabled = false; } } } [Category("Behavior")][DefaultValue(500)]public int RepeatClickDelay { get { return m_repeatClickDelay; } set { m_repeatClickDelay = value; } } [Category("Behavior")][DefaultValue(100)]public int RepeatClickInterval { get { return m_repeatClickInterval; } set { m_repeatClickInterval = value; } } private Timer Timer { get { return m_timer; } } [Category("Appearance")][DefaultValue("")]public string ToolTipText { get { return m_toolTipText; } set { if (m_toolTipText != value) { if (m_toolTip == null) { m_toolTip = new ToolTip(this.components); } m_toolTipText = value; m_toolTip.SetToolTip(this, value); } } } #endregion #region Events private void Timer_Tick(object sender, EventArgs e) { if (m_mouseCapture && m_mouseOver) { OnClick(RepeatClickEventArgs.Empty); } if (ClickStatus == RepeatClickStatus.Started) { ClickStatus = RepeatClickStatus.Repeating; } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button != System.Windows.Forms.MouseButtons.Left) { return; } if (m_mouseCapture == false || m_mouseOver == false) { m_mouseCapture = true; m_mouseOver = true; //Redraw to show button state Invalidate(); } if (RepeatClick) { OnClick(RepeatClickEventArgs.Empty); ClickStatus = RepeatClickStatus.Started; } } protected override void OnClick(EventArgs e) { if (RepeatClick && !(e is RepeatClickEventArgs)) { return; } base.OnClick(e); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button != System.Windows.Forms.MouseButtons.Left) { return; } if (m_mouseOver == true || m_mouseCapture == true) { m_mouseOver = false; m_mouseCapture = false; // Redraw to show button state Invalidate(); } if (RepeatClick) { ClickStatus = RepeatClickStatus.Stopped; } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); // Is mouse point inside our client rectangle bool over = this.ClientRectangle.Contains(new Point(e.X, e.Y)); // If entering the button area or leaving the button area... if (over != m_mouseOver) { // Update state m_mouseOver = over; // Redraw to show button state Invalidate(); } } protected override void OnMouseEnter(EventArgs e) { // Update state to reflect mouse over the button area if (! m_mouseOver) { m_mouseOver = true; // Redraw to show button state Invalidate(); } base.OnMouseEnter(e); } protected override void OnMouseLeave(EventArgs e) { // Update state to reflect mouse not over the button area if (m_mouseOver) { m_mouseOver = false; // Redraw to show button state Invalidate(); } base.OnMouseLeave(e); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); DrawBackground(e.Graphics); DrawImage(e.Graphics); DrawText(e.Graphics); if (m_mouseOver || m_mouseCapture) { DrawBorder(e.Graphics); } } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); if (Enabled == false) { m_mouseOver = false; m_mouseCapture = false; if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped) { ClickStatus = RepeatClickStatus.Stopped; } } Invalidate(); } #endregion private void InitializeComponent() { this.SuspendLayout(); // //PopupButton // this.AutoSize = true; this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.ResumeLayout(false); } } } } }
using System; using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; namespace Rainbow.Framework.Content.Data { /// <summary> /// This class encapsulates the basic attributes of a Question, and is used /// by the administration pages when manipulating questions. QuestionItem implements /// the IComparable interface so that an ArrayList of QuestionItems may be sorted /// by TabOrder, using the ArrayList//s Sort() method. /// </summary> public class QuestionItem : IComparable { private int _QuestionOrder; private string _name; private int _id; private string _TypeOption; /// <summary> /// /// </summary> public string TypeOption { get { return _TypeOption; } set { _TypeOption = value; } } /// <summary> /// /// </summary> public int QuestionOrder { get { return _QuestionOrder; } set { _QuestionOrder = value; } } /// <summary> /// /// </summary> public string QuestionName { get { return _name; } set { _name = value; } } /// <summary> /// /// </summary> public int QuestionID { get { return _id; } set { _id = value; } } // public virtual int IComparable.CompareTo:CompareTo:(object value) /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual int CompareTo(object value) { if (value == null) { return 1; } int compareOrder = ((QuestionItem) value).QuestionOrder; if (QuestionOrder == compareOrder) { return 0; } if (QuestionOrder < compareOrder) { return -1; } if (QuestionOrder > compareOrder) { return 1; } return 0; } } /// <summary> /// This class encapsulates the basic attributes of an Option, and is used /// by the administration pages when manipulating questions/options. OptionItem implements /// the IComparable interface so that an ArrayList of OptionItems may be sorted /// by TabOrder, using the ArrayList//s Sort() method. /// </summary> public class OptionItem : IComparable { private int _OptionOrder; private string _name; private int _id; /// <summary> /// /// </summary> public int OptionOrder { get { return _OptionOrder; } set { _OptionOrder = value; } } /// <summary> /// /// </summary> public string OptionName { get { return _name; } set { _name = value; } } /// <summary> /// /// </summary> public int OptionID { get { return _id; } set { _id = value; } } // public virtual int : IComparable.CompareTo CompareTo( object value) // JLH!! /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual int CompareTo(object value) { if (value == null) { return 1; } int compareOrder = ((OptionItem) value).OptionOrder; if (OptionOrder == compareOrder) { return 0; } if (OptionOrder < compareOrder) { return -1; } if (OptionOrder > compareOrder) { return 1; } return 0; } } /// <summary> /// IBS Tasks module /// Class that encapsulates all data logic necessary to add/query/delete /// surveys within the Portal database. /// Moved into Rainbow by Jakob Hansen /// </summary> public class SurveyDB { /// <summary> /// The GetQuestions method returns a SqlDataReader containing all of the /// questions for a specific portal module. /// Other relevant sources: /// GetSurveyQuestions Stored Procedure /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetQuestions(int moduleID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyQuestions", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); // Execute the command and return the datareader myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetOptions method returns a SqlDataReader containing all of the /// options for a specific portal module. /// Other relevant sources: /// GetSurveyOptions Stored Procedure /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="TypeOption">The type option.</param> /// <returns></returns> public SqlDataReader GetOptions(int moduleID, string TypeOption) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyOptions", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterTypeOption = new SqlParameter("@TypeOption", SqlDbType.NVarChar, 2); parameterTypeOption.Value = TypeOption; myCommand.Parameters.Add(parameterTypeOption); // Execute the command and return the datareader myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetOptionList method returns a SqlDataReader containing all of the /// options for a specific QuestionID. /// Other relevant sources: /// GetSurveyOptionList Stored Procedure /// </summary> /// <param name="QuestionID">The question ID.</param> /// <returns></returns> public SqlDataReader GetOptionList(int QuestionID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyOptionList", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); // Execute the command and return the datareader myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetAnswers method returns a SqlDataReader containing all of the /// answers for a specific SurveyID. /// Other relevant sources: /// rb_GetSurveyAnswers Stored Procedure /// </summary> /// <param name="SurveyID">The survey ID.</param> /// <returns></returns> public SqlDataReader GetAnswers(int SurveyID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyAnswers", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterSurveyID = new SqlParameter("@SurveyID", SqlDbType.Int, 4); parameterSurveyID.Value = SurveyID; myCommand.Parameters.Add(parameterSurveyID); // Execute the command and return the datareader myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetSurveyID method returns the SurveyID from rb_Surveys table /// for a specific ModuleID. /// Other relevant sources: /// rb_GetSurveyID Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <returns></returns> public int GetSurveyID(int ModuleID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyID", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterSurveyID = new SqlParameter("@SurveyID", SqlDbType.Int, 4); parameterSurveyID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterSurveyID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterSurveyID.Value; } /// <summary> /// The GetQuestionList method returns a SqlDataReader containing all of the /// questions for a specific SurveyID. /// Other relevant sources: /// GetSurveyQuestionList Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <returns></returns> public SqlDataReader GetQuestionList(int ModuleID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyQuestionList", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); // Execute the command and return the datareader myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The AddAnswer method add a record in rb_SurveyAnswers table /// for a specific SurveyID and QuestionID. /// Other relevant sources: /// rb_AddSurveyAnswer Stored Procedure /// </summary> /// <param name="SurveyID">The survey ID.</param> /// <param name="QuestionID">The question ID.</param> /// <param name="OptionID">The option ID.</param> /// <returns></returns> public int AddAnswer(int SurveyID, int QuestionID, int OptionID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddSurveyAnswer", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterSurveyID = new SqlParameter("@SurveyID", SqlDbType.Int, 4); parameterSurveyID.Value = SurveyID; myCommand.Parameters.Add(parameterSurveyID); SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); SqlParameter parameterOptionID = new SqlParameter("@OptionID", SqlDbType.Int, 4); parameterOptionID.Value = OptionID; myCommand.Parameters.Add(parameterOptionID); SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterItemID.Value; } /// <summary> /// The AddQuestion method add a record in rb_SurveyQuestions table /// for a specific SurveyID. /// Other relevant sources: /// rb_AddSurveyQuestion Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <param name="Question">The question.</param> /// <param name="ViewOrder">The view order.</param> /// <param name="TypeOption">The type option.</param> /// <returns></returns> public int AddQuestion(int ModuleID, string Question, int ViewOrder, string TypeOption) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddSurveyQuestion", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterQuestion = new SqlParameter("@Question", SqlDbType.NVarChar, 500); parameterQuestion.Value = Question; myCommand.Parameters.Add(parameterQuestion); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = ViewOrder; myCommand.Parameters.Add(parameterViewOrder); SqlParameter parameterTypeOption = new SqlParameter("@TypeOption", SqlDbType.NVarChar, 2); parameterTypeOption.Value = TypeOption; myCommand.Parameters.Add(parameterTypeOption); SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterQuestionID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterQuestionID.Value; } /// <summary> /// The AddOption method add a record in rb_SurveyOptions table /// for a specific QuestionID. /// Other relevant sources: /// rb_AddSurveyOption Stored Procedure /// </summary> /// <param name="QuestionID">The question ID.</param> /// <param name="OptionDesc">The option desc.</param> /// <param name="ViewOrder">The view order.</param> /// <returns></returns> public int AddOption(int QuestionID, string OptionDesc, int ViewOrder) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddSurveyOption", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); SqlParameter parameterOptionDesc = new SqlParameter("@OptionDesc", SqlDbType.NVarChar, 500); parameterOptionDesc.Value = OptionDesc; myCommand.Parameters.Add(parameterOptionDesc); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = ViewOrder; myCommand.Parameters.Add(parameterViewOrder); SqlParameter parameterOptionID = new SqlParameter("@OptionID", SqlDbType.Int, 4); parameterOptionID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterOptionID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterOptionID.Value; } /// <summary> /// The DelQuestion method delete a record in rb_SurveyQuestions table /// for a specific QuestionID. /// Other relevant sources: /// rb_DelSurveyQuestion Stored Procedure /// </summary> /// <param name="QuestionID">The question ID.</param> /// <returns></returns> public int DelQuestion(int QuestionID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DelSurveyQuestion", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return 1; } /// <summary> /// The DelOption method delete a record in rb_SurveyOptions table /// for a specific OptionID. /// Other relevant sources: /// rb_DelSurveyOption Stored Procedure /// </summary> /// <param name="OptionID">The option ID.</param> /// <returns></returns> public int DelOption(int OptionID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DelSurveyOption", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterOptionID = new SqlParameter("@OptionID", SqlDbType.Int, 4); parameterOptionID.Value = OptionID; myCommand.Parameters.Add(parameterOptionID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return 1; } /// <summary> /// The UpdateQuestionOrder method set the new ViewOrder in the /// rb_SurveyQuestions table for a specific QuestionID. /// Other relevant sources: /// rb_UpdateSurveyQuestionOrder Stored Procedure /// </summary> /// <param name="QuestionID">The question ID.</param> /// <param name="Order">The order.</param> /// <returns></returns> public int UpdateQuestionOrder(int QuestionID, int Order) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateSurveyQuestionOrder", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); SqlParameter parameterOrder = new SqlParameter("@Order", SqlDbType.Int, 4); parameterOrder.Value = Order; myCommand.Parameters.Add(parameterOrder); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return 1; } /// <summary> /// The UpdateOptionOrder method set the new ViewOrder in the /// rb_SurveyOptions table for a specific OptionID. /// Other relevant sources: /// rb_UpdateSurveyOptionOrder Stored Procedure /// </summary> /// <param name="OptionID">The option ID.</param> /// <param name="Order">The order.</param> /// <returns></returns> public int UpdateOptionOrder(int OptionID, int Order) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateSurveyOptionOrder", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameteroptionID = new SqlParameter("@OptionID", SqlDbType.Int, 4); parameteroptionID.Value = OptionID; myCommand.Parameters.Add(parameteroptionID); SqlParameter parameterOrder = new SqlParameter("@Order", SqlDbType.Int, 4); parameterOrder.Value = Order; myCommand.Parameters.Add(parameterOrder); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return 1; } /// <summary> /// The GetAnswerNum method get the number of answers /// for a specific SurveyID and QuestionID. /// Other relevant sources: /// rb_GetSurveyAnswersNum Stored Procedure /// </summary> /// <param name="SurveyID">The survey ID.</param> /// <param name="QuestionID">The question ID.</param> /// <returns></returns> public int GetAnswerNum(int SurveyID, int QuestionID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyAnswersNum", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterSurveyID = new SqlParameter("@SurveyID", SqlDbType.Int, 4); parameterSurveyID.Value = SurveyID; myCommand.Parameters.Add(parameterSurveyID); SqlParameter parameterQuestionID = new SqlParameter("@QuestionID", SqlDbType.Int, 4); parameterQuestionID.Value = QuestionID; myCommand.Parameters.Add(parameterQuestionID); SqlParameter parameterNum = new SqlParameter("@NumAnswer", SqlDbType.Int, 4); parameterNum.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterNum); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterNum.Value; } /// <summary> /// The ExistSurvey method checks whether the Survey exists in rb_Surveys /// table for a specific ModuleID. /// Other relevant sources: /// rb_ExistSurvey Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <returns></returns> public int ExistSurvey(int ModuleID) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ExistSurvey", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterRowCount = new SqlParameter("@RowCount", SqlDbType.Int, 4); parameterRowCount.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterRowCount); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterRowCount.Value; } /// <summary> /// The ExistAddSurvey method checks whether the Survey exists in rb_Surveys /// table for a specific ModuleID, if not it creates a new one. /// Other relevant sources: /// rb_ExistAddSurvey Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <param name="CreatedByUser">The created by user.</param> /// <returns></returns> public string ExistAddSurvey(int ModuleID, string CreatedByUser) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_ExistAddSurvey", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterCreatedByUser = new SqlParameter("@CreatedByUser", SqlDbType.NVarChar, 100); parameterCreatedByUser.Value = CreatedByUser; myCommand.Parameters.Add(parameterCreatedByUser); SqlParameter parameterSurveyDesc = new SqlParameter("@SurveyDesc", SqlDbType.NVarChar, 500); parameterSurveyDesc.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterSurveyDesc); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (string) parameterSurveyDesc.Value; } /// <summary> /// The GetDimArrays method get the dimensionof the arrays /// for a specific ModuleID and TypeOption. /// Other relevant sources: /// rb_GetSurveyDimArray Stored Procedure /// </summary> /// <param name="ModuleID">The module ID.</param> /// <param name="TypeOption">The type option.</param> /// <returns></returns> public int GetDimArray(int ModuleID, string TypeOption) { // Create Instance of Connection and Command object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSurveyDimArray", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = ModuleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterTypeOption = new SqlParameter("@TypeOption", SqlDbType.NChar, 2); parameterTypeOption.Value = TypeOption; myCommand.Parameters.Add(parameterTypeOption); SqlParameter parameterDimArray = new SqlParameter("@DimArray", SqlDbType.Int, 4); parameterDimArray.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterDimArray); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterDimArray.Value; } } }
// * ************************************************************************** // * Copyright (c) Clinton Sheppard <sheppard@cs.unm.edu> // * // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * // * source repository: https://github.com/handcraftsman/QIFGet // * ************************************************************************** using System; using FluentAssert; using NUnit.Framework; using QIFGet.API.Domain; using QIFGet.Domain; using QIFGet.Domain.NamedConstants; namespace QIFGet.Tests.Domain.NamedConstants { public class QIFContentTypeTests { public class AccountName { [TestFixture] public class Given__NPersonal_Checking { private const string Input = "NPersonal_Checking"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry { IsAccountHeader = true }; _contentType = QIFContentType.AccountName; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.AccountName.ShouldBeEqualTo(Input.Substring(1)); } } } public class Amount { [TestFixture] public class Given__T47_COMMA_111_COMMA_500_COMMA_000_DOT_00 { private const string Input = "T47,111,500,000.00"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Amount; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.DollarAmount.ShouldNotBeNull(); // ReSharper disable PossibleInvalidOperationException _entry.DollarAmount.Value.ShouldBeEqualTo(47111500000.00m); // ReSharper restore PossibleInvalidOperationException } } [TestFixture] public class Given__T_DASH_47_DOT_00 { private const string Input = "T-47.00"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Amount; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.DollarAmount.ShouldNotBeNull(); // ReSharper disable PossibleInvalidOperationException _entry.DollarAmount.Value.ShouldBeEqualTo(-47.00m); // ReSharper restore PossibleInvalidOperationException } } } public class Category { [TestFixture] public class Given__LAdjustment { private const string Input = "LAdjustment"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Category; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Category.ShouldBeEqualTo(Input.Substring(1)); } } } public class ClearedStatus { [TestFixture] public class Given__CX { private const string Input = "CX"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.ClearedStatus; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Status.ShouldBeEqualTo(QIFGet.API.Domain.NamedConstants.ClearedStatus.Reconciled); } } } public class Date { [TestFixture] public class Given__D6_SLASH_9_APOS_2006 { private const string Input = "D6/9'2006"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Date; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Date.ShouldBeEqualTo(new DateTime(2006, 6, 9)); } } } public class EachPrice { [TestFixture] public class Given__I { private const string Input = "I"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.EachPrice; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_not_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.EachPrice.ShouldBeNull(); } } [TestFixture] public class Given__I15_DOT_964 { private const string Input = "I15.964"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.EachPrice; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.EachPrice.ShouldNotBeNull(); // ReSharper disable PossibleInvalidOperationException _entry.EachPrice.Value.ShouldBeEqualTo(15.964m); // ReSharper restore PossibleInvalidOperationException } } } public class ItemDescription { [TestFixture] public class Given__YPersonal_Checking { private const string Input = "YPersonal_Checking"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry { IsAccountHeader = false }; _contentType = QIFContentType.ItemDescription; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.ItemDescription.ShouldBeEqualTo(Input.Substring(1)); } } } public class Memo { [TestFixture] public class Given__MAmeritrade { private const string Input = "MAmeritrade"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Memo; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Memo.ShouldBeEqualTo(Input.Substring(1)); } } } public class Payee { [TestFixture] public class Given__PBank { private const string Input = "PBank"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Payee; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Payee.ShouldBeEqualTo(Input.Substring(1)); } } } public class Quantity { [TestFixture] public class Given__Q { private const string Input = "Q"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Quantity; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_not_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Quantity.ShouldBeNull(); } } [TestFixture] public class Given__Q15_DOT_964 { private const string Input = "Q15.964"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.Quantity; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.Quantity.ShouldNotBeNull(); // ReSharper disable PossibleInvalidOperationException _entry.Quantity.Value.ShouldBeEqualTo(15.964m); // ReSharper restore PossibleInvalidOperationException } } } public class TransferAmount { [TestFixture] public class Given__DOLLAR_47_DOT_00 { private const string Input = "$47.00"; private QIFContentType _contentType; private Entry _entry; private QIFRecord _record; [TestFixtureSetUp] public void Before_first_test() { _record = new QIFRecord(QIFRecordType.Content, Input); _entry = new Entry(); _contentType = QIFContentType.TransferAmount; } [Test] public void IsMatch_should_return_true() { _contentType.IsMatch(_entry, _record).ShouldBeTrue(); } [Test] public void Update_should_set_the_value_on_the_Entry() { _contentType.Update(_entry, _record); _entry.TransferAmount.ShouldNotBeNull(); // ReSharper disable PossibleInvalidOperationException _entry.TransferAmount.Value.ShouldBeEqualTo(47.00m); // ReSharper restore PossibleInvalidOperationException } } } } }
/* * Evidence.cs - Implementation of the "System.Security.Policy.Evidence" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Policy { #if CONFIG_PERMISSIONS && CONFIG_POLICY_OBJECTS using System.Collections; using System.Security.Permissions; [Serializable] public sealed class Evidence : ICollection, IEnumerable { // Internal state. private Object[] hostEvidence; private Object[] assemblyEvidence; private bool locked; // Constructors. public Evidence() { this.hostEvidence = null; this.assemblyEvidence = null; } public Evidence(Evidence evidence) { if(evidence == null) { throw new ArgumentNullException("evidence"); } this.hostEvidence = evidence.hostEvidence; this.assemblyEvidence = evidence.assemblyEvidence; } public Evidence(Object[] hostEvidence, Object[] assemblyEvidence) { this.hostEvidence = hostEvidence; this.assemblyEvidence = assemblyEvidence; } // Implement the ICollection interface. public void CopyTo(Array array, int index) { if(hostEvidence != null) { foreach(Object o1 in hostEvidence) { array.SetValue(o1, index++); } } if(assemblyEvidence != null) { foreach(Object o2 in assemblyEvidence) { array.SetValue(o2, index++); } } } public int Count { get { return ((hostEvidence != null) ? hostEvidence.Length : 0) + ((assemblyEvidence != null) ? assemblyEvidence.Length : 0); } } public bool IsSynchronized { get { return false; } } public Object SyncRoot { get { return this; } } // Determine if this evidence set is read-only. public bool IsReadOnly { get { return false; } } // Get or set the lock flag on this evidence list. public bool Locked { get { return locked; } set { (new SecurityPermission (SecurityPermissionFlag.ControlEvidence)).Demand(); locked = value; } } // Add to the assembly evidence list. public void AddAssembly(Object id) { if(locked) { (new SecurityPermission (SecurityPermissionFlag.ControlEvidence)).Demand(); } if(id != null) { if(assemblyEvidence == null) { assemblyEvidence = new Object [] {id}; } else { Object[] newList = new Object [assemblyEvidence.Length + 1]; Array.Copy(assemblyEvidence, 0, newList, 0, assemblyEvidence.Length); newList[assemblyEvidence.Length] = id; assemblyEvidence = newList; } } } // Add to the host evidence list. public void AddHost(Object id) { if(locked) { (new SecurityPermission (SecurityPermissionFlag.ControlEvidence)).Demand(); } if(id != null) { if(hostEvidence == null) { hostEvidence = new Object [] {id}; } else { Object[] newList = new Object [hostEvidence.Length + 1]; Array.Copy(hostEvidence, 0, newList, 0, hostEvidence.Length); newList[hostEvidence.Length] = id; hostEvidence = newList; } } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return new EvidenceEnumerator(this, true, true); } // Enumerate the assembly evidence objects. public IEnumerator GetAssemblyEnumerator() { return new EvidenceEnumerator(this, true, false); } // Enumerate the host evidence objects. public IEnumerator GetHostEnumerator() { return new EvidenceEnumerator(this, false, true); } // Merge two object arrays. private static Object[] Merge(Object[] list1, Object[] list2) { if(list1 == null) { return list2; } else if(list2 == null) { return list1; } Object[] newList = new Object [list1.Length + list2.Length]; Array.Copy(list1, 0, newList, 0, list1.Length); Array.Copy(list2, 0, newList, list1.Length, list2.Length); return newList; } // Merge another evidence set into this one. public void Merge(Evidence evidence) { if(evidence == null) { throw new ArgumentNullException("evidence"); } if(locked) { (new SecurityPermission (SecurityPermissionFlag.ControlEvidence)).Demand(); } hostEvidence = Merge(hostEvidence, evidence.hostEvidence); assemblyEvidence = Merge(assemblyEvidence, evidence.assemblyEvidence); } // Get the number of hosts and assemblies. private int HostCount { get { if(hostEvidence != null) { return hostEvidence.Length; } else { return 0; } } } private int AssemblyCount { get { if(assemblyEvidence != null) { return assemblyEvidence.Length; } else { return 0; } } } // Evidence enumerator class. private sealed class EvidenceEnumerator : IEnumerator { // Internal state. private Evidence evidence; private bool enumHosts; private bool enumAssemblies; private int index; // Constructor. public EvidenceEnumerator(Evidence evidence, bool enumHosts, bool enumAssemblies) { this.evidence = evidence; this.enumHosts = enumHosts; this.enumAssemblies = enumAssemblies; this.index = -1; } // Implement the IEnumerator interface. public bool MoveNext() { ++index; if(enumHosts && enumAssemblies) { return (index < evidence.Count); } else if(enumHosts) { return (index < evidence.HostCount); } else { return (index < evidence.AssemblyCount); } } public void Reset() { index = -1; } public Object Current { get { if(enumHosts && enumAssemblies) { if(index < 0) { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } else if(index < evidence.HostCount) { return evidence.hostEvidence[index]; } else if(index < evidence.Count) { return evidence.assemblyEvidence [index - evidence.HostCount]; } else { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } } else if(enumHosts) { if(index < 0 || index >= evidence.HostCount) { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } else { return evidence.hostEvidence[index]; } } else { if(index < 0 || index >= evidence.AssemblyCount) { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } else { return evidence.assemblyEvidence[index]; } } } } }; // class EvidenceEnumerator }; // class Evidence #else // !(CONFIG_PERMISSIONS && CONFIG_POLICY_OBJECTS) // Define a dummy Evidence class if we aren't using policy objects. public sealed class Evidence { public Evidence() {} public Evidence(Evidence e) {} }; // class Evidence #endif // !(CONFIG_PERMISSIONS && CONFIG_POLICY_OBJECTS) }; // namespace System.Security.Policy
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Content Delivery ///<para>SObject Name: ContentDistribution</para> ///<para>Custom Object: False</para> ///</summary> public class SfContentDistribution : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ContentDistribution"; } } ///<summary> /// Content Delivery ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: Owner</para> ///</summary> [JsonProperty(PropertyName = "owner")] [Updateable(false), Createable(false)] public SfUser Owner { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Content Delivery Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// ContentVersion ID /// <para>Name: ContentVersionId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "contentVersionId")] [Updateable(false), Createable(true)] public string ContentVersionId { get; set; } ///<summary> /// ReferenceTo: ContentVersion /// <para>RelationshipName: ContentVersion</para> ///</summary> [JsonProperty(PropertyName = "contentVersion")] [Updateable(false), Createable(false)] public SfContentVersion ContentVersion { get; set; } ///<summary> /// ContentDocument ID /// <para>Name: ContentDocumentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "contentDocumentId")] [Updateable(false), Createable(false)] public string ContentDocumentId { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] public string RelatedRecordId { get; set; } ///<summary> /// Allow Download as PDF /// <para>Name: PreferencesAllowPDFDownload</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesAllowPDFDownload")] public bool? PreferencesAllowPDFDownload { get; set; } ///<summary> /// Allow Download in Original Format /// <para>Name: PreferencesAllowOriginalDownload</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesAllowOriginalDownload")] public bool? PreferencesAllowOriginalDownload { get; set; } ///<summary> /// Require Password to Access Content /// <para>Name: PreferencesPasswordRequired</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesPasswordRequired")] public bool? PreferencesPasswordRequired { get; set; } ///<summary> /// Notify Me of First View or Download /// <para>Name: PreferencesNotifyOnVisit</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesNotifyOnVisit")] public bool? PreferencesNotifyOnVisit { get; set; } ///<summary> /// Content Delivery Opens Latest Version /// <para>Name: PreferencesLinkLatestVersion</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesLinkLatestVersion")] public bool? PreferencesLinkLatestVersion { get; set; } ///<summary> /// Allow View in the Browser /// <para>Name: PreferencesAllowViewInBrowser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesAllowViewInBrowser")] public bool? PreferencesAllowViewInBrowser { get; set; } ///<summary> /// Content Delivery Expires /// <para>Name: PreferencesExpires</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesExpires")] public bool? PreferencesExpires { get; set; } ///<summary> /// Email when Preview Images are Ready /// <para>Name: PreferencesNotifyRndtnComplete</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "preferencesNotifyRndtnComplete")] public bool? PreferencesNotifyRndtnComplete { get; set; } ///<summary> /// Expiration Date /// <para>Name: ExpiryDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "expiryDate")] public DateTimeOffset? ExpiryDate { get; set; } ///<summary> /// Password /// <para>Name: Password</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "password")] [Updateable(false), Createable(false)] public string Password { get; set; } ///<summary> /// View Count /// <para>Name: ViewCount</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "viewCount")] [Updateable(false), Createable(false)] public int? ViewCount { get; set; } ///<summary> /// First Viewed /// <para>Name: FirstViewDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "firstViewDate")] [Updateable(false), Createable(false)] public DateTimeOffset? FirstViewDate { get; set; } ///<summary> /// Last Viewed /// <para>Name: LastViewDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewDate { get; set; } ///<summary> /// External Link /// <para>Name: DistributionPublicUrl</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "distributionPublicUrl")] [Updateable(false), Createable(false)] public string DistributionPublicUrl { get; set; } ///<summary> /// File Download Link /// <para>Name: ContentDownloadUrl</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "contentDownloadUrl")] [Updateable(false), Createable(false)] public string ContentDownloadUrl { get; set; } ///<summary> /// PDF Download Link /// <para>Name: PdfDownloadUrl</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "pdfDownloadUrl")] [Updateable(false), Createable(false)] public string PdfDownloadUrl { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using static System.Linq.Utilities; namespace System.Linq { public static partial class Enumerable { public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => Union(first, second, comparer: null); public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { if (first == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } return first is UnionIterator<TSource> union && AreEqualityComparersEqual(comparer, union._comparer) ? union.Union(second) : new UnionIterator2<TSource>(first, second, comparer); } /// <summary> /// An iterator that yields distinct values from two or more <see cref="IEnumerable{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source enumerables.</typeparam> private abstract partial class UnionIterator<TSource> : Iterator<TSource> { internal readonly IEqualityComparer<TSource>? _comparer; private IEnumerator<TSource>? _enumerator; private Set<TSource>? _set; protected UnionIterator(IEqualityComparer<TSource>? comparer) { _comparer = comparer; } public sealed override void Dispose() { if (_enumerator != null) { _enumerator.Dispose(); _enumerator = null; _set = null; } base.Dispose(); } internal abstract IEnumerable<TSource>? GetEnumerable(int index); internal abstract UnionIterator<TSource> Union(IEnumerable<TSource> next); private void SetEnumerator(IEnumerator<TSource> enumerator) { _enumerator?.Dispose(); _enumerator = enumerator; } private void StoreFirst() { Debug.Assert(_enumerator != null); Set<TSource> set = new Set<TSource>(_comparer); TSource element = _enumerator.Current; set.Add(element); _current = element; _set = set; } private bool GetNext() { Debug.Assert(_enumerator != null); Debug.Assert(_set != null); Set<TSource> set = _set; while (_enumerator.MoveNext()) { TSource element = _enumerator.Current; if (set.Add(element)) { _current = element; return true; } } return false; } public sealed override bool MoveNext() { if (_state == 1) { for (IEnumerable<TSource>? enumerable = GetEnumerable(0); enumerable != null; enumerable = GetEnumerable(_state - 1)) { IEnumerator<TSource> enumerator = enumerable.GetEnumerator(); SetEnumerator(enumerator); ++_state; if (enumerator.MoveNext()) { StoreFirst(); return true; } } } else if (_state > 0) { while (true) { if (GetNext()) { return true; } IEnumerable<TSource>? enumerable = GetEnumerable(_state - 1); if (enumerable == null) { break; } SetEnumerator(enumerable.GetEnumerator()); ++_state; } } Dispose(); return false; } } /// <summary> /// An iterator that yields distinct values from two <see cref="IEnumerable{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source enumerables.</typeparam> private sealed class UnionIterator2<TSource> : UnionIterator<TSource> { private readonly IEnumerable<TSource> _first; private readonly IEnumerable<TSource> _second; public UnionIterator2(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) : base(comparer) { Debug.Assert(first != null); Debug.Assert(second != null); _first = first; _second = second; } public override Iterator<TSource> Clone() => new UnionIterator2<TSource>(_first, _second, _comparer); internal override IEnumerable<TSource>? GetEnumerable(int index) { Debug.Assert(index >= 0 && index <= 2); return index switch { 0 => _first, 1 => _second, _ => null, }; } internal override UnionIterator<TSource> Union(IEnumerable<TSource> next) { var sources = new SingleLinkedNode<IEnumerable<TSource>>(_first).Add(_second).Add(next); return new UnionIteratorN<TSource>(sources, 2, _comparer); } } /// <summary> /// An iterator that yields distinct values from three or more <see cref="IEnumerable{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source enumerables.</typeparam> private sealed class UnionIteratorN<TSource> : UnionIterator<TSource> { private readonly SingleLinkedNode<IEnumerable<TSource>> _sources; private readonly int _headIndex; public UnionIteratorN(SingleLinkedNode<IEnumerable<TSource>> sources, int headIndex, IEqualityComparer<TSource>? comparer) : base(comparer) { Debug.Assert(headIndex >= 2); Debug.Assert(sources?.GetCount() == headIndex + 1); _sources = sources; _headIndex = headIndex; } public override Iterator<TSource> Clone() => new UnionIteratorN<TSource>(_sources, _headIndex, _comparer); internal override IEnumerable<TSource>? GetEnumerable(int index) => index > _headIndex ? null : _sources.GetNode(_headIndex - index).Item; internal override UnionIterator<TSource> Union(IEnumerable<TSource> next) { if (_headIndex == int.MaxValue - 2) { // In the unlikely case of this many unions, if we produced a UnionIteratorN // with int.MaxValue then state would overflow before it matched it's index. // So we use the naive approach of just having a left and right sequence. return new UnionIterator2<TSource>(this, next, _comparer); } return new UnionIteratorN<TSource>(_sources.Add(next), _headIndex + 1, _comparer); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Net; using System.Reflection; using System.Resources; using System.Security; using System.Security.Principal; using System.Text; using System.Threading; using System.Xml; using Microsoft.PowerShell.Commands.Diagnostics.Common; using Microsoft.PowerShell.Commands.GetCounter; using Microsoft.Powershell.Commands.GetCounter.PdhNative; namespace Microsoft.PowerShell.Commands { /// /// Class that implements the Get-Counter cmdlet. /// [Cmdlet(VerbsData.Import, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138338")] public sealed class ImportCounterCommand : PSCmdlet { // // Path parameter // [Parameter( Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessageBaseName = "GetEventResources")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", Justification = "A string[] is required here because that is the type Powershell supports")] public string[] Path { get { return _path; } set { _path = value; } } private string[] _path; private StringCollection _resolvedPaths = new StringCollection(); private List<string> _accumulatedFileNames = new List<string>(); // // ListSet parameter // [Parameter( Mandatory = true, ParameterSetName = "ListSetSet", ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources")] [AllowEmptyCollection] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", Justification = "A string[] is required here because that is the type Powershell supports")] public string[] ListSet { get { return _listSet; } set { _listSet = value; } } private string[] _listSet = Array.Empty<string>(); // // StartTime parameter // [Parameter( ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "GetCounterSet", HelpMessageBaseName = "GetEventResources")] public DateTime StartTime { get { return _startTime; } set { _startTime = value; } } private DateTime _startTime = DateTime.MinValue; // // EndTime parameter // [Parameter( ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "GetCounterSet", HelpMessageBaseName = "GetEventResources")] public DateTime EndTime { get { return _endTime; } set { _endTime = value; } } private DateTime _endTime = DateTime.MaxValue; // // Counter parameter // [Parameter( Mandatory = false, ParameterSetName = "GetCounterSet", ValueFromPipeline = false, HelpMessageBaseName = "GetEventResources")] [AllowEmptyCollection] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", Justification = "A string[] is required here because that is the type Powershell supports")] public string[] Counter { get { return _counter; } set { _counter = value; } } private string[] _counter = Array.Empty<string>(); // // Summary switch // [Parameter(ParameterSetName = "SummarySet")] public SwitchParameter Summary { get { return _summary; } set { _summary = value; } } private SwitchParameter _summary; // // MaxSamples parameter // private const Int64 KEEP_ON_SAMPLING = -1; [Parameter( ParameterSetName = "GetCounterSet", ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources")] [ValidateRange((Int64)1, Int64.MaxValue)] public Int64 MaxSamples { get { return _maxSamples; } set { _maxSamples = value; } } private Int64 _maxSamples = KEEP_ON_SAMPLING; private ResourceManager _resourceMgr = null; private PdhHelper _pdhHelper = null; private bool _stopping = false; // // AccumulatePipelineFileNames() accumulates counter file paths in the pipeline scenario: // we do not want to construct a Pdh query until all the file names are supplied. // private void AccumulatePipelineFileNames() { _accumulatedFileNames.AddRange(_path); } // // BeginProcessing() is invoked once per pipeline // protected override void BeginProcessing() { #if CORECLR if (Platform.IsIoT) { // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. throw new PlatformNotSupportedException(); } // PowerShell 7 requires at least Windows 7, // so no version test is needed _pdhHelper = new PdhHelper(false); #else _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); #endif _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); } // // EndProcessing() is invoked once per pipeline // protected override void EndProcessing() { // // Resolve and validate the Path argument: present for all parametersets. // if (!ResolveFilePaths()) { return; } ValidateFilePaths(); switch (ParameterSetName) { case "ListSetSet": ProcessListSet(); break; case "GetCounterSet": ProcessGetCounter(); break; case "SummarySet": ProcessSummary(); break; default: Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); break; } _pdhHelper.Dispose(); } // // Handle Control-C // protected override void StopProcessing() { _stopping = true; _pdhHelper.Dispose(); } // // ProcessRecord() override. // This is the main entry point for the cmdlet. // protected override void ProcessRecord() { AccumulatePipelineFileNames(); } // // ProcessSummary(). // Does the work to process Summary parameter set. // private void ProcessSummary() { uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); if (res != 0) { ReportPdhError(res, true); return; } CounterFileInfo summaryObj; res = _pdhHelper.GetFilesSummary(out summaryObj); if (res != 0) { ReportPdhError(res, true); return; } WriteObject(summaryObj); } // // ProcessListSet(). // Does the work to process ListSet parameter set. // private void ProcessListSet() { uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); if (res != 0) { ReportPdhError(res, true); return; } StringCollection machineNames = new StringCollection(); res = _pdhHelper.EnumBlgFilesMachines(ref machineNames); if (res != 0) { ReportPdhError(res, true); return; } foreach (string machine in machineNames) { StringCollection counterSets = new StringCollection(); res = _pdhHelper.EnumObjects(machine, ref counterSets); if (res != 0) { return; } StringCollection validPaths = new StringCollection(); foreach (string pattern in _listSet) { bool bMatched = false; WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); foreach (string counterSet in counterSets) { if (!wildLogPattern.IsMatch(counterSet)) { continue; } StringCollection counterSetCounters = new StringCollection(); StringCollection counterSetInstances = new StringCollection(); res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); if (res != 0) { ReportPdhError(res, false); continue; } string[] instanceArray = new string[counterSetInstances.Count]; int i = 0; foreach (string instance in counterSetInstances) { instanceArray[i++] = instance; } Dictionary<string, string[]> counterInstanceMapping = new Dictionary<string, string[]>(); foreach (string counter in counterSetCounters) { counterInstanceMapping.Add(counter, instanceArray); } PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; if (counterSetInstances.Count > 1) { categoryType = PerformanceCounterCategoryType.MultiInstance; } else // if (counterSetInstances.Count == 1) //??? { categoryType = PerformanceCounterCategoryType.SingleInstance; } string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet); CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping); WriteObject(setObj); bMatched = true; } if (!bMatched) { string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile"); Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, CommonUtilities.StringArrayToString(_resolvedPaths), pattern)); WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null)); } } } } // // ProcessGetCounter() // Does the work to process GetCounterSet parameter set. // private void ProcessGetCounter() { // Validate StartTime-EndTime, if present if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) { if (_startTime >= _endTime) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidDateRange")); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidDateRange", ErrorCategory.InvalidArgument, null)); return; } } uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); if (res != 0) { ReportPdhError(res, true); return; } StringCollection validPaths = new StringCollection(); if (_counter.Length > 0) { foreach (string path in _counter) { StringCollection expandedPaths; res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths); if (res != 0) { WriteDebug(path); ReportPdhError(res, false); continue; } foreach (string expandedPath in expandedPaths) { if (!_pdhHelper.IsPathValid(expandedPath)) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathIsInvalid"), path); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); continue; } validPaths.Add(expandedPath); } } if (validPaths.Count == 0) { return; } } else { res = _pdhHelper.GetValidPathsFromFiles(ref validPaths); if (res != 0) { ReportPdhError(res, false); } } if (validPaths.Count == 0) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid")); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null)); } res = _pdhHelper.OpenQuery(); if (res != 0) { ReportPdhError(res, false); } if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) { res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime); if (res != 0) { ReportPdhError(res, true); } } res = _pdhHelper.AddCounters(ref validPaths, true); if (res != 0) { ReportPdhError(res, true); } PerformanceCounterSampleSet nextSet; uint samplesRead = 0; while (!_stopping) { res = _pdhHelper.ReadNextSet(out nextSet, false); if (res == PdhResults.PDH_NO_MORE_DATA) { break; } if (res != 0 && res != PdhResults.PDH_INVALID_DATA) { ReportPdhError(res, false); continue; } // // Display data // WriteSampleSetObject(nextSet, (samplesRead == 0)); samplesRead++; if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples) { break; } } } // // ValidateFilePaths() helper. // Validates the _resolvedPaths: present for all parametersets. // We cannot have more than 32 blg files, or more than one CSV or TSC file. // Files have to all be of the same type (.blg, .csv, .tsv). // private void ValidateFilePaths() { Debug.Assert(_resolvedPaths.Count > 0); string firstExt = System.IO.Path.GetExtension(_resolvedPaths[0]); foreach (string fileName in _resolvedPaths) { WriteVerbose(fileName); string curExtension = System.IO.Path.GetExtension(fileName); if (!curExtension.Equals(".blg", StringComparison.OrdinalIgnoreCase) && !curExtension.Equals(".csv", StringComparison.OrdinalIgnoreCase) && !curExtension.Equals(".tsv", StringComparison.OrdinalIgnoreCase)) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNotALogFile"), fileName); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterNotALogFile", ErrorCategory.InvalidResult, null)); return; } if (!curExtension.Equals(firstExt, StringComparison.OrdinalIgnoreCase)) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNoMixedLogTypes"), fileName); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterNoMixedLogTypes", ErrorCategory.InvalidResult, null)); return; } } if (firstExt.Equals(".blg", StringComparison.OrdinalIgnoreCase)) { if (_resolvedPaths.Count > 32) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter32FileLimit")); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "Counter32FileLimit", ErrorCategory.InvalidResult, null)); return; } } else if (_resolvedPaths.Count > 1) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter1FileLimit")); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "Counter1FileLimit", ErrorCategory.InvalidResult, null)); return; } } // // ResolveFilePath helper. // Returns a string collection of resolved file paths. // Writes non-terminating errors for invalid paths // and returns an empty collection. // private bool ResolveFilePaths() { StringCollection retColl = new StringCollection(); foreach (string origPath in _accumulatedFileNames) { Collection<PathInfo> resolvedPathSubset = null; try { resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(origPath); } catch (PSNotSupportedException notSupported) { WriteError(new ErrorRecord(notSupported, string.Empty, ErrorCategory.ObjectNotFound, origPath)); continue; } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { WriteError(new ErrorRecord(driveNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError(new ErrorRecord(providerNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError(new ErrorRecord(pathNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); continue; } catch (Exception exc) { WriteError(new ErrorRecord(exc, string.Empty, ErrorCategory.ObjectNotFound, origPath)); continue; } foreach (PathInfo pi in resolvedPathSubset) { // // Check the provider: only FileSystem provider paths are acceptable. // if (pi.Provider.Name != "FileSystem") { string msg = _resourceMgr.GetString("NotAFileSystemPath"); Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, origPath)); WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, origPath)); continue; } _resolvedPaths.Add(pi.ProviderPath.ToLowerInvariant()); } } return (_resolvedPaths.Count > 0); } private void ReportPdhError(uint res, bool bTerminate) { string msg; uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); if (formatRes != 0) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } Exception exc = new Exception(msg); if (bTerminate) { ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } else { WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } } // // WriteSampleSetObject() helper. // In addition to writing the PerformanceCounterSampleSet object, // it writes a single error if one of the samples has an invalid (non-zero) status. // The only exception is the first set, where we allow for the formatted value to be 0 - // this is expected for CSV and TSV files. private void WriteSampleSetObject(PerformanceCounterSampleSet set, bool firstSet) { if (!firstSet) { foreach (PerformanceCounterSample sample in set.CounterSamples) { if (sample.Status != 0) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid")); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); break; } } } WriteObject(set); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { [Test] public void ShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Marionette doesn't see subsequent navigation to a fragment as a new navigation."); } driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] [IgnoreBrowser(Browser.Safari, "Hangs Safari driver")] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [IgnoreBrowser(Browser.IE, "IE happily will navigate to invalid URLs")] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Safari, "Hangs Safari driver")] public void ShouldThrowIfUrlIsMalformed() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Browser hangs when executed via Marionette"); } driver.Url = "www.test.com"; } [Test] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Safari, "Hangs Safari driver")] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(BeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.IsTrue(currentTitle == originalTitle || currentTitle == "We Leave From Here", "title is " + currentTitle); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } //TODO (jimevan): Implement SSL secure http function //[Test] //[IgnoreBrowser(Browser.Chrome)] //[IgnoreBrowser(Browser.IE)] //public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() //{ // String url = GlobalTestEnvironment.get().getAppServer().whereIsSecure("simpleTest.html"); // driver.Url = url; // // This should work // Assert.AreEqual(driver.Title, "Hello WebDriver"); //} [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.IPhone, "Untested user-agent")] [IgnoreBrowser(Browser.Safari, "Untested user-agent")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Browser hangs when executed via Marionette"); } driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } [Test] [IgnoreBrowser(Browser.Android, "Not implemented for browser")] [IgnoreBrowser(Browser.Chrome, "Not implemented for browser")] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented for browser")] [IgnoreBrowser(Browser.IPhone, "Not implemented for browser")] [IgnoreBrowser(Browser.PhantomJS, "Not implemented for browser")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Safari, "See issue 687, comment 41")] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(2)); try { // Get the sleeping servlet with a pause of 5 seconds string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); driver.Url = slowPage; Assert.Fail("I should have timed out"); } catch (WebDriverTimeoutException) { } finally { driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.MinValue); } } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } } }
// 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.Drawing.Imaging { using System.Runtime.InteropServices; using System.Diagnostics; using System.Drawing.Drawing2D; using System.Globalization; // sdkinc\GDIplusImageAttributes.h // There are 5 possible sets of color adjustments: // ColorAdjustDefault, // ColorAdjustBitmap, // ColorAdjustBrush, // ColorAdjustPen, // ColorAdjustText, // Bitmaps, Brushes, Pens, and Text will all use any color adjustments // that have been set into the default ImageAttributes until their own // color adjustments have been set. So as soon as any "Set" method is // called for Bitmaps, Brushes, Pens, or Text, then they start from // scratch with only the color adjustments that have been set for them. // Calling Reset removes any individual color adjustments for a type // and makes it revert back to using all the default color adjustments // (if any). The SetToIdentity method is a way to force a type to // have no color adjustments at all, regardless of what previous adjustments // have been set for the defaults or for that type. /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes"]/*' /> /// <devdoc> /// Contains information about how image colors /// are manipulated during rendering. /// </devdoc> [StructLayout(LayoutKind.Sequential)] public sealed class ImageAttributes : ICloneable, IDisposable { #if FINALIZATION_WATCH private string allocationSite = Graphics.GetAllocationStack(); #endif /* * Handle to native image attributes object */ internal IntPtr nativeImageAttributes; internal void SetNativeImageAttributes(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentNullException("handle"); nativeImageAttributes = handle; } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ImageAttributes"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Imaging.ImageAttributes'/> class. /// </devdoc> public ImageAttributes() { IntPtr newImageAttributes = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateImageAttributes(out newImageAttributes); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImageAttributes(newImageAttributes); } internal ImageAttributes(IntPtr newNativeImageAttributes) { SetNativeImageAttributes(newNativeImageAttributes); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Dispose"]/*' /> /// <devdoc> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { #if FINALIZATION_WATCH if (!disposing && nativeImageAttributes != IntPtr.Zero) Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite); #endif if (nativeImageAttributes != IntPtr.Zero) { try { #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDisposeImageAttributes(new HandleRef(this, nativeImageAttributes)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during Dispose: " + ex.ToString()); } finally { nativeImageAttributes = IntPtr.Zero; } } } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Finalize"]/*' /> /// <devdoc> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </devdoc> ~ImageAttributes() { Dispose(false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Clone"]/*' /> /// <devdoc> /// <para> /// Creates an exact copy of this <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </para> /// </devdoc> public object Clone() { IntPtr clone = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneImageAttributes( new HandleRef(this, nativeImageAttributes), out clone); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new ImageAttributes(clone); } /* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future. void SetToIdentity() { SetToIdentity(ColorAdjustType.Default); } void SetToIdentity(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesToIdentity(new HandleRef(this, nativeImageAttributes), type); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } void Reset() { Reset(ColorAdjustType.Default); } void Reset(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipResetImageAttributes(new HandleRef(this, nativeImageAttributes), type); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } */ /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the /// specified <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix) { SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix1"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags) { SetColorMatrix(newColorMatrix, flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix2"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the /// specified 'ColorMatrixFlags'. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag mode, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, true, newColorMatrix, null, mode); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorMatrix"]/*' /> /// <devdoc> /// Clears the color adjust matrix to all /// zeroes. /// </devdoc> public void ClearColorMatrix() { ClearColorMatrix(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorMatrix1"]/*' /> /// <devdoc> /// <para> /// Clears the color adjust matrix. /// </para> /// </devdoc> public void ClearColorMatrix(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, false, null, null, ColorMatrixFlag.Default); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices"]/*' /> /// <devdoc> /// <para> /// Sets a color adjust matrix for image colors /// and a separate gray scale adjust matrix for gray scale values. /// </para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix) { SetColorMatrices(newColorMatrix, grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag flags) { SetColorMatrices(newColorMatrix, grayMatrix, flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag mode, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, true, newColorMatrix, grayMatrix, mode); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetThreshold"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetThreshold(float threshold) { SetThreshold(threshold, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetThreshold1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetThreshold(float threshold, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold( new HandleRef(this, nativeImageAttributes), type, true, threshold); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearThreshold"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearThreshold() { ClearThreshold(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearThreshold1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearThreshold(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold( new HandleRef(this, nativeImageAttributes), type, false, 0.0f); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetGamma"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetGamma(float gamma) { SetGamma(gamma, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetGamma1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetGamma(float gamma, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma( new HandleRef(this, nativeImageAttributes), type, true, gamma); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearGamma"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearGamma() { ClearGamma(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearGamma1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearGamma(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma( new HandleRef(this, nativeImageAttributes), type, false, 0.0f); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetNoOp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetNoOp() { SetNoOp(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetNoOp1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetNoOp(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp( new HandleRef(this, nativeImageAttributes), type, true); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearNoOp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearNoOp() { ClearNoOp(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearNoOp1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearNoOp(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp( new HandleRef(this, nativeImageAttributes), type, false); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorKey"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorKey(Color colorLow, Color colorHigh) { SetColorKey(colorLow, colorHigh, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorKey1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorKey(Color colorLow, Color colorHigh, ColorAdjustType type) { int lowInt = colorLow.ToArgb(); int highInt = colorHigh.ToArgb(); int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys( new HandleRef(this, nativeImageAttributes), type, true, lowInt, highInt); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorKey"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearColorKey() { ClearColorKey(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorKey1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearColorKey(ColorAdjustType type) { int zero = 0; int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys( new HandleRef(this, nativeImageAttributes), type, false, zero, zero); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannel(ColorChannelFlag flags) { SetOutputChannel(flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannel1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannel(ColorChannelFlag flags, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, true, flags); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannel() { ClearOutputChannel(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannel1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannel(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, false, ColorChannelFlag.ColorChannelLast); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannelColorProfile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannelColorProfile(String colorProfileFilename) { SetOutputChannelColorProfile(colorProfileFilename, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannelColorProfile1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannelColorProfile(String colorProfileFilename, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannelColorProfile( new HandleRef(this, nativeImageAttributes), type, true, colorProfileFilename); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannelColorProfile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannelColorProfile() { ClearOutputChannel(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannelColorProfile1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannelColorProfile(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, false, ColorChannelFlag.ColorChannelLast); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetRemapTable(ColorMap[] map) { SetRemapTable(map, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetRemapTable1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetRemapTable(ColorMap[] map, ColorAdjustType type) { int index = 0; int mapSize = map.Length; int size = 4; // Marshal.SizeOf(index.GetType()); IntPtr memory = Marshal.AllocHGlobal(checked(mapSize * size * 2)); try { for (index = 0; index < mapSize; index++) { Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)((long)memory + index * size * 2), false); Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)((long)memory + index * size * 2 + size), false); } int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable( new HandleRef(this, nativeImageAttributes), type, true, mapSize, new HandleRef(null, memory)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } finally { Marshal.FreeHGlobal(memory); } } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearRemapTable() { ClearRemapTable(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearRemapTable1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearRemapTable(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable( new HandleRef(this, nativeImageAttributes), type, false, 0, NativeMethods.NullHandleRef); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetBrushRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetBrushRemapTable(ColorMap[] map) { SetRemapTable(map, ColorAdjustType.Brush); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearBrushRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearBrushRemapTable() { ClearRemapTable(ColorAdjustType.Brush); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode) { SetWrapMode(mode, new Color(), false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode, Color color) { SetWrapMode(mode, color, false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode, Color color, bool clamp) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesWrapMode( new HandleRef(this, nativeImageAttributes), unchecked((int)mode), color.ToArgb(), clamp); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.GetAdjustedPalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type) { // does inplace adjustment IntPtr memory = palette.ConvertToMemory(); try { int status = SafeNativeMethods.Gdip.GdipGetImageAttributesAdjustedPalette( new HandleRef(this, nativeImageAttributes), new HandleRef(null, memory), type); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } palette.ConvertFromMemory(memory); } finally { if (memory != IntPtr.Zero) { Marshal.FreeHGlobal(memory); } } } } }
// 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.IdentityModel.Tokens { using System; using System.Collections.Generic; using System.Globalization; using System.IdentityModel; using System.IdentityModel.Selectors; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using Microsoft.Xml; //using HexBinary = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary; using KeyIdentifierClauseEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.KeyIdentifierClauseEntry; using StrEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.StrEntry; using TokenEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.TokenEntry; internal class WSSecurityJan2004 : SecurityTokenSerializer.SerializerEntries { private KeyInfoSerializer _securityTokenSerializer; public WSSecurityJan2004(KeyInfoSerializer securityTokenSerializer) { _securityTokenSerializer = securityTokenSerializer; } public KeyInfoSerializer SecurityTokenSerializer { get { return _securityTokenSerializer; } } public override void PopulateKeyIdentifierClauseEntries(IList<KeyIdentifierClauseEntry> clauseEntries) { List<StrEntry> strEntries = new List<StrEntry>(); _securityTokenSerializer.PopulateStrEntries(strEntries); SecurityTokenReferenceJan2004ClauseEntry strClause = new SecurityTokenReferenceJan2004ClauseEntry(_securityTokenSerializer.EmitBspRequiredAttributes, strEntries); clauseEntries.Add(strClause); } protected void PopulateJan2004StrEntries(IList<StrEntry> strEntries) { strEntries.Add(new LocalReferenceStrEntry(_securityTokenSerializer.EmitBspRequiredAttributes, _securityTokenSerializer)); strEntries.Add(new KerberosHashStrEntry(_securityTokenSerializer.EmitBspRequiredAttributes)); strEntries.Add(new X509SkiStrEntry(_securityTokenSerializer.EmitBspRequiredAttributes)); strEntries.Add(new X509IssuerSerialStrEntry()); strEntries.Add(new RelDirectStrEntry()); strEntries.Add(new SamlJan2004KeyIdentifierStrEntry()); strEntries.Add(new Saml2Jan2004KeyIdentifierStrEntry()); } public override void PopulateStrEntries(IList<StrEntry> strEntries) { PopulateJan2004StrEntries(strEntries); } protected void PopulateJan2004TokenEntries(IList<TokenEntry> tokenEntryList) { tokenEntryList.Add(new GenericXmlTokenEntry()); tokenEntryList.Add(new UserNamePasswordTokenEntry()); tokenEntryList.Add(new KerberosTokenEntry()); tokenEntryList.Add(new X509TokenEntry()); } public override void PopulateTokenEntries(IList<TokenEntry> tokenEntryList) { PopulateJan2004TokenEntries(tokenEntryList); tokenEntryList.Add(new SamlTokenEntry()); tokenEntryList.Add(new WrappedKeyTokenEntry()); } internal abstract class BinaryTokenEntry : TokenEntry { internal static readonly XmlDictionaryString ElementName = XD.SecurityJan2004Dictionary.BinarySecurityToken; internal static readonly XmlDictionaryString EncodingTypeAttribute = XD.SecurityJan2004Dictionary.EncodingType; internal const string EncodingTypeAttributeString = SecurityJan2004Strings.EncodingType; internal const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; internal const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary; internal static readonly XmlDictionaryString ValueTypeAttribute = XD.SecurityJan2004Dictionary.ValueType; private string[] _valueTypeUris = null; protected BinaryTokenEntry(string valueTypeUri) { _valueTypeUris = new string[1]; _valueTypeUris[0] = valueTypeUri; } protected BinaryTokenEntry(string[] valueTypeUris) { if (valueTypeUris == null) throw new ArgumentNullException("valueTypeUris"); // TODO: DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris"); _valueTypeUris = new string[valueTypeUris.GetLength(0)]; for (int i = 0; i < _valueTypeUris.GetLength(0); ++i) _valueTypeUris[i] = valueTypeUris[i]; } protected override XmlDictionaryString LocalName { get { return ElementName; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } public override string TokenTypeUri { get { return _valueTypeUris[0]; } } protected override string ValueTypeUri { get { return _valueTypeUris[0]; } } public override bool SupportsTokenTypeUri(string tokenTypeUri) { for (int i = 0; i < _valueTypeUris.GetLength(0); ++i) { if (_valueTypeUris[i] == tokenTypeUri) return true; } return false; } } private class GenericXmlTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return null; } } protected override XmlDictionaryString NamespaceUri { get { return null; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(GenericXmlSecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } private class KerberosTokenEntry : BinaryTokenEntry { public KerberosTokenEntry() : base(new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 }) { } protected override Type[] GetTokenTypesCore() { throw new NotImplementedException(); } } protected class SamlTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SamlAssertion; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.SamlUri; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(SamlSecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } private class UserNamePasswordTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.UserNameTokenElement; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(UserNameSecurityToken) }; } public override string TokenTypeUri { get { return SecurityJan2004Strings.UPTokenType; } } protected override string ValueTypeUri { get { return null; } } } protected class WrappedKeyTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return EncryptedKey.ElementName; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlEncryptionDictionary.Namespace; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(WrappedKeySecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } protected class X509TokenEntry : BinaryTokenEntry { internal const string ValueTypeAbsoluteUri = SecurityJan2004Strings.X509TokenType; public X509TokenEntry() : base(ValueTypeAbsoluteUri) { } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(X509SecurityToken), typeof(X509WindowsSecurityToken) }; } } protected class SecurityTokenReferenceJan2004ClauseEntry : KeyIdentifierClauseEntry { private const int DefaultDerivedKeyLength = 32; private bool _emitBspRequiredAttributes; private IList<StrEntry> _strEntries; public SecurityTokenReferenceJan2004ClauseEntry(bool emitBspRequiredAttributes, IList<StrEntry> strEntries) { _emitBspRequiredAttributes = emitBspRequiredAttributes; _strEntries = strEntries; } protected bool EmitBspRequiredAttributes { get { return _emitBspRequiredAttributes; } } protected IList<StrEntry> StrEntries { get { return _strEntries; } } protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SecurityTokenReference; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } protected virtual string ReadTokenType(XmlDictionaryReader reader) { return null; } public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) { throw new NotImplementedException(); } public override bool SupportsCore(SecurityKeyIdentifierClause keyIdentifierClause) { for (int i = 0; i < _strEntries.Count; ++i) { if (_strEntries[i].SupportsCore(keyIdentifierClause)) { return true; } } return false; } public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause) { throw new NotImplementedException(); } } protected abstract class KeyIdentifierStrEntry : StrEntry { private bool _emitBspRequiredAttributes; protected const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; protected const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary; protected const string EncodingTypeValueText = SecurityJan2004Strings.EncodingTypeValueText; protected abstract Type ClauseType { get; } protected virtual string DefaultEncodingType { get { return EncodingTypeValueBase64Binary; } } public abstract Type TokenType { get; } protected abstract string ValueTypeUri { get; } protected bool EmitBspRequiredAttributes { get { return _emitBspRequiredAttributes; } } protected KeyIdentifierStrEntry(bool emitBspRequiredAttributes) { _emitBspRequiredAttributes = emitBspRequiredAttributes; } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return (ValueTypeUri == valueType); } return false; } protected abstract SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength); public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return this.TokenType; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { throw new NotImplementedException(); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace); writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, ValueTypeUri); if (_emitBspRequiredAttributes) { // Emit the encodingType attribute. writer.WriteAttributeString(XD.SecurityJan2004Dictionary.EncodingType, null, DefaultEncodingType); } string encoding = DefaultEncodingType; BinaryKeyIdentifierClause binaryClause = clause as BinaryKeyIdentifierClause; byte[] keyIdentifier = binaryClause.GetBuffer(); if (encoding == EncodingTypeValueBase64Binary) { writer.WriteBase64(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueHexBinary) { writer.WriteBinHex(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueText) { writer.WriteString(new UTF8Encoding().GetString(keyIdentifier, 0, keyIdentifier.Length)); } writer.WriteEndElement(); } } protected class KerberosHashStrEntry : KeyIdentifierStrEntry { protected override Type ClauseType { get { throw new NotImplementedException(); } } public override Type TokenType { get { return typeof(KerberosRequestorSecurityToken); } } protected override string ValueTypeUri { get { return SecurityJan2004Strings.KerberosHashValueType; } } public KerberosHashStrEntry(bool emitBspRequiredAttributes) : base(emitBspRequiredAttributes) { } protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength) { throw new NotImplementedException(); } public override string GetTokenTypeUri() { return XD.SecurityJan2004Dictionary.KerberosTokenTypeGSS.Value; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } } protected class X509SkiStrEntry : KeyIdentifierStrEntry { protected override Type ClauseType { get { throw new NotImplementedException(); } } public override Type TokenType { get { return typeof(X509SecurityToken); } } protected override string ValueTypeUri { get { return SecurityJan2004Strings.X509SKIValueType; } } public X509SkiStrEntry(bool emitBspRequiredAttributes) : base(emitBspRequiredAttributes) { } protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength) { throw new NotImplementedException(); } public override string GetTokenTypeUri() { return SecurityJan2004Strings.X509TokenType; } } protected class LocalReferenceStrEntry : StrEntry { private bool _emitBspRequiredAttributes; private KeyInfoSerializer _tokenSerializer; public LocalReferenceStrEntry(bool emitBspRequiredAttributes, KeyInfoSerializer tokenSerializer) { _emitBspRequiredAttributes = emitBspRequiredAttributes; _tokenSerializer = tokenSerializer; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { LocalIdKeyIdentifierClause localClause = clause as LocalIdKeyIdentifierClause; return localClause.OwnerType; } public string GetLocalTokenTypeUri(SecurityKeyIdentifierClause clause) { Type tokenType = GetTokenType(clause); return _tokenSerializer.GetTokenTypeUri(tokenType); } public override string GetTokenTypeUri() { return null; } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace)) { string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); if (uri != null && uri.Length > 0 && uri[0] == '#') { return true; } } return false; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); string tokenTypeUri = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); Type[] tokenTypes = null; if (tokenTypeUri != null) { tokenTypes = _tokenSerializer.GetTokenTypes(tokenTypeUri); } SecurityKeyIdentifierClause clause = new LocalIdKeyIdentifierClause(uri.Substring(1), derivationNonce, derivationLength, tokenTypes); if (reader.IsEmptyElement) { reader.Read(); } else { reader.ReadStartElement(); reader.ReadEndElement(); } return clause; } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { return clause is LocalIdKeyIdentifierClause; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { LocalIdKeyIdentifierClause localIdClause = clause as LocalIdKeyIdentifierClause; writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace); if (_emitBspRequiredAttributes) { string tokenTypeUri = GetLocalTokenTypeUri(localIdClause); if (tokenTypeUri != null) { writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, tokenTypeUri); } } writer.WriteAttributeString(XD.SecurityJan2004Dictionary.URI, null, "#" + localIdClause.LocalId); writer.WriteEndElement(); } } protected class SamlJan2004KeyIdentifierStrEntry : StrEntry { protected virtual bool IsMatchingValueType(string valueType) { return (valueType == SecurityJan2004Strings.SamlAssertionIdValueType); } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri)) { return true; } else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return IsMatchingValueType(valueType); } return false; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return typeof(SamlSecurityToken); } public override string GetTokenTypeUri() { return XD.SecurityXXX2005Dictionary.SamlTokenType.Value; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) { throw new NotImplementedException(); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } } private class Saml2Jan2004KeyIdentifierStrEntry : SamlJan2004KeyIdentifierStrEntry { // handles SAML2.0 protected override bool IsMatchingValueType(string valueType) { return (valueType == XD.SecurityXXX2005Dictionary.Saml11AssertionValueType.Value); } public override string GetTokenTypeUri() { return XD.SecurityXXX2005Dictionary.Saml20TokenType.Value; } } protected class RelDirectStrEntry : StrEntry { public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return (valueType == SecurityJan2004Strings.RelAssertionValueType); } return false; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return null; } public override string GetTokenTypeUri() { return XD.SecurityJan2004Dictionary.RelAssertionValueType.Value; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) { throw new NotImplementedException(); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } } protected class X509IssuerSerialStrEntry : StrEntry { public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return typeof(X509SecurityToken); } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { return reader.IsStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); } public override string GetTokenTypeUri() { return SecurityJan2004Strings.X509TokenType; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { throw new NotImplementedException(); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { throw new NotImplementedException(); } } public class IdManager : SignatureTargetIdManager { internal static readonly XmlDictionaryString ElementName = XD.XmlEncryptionDictionary.EncryptedData; private static readonly IdManager s_instance = new IdManager(); private IdManager() { } public override string DefaultIdNamespacePrefix { get { return UtilityStrings.Prefix; } } public override string DefaultIdNamespaceUri { get { return UtilityStrings.Namespace; } } internal static IdManager Instance { get { return s_instance; } } public override string ExtractId(XmlDictionaryReader reader) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.IsStartElement(ElementName, XD.XmlEncryptionDictionary.Namespace)) { return reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null); } else { return reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); } } public override void WriteIdAttribute(XmlDictionaryWriter writer, string id) { if (writer == null) throw new ArgumentNullException("writer"); writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id); } } } }
//----------------------------------------------------------------------------- // Rectangle.cs // // Copyright (C) 2006 The Mono.Xna Team. All rights reserved. // Website: http://monogame.com // Other Contributors: deathbeam @ http://indiearmory.com // License: MIT //----------------------------------------------------------------------------- using System; namespace Spooker { [Serializable] public struct Rectangle : IEquatable<Rectangle> { #region Public Fields public int X; public int Y; public int Width; public int Height; #endregion Public Fields #region Public Properties public int Left { get { return X; } } public int Right { get { return (X + Width); } } public int Top { get { return Y; } } public int Bottom { get { return (Y + Height); } } public Vector2 Location { get { return new Vector2(X, Y); } } public Vector2 Size { get { return new Vector2(Width, Height); } } public Vector2 Center { get { return new Vector2(X + (Width / 2), Y + (Height / 2)); } } public bool IsEmpty { get { return ((((Width == 0) && (Height == 0)) && (X == 0)) && (Y == 0)); } } #endregion Public Properties #region SFML Helpers internal Rectangle(SFML.Graphics.IntRect copy) { X = copy.Left; Y = copy.Top; Width = copy.Width; Height = copy.Height; } internal SFML.Graphics.IntRect ToSfml() { return new SFML.Graphics.IntRect(X, Y, Width, Height); } #endregion SFML Helpers #region Constructors public Rectangle(int x, int y, int width, int height) { X = x; Y = y; Width = width; Height = height; } public static Rectangle Empty { get { return new Rectangle(0, 0, 0, 0); } } #endregion Constructors #region Static Methods public static Rectangle Union(Rectangle value1, Rectangle value2) { var x = Math.Min(value1.X, value2.X); var y = Math.Min(value1.Y, value2.Y); return new Rectangle(x, y, Math.Max(value1.Right, value2.Right) - x, Math.Max(value1.Bottom, value2.Bottom) - y); } #endregion Static Methods #region Public Methods public bool Contains(int x, int y) { return ((((X <= x) && (x < (X + Width))) && (Y <= y)) && (y < (Y + Height))); } public bool Contains(Point value) { return ((((X <= value.X) && (value.X < (X + Width))) && (Y <= value.Y)) && (value.Y < (Y + Height))); } public bool Contains(Rectangle value) { return ((((X <= value.X) && ((value.X + value.Width) <= (X + Width))) && (Y <= value.Y)) && ((value.Y + value.Height) <= (Y + Height))); } public void Offset(Point offset) { X += offset.X; Y += offset.Y; } public void Offset(int offsetX, int offsetY) { X += offsetX; Y += offsetY; } public void Inflate(int horizontalValue, int verticalValue) { X -= horizontalValue; Y -= verticalValue; Width += horizontalValue * 2; Height += verticalValue * 2; } public static Rectangle Intersect(Rectangle rectangle1, Rectangle rectangle2) { if (rectangle1.Intersects(rectangle2)) { var rightSide = Math.Min(rectangle1.X + rectangle1.Width, rectangle2.X + rectangle2.Width); var leftSide = Math.Max(rectangle1.X, rectangle2.X); var topSide = Math.Max(rectangle1.Y, rectangle2.Y); var bottomSide = Math.Min(rectangle1.Y + rectangle1.Height, rectangle2.Y + rectangle2.Height); return new Rectangle(leftSide, topSide, rightSide - leftSide, bottomSide - topSide); } return Empty; } public bool Intersects(Rectangle rectangle) { return rectangle.Left < Right && Left < rectangle.Right && rectangle.Top < Bottom && Top < rectangle.Bottom; } public bool Equals(Rectangle other) { return (X == other.X) && (Y == other.Y) && (Width == other.Width) && (Height == other.Height); } public override bool Equals(object obj) { return (obj is Rectangle) && Equals((Rectangle)obj); } public override string ToString() { return string.Format("{{X:{0} Y:{1} Width:{2} Height:{3}}}", X, Y, Width, Height); } public override int GetHashCode() { return unchecked((int)((uint)Left ^ (((uint)Top << 13) | ((uint)Top >> 19)) ^ (((uint)Width << 26) | ((uint)Width >> 6)) ^ (((uint)Height << 7) | ((uint)Height >> 25)))); } #endregion Public Methods #region Operators public static bool operator ==(Rectangle a, Rectangle b) { return a.Equals (b); } public static bool operator !=(Rectangle a, Rectangle b) { return !a.Equals (b); } #endregion Operators } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using System.IO; using Trionic5Tools; namespace T5Suite2 { public partial class frmPartNumberList : DevExpress.XtraEditors.XtraForm { private string m_selectedpartnumber = ""; private DataTable partnumbers = new DataTable(); public string Selectedpartnumber { get { return m_selectedpartnumber; } set { m_selectedpartnumber = value; } } Trionic5File trionic5file = new Trionic5File(); public frmPartNumberList() { InitializeComponent(); partnumbers.Columns.Add("FILENAME"); partnumbers.Columns.Add("PARTNUMBER"); partnumbers.Columns.Add("ENGINETYPE"); partnumbers.Columns.Add("CARTYPE"); partnumbers.Columns.Add("TUNER"); partnumbers.Columns.Add("STAGE"); partnumbers.Columns.Add("INFO"); partnumbers.Columns.Add("SPEED"); //partnumbers.Columns.Add("TYPE"); //backgroundWorker1.RunWorkerAsync(); } private void LoadPartNumbersFromFiles() { if (Directory.Exists(Application.StartupPath + "\\Binaries")) { string[] binfiles = Directory.GetFiles(Application.StartupPath + "\\Binaries", "*.BIN"); foreach (string binfile in binfiles) { //FileInfo fi = new FileInfo(binfile); //string fileIdent = "T5.5"; //if (fi.Length == 0x20000) fileIdent = "T5.2"; string speed = "16"; if (Find20MhzSequence(binfile)) speed = "20"; string binfilename = Path.GetFileNameWithoutExtension(binfile); string partnumber = ""; string enginetype = ""; string cartype = ""; string tuner = ""; string stage = ""; string additionalinfo = ""; string softwareid = ""; if (binfilename.Contains("-")) { char[] sep = new char[1]; sep.SetValue('-', 0); string[] values = binfilename.Split(sep); if (values.Length == 1) { // assume partnumber partnumber = (string)binfilename; partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } if (values.Length == 2) { // assume partnumber-softwareid partnumber = (string)values.GetValue(0); softwareid = (string)values.GetValue(1); partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } else if (values.Length == 3) { cartype = (string)values.GetValue(0); enginetype = (string)values.GetValue(1); partnumber = (string)values.GetValue(2); partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } else if (values.Length == 4) { cartype = (string)values.GetValue(0); enginetype = (string)values.GetValue(1); partnumber = (string)values.GetValue(2); tuner = (string)values.GetValue(3); partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } else if (values.Length == 5) { cartype = (string)values.GetValue(0); enginetype = (string)values.GetValue(1); partnumber = (string)values.GetValue(2); tuner = (string)values.GetValue(3); stage = (string)values.GetValue(4); partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } else if (values.Length > 5) { cartype = (string)values.GetValue(0); enginetype = (string)values.GetValue(1); partnumber = (string)values.GetValue(2); tuner = (string)values.GetValue(3); stage = (string)values.GetValue(4); for (int tel = 5; tel < values.Length; tel++) { additionalinfo += (string)values.GetValue(tel) + " "; } partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } } else { // assume partnumber partnumber = (string)binfilename; ///////////////// temporary conversion code softwareid = (string)trionic5file.GetSoftwareVersion(binfile); string outputfile = Path.GetDirectoryName(binfile); outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(binfile) + "-" + softwareid + ".BIN"); File.Move(binfile, outputfile); ///////////////// end temporary conversion code partnumbers.Rows.Add(binfile, partnumber, enginetype, cartype, tuner, stage, additionalinfo, speed); } // backgroundWorker1.ReportProgress(0); Application.DoEvents(); } } } private void frmPartNumberList_Load(object sender, EventArgs e) { PartnumberCollection pnc = new PartnumberCollection(); DataTable dt = pnc.GeneratePartNumberCollection(); //dt.Columns.Add("Filename"); //dt.Columns.Add("Tuner"); //dt.Columns.Add("Stage"); //dt.Columns.Add("Info"); LoadPartNumbersFromFiles(); /*foreach (DataRow dr in dt.Rows) { foreach (DataRow pdr in partnumbers.Rows) { if(dr["Partnumber"] != DBNull.Value && pdr["PARTNUMBER"] != DBNull.Value) { if (dr["Partnumber"].ToString() == pdr["PARTNUMBER"].ToString()) { dr["Filename"] = pdr["FILENAME"]; dr["Tuner"] = pdr["TUNER"]; dr["Stage"] = pdr["STAGE"]; dr["Info"] = pdr["INFO"]; } } } }*/ gridControl1.DataSource = dt; gridView1.Columns["Carmodel"].Group(); gridView1.Columns["Enginetype"].Group(); gridView1.BestFitColumns(); } private void gridView1_DoubleClick(object sender, EventArgs e) { int[] rows = gridView1.GetSelectedRows(); if(rows.Length > 0) { m_selectedpartnumber = (string)gridView1.GetRowCellValue((int)rows.GetValue(0), "Partnumber"); if (m_selectedpartnumber != null) { if (m_selectedpartnumber != string.Empty) { this.Close(); } } } } private void simpleButton1_Click(object sender, EventArgs e) { int[] rows = gridView1.GetSelectedRows(); if (rows.Length > 0) { m_selectedpartnumber = (string)gridView1.GetRowCellValue((int)rows.GetValue(0), "Partnumber"); } this.Close(); } private string CheckTypeInAvailableLibrary(string partnumber) { string retval = ""; foreach (DataRow dr in partnumbers.Rows) { if (dr["PARTNUMBER"] != DBNull.Value) { if (dr["PARTNUMBER"].ToString() == partnumber) { retval = dr["Type"].ToString(); break; } } } return retval; } private int CheckInAvailableLibrary(string partnumber) { int retval = 0; foreach (DataRow dr in partnumbers.Rows) { if (dr["PARTNUMBER"] != DBNull.Value) { if (dr["PARTNUMBER"].ToString() == partnumber) { retval = 1; if (dr["SPEED"].ToString() == "20") { retval = 2; } break; } } } return retval; } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { if (e.Column.FieldName == "Partnumber") { if (e.CellValue != null) { if (e.CellValue != DBNull.Value) { int type = CheckInAvailableLibrary(e.CellValue.ToString()); if (type == 1) { e.Graphics.FillRectangle(Brushes.YellowGreen, e.Bounds); } if (type == 2) { e.Graphics.FillRectangle(Brushes.Orange, e.Bounds); } } } } /*if (e.Column.FieldName == "Type") { if (e.CellValue != null) { if (e.CellValue != DBNull.Value) { string type = CheckTypeInAvailableLibrary(gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["Partnumber"]).ToString()); e.DisplayText = type; } } }*/ } private bool Find20MhzSequence(string filename) { bool retval = false; FileInfo fi = new FileInfo(filename); using (FileStream a_fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { byte[] sequence = new byte[32] {0x02, 0x39, 0x00, 0xBF, 0x00, 0xFF, 0xFA, 0x04, 0x00, 0x39, 0x00, 0x80, 0x00, 0xFF, 0xFA, 0x04, 0x02, 0x39, 0x00, 0xC0, 0x00, 0xFF, 0xFA, 0x04, 0x00, 0x39, 0x00, 0x13, 0x00, 0xFF, 0xFA, 0x04}; /*byte[] seq_mask = new byte[32] {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1};*/ byte data; int i; i = 0; while (a_fileStream.Position < fi.Length -1) { data = (byte)a_fileStream.ReadByte(); if (data == sequence[i]) { i++; } else { i = 0; } if (i == sequence.Length) break; } if (i == sequence.Length) { retval = true; } } return retval; } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { } } }
/* * 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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenSim.Framework; using OpenSim.Region.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Physics.Manager; using Nini.Config; using log4net; using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { // The physical implementation of the terrain is wrapped in this class. public abstract class BSTerrainPhys : IDisposable { public enum TerrainImplementation { Heightmap = 0, Mesh = 1 } protected BSScene m_physicsScene { get; private set; } // Base of the region in world coordinates. Coordinates inside the region are relative to this. public Vector3 TerrainBase { get; private set; } public uint ID { get; private set; } public BSTerrainPhys(BSScene physicsScene, Vector3 regionBase, uint id) { m_physicsScene = physicsScene; TerrainBase = regionBase; ID = id; } public abstract void Dispose(); public abstract float GetTerrainHeightAtXYZ(Vector3 pos); public abstract float GetWaterLevelAtXYZ(Vector3 pos); } // ========================================================================================== public sealed class BSTerrainManager : IDisposable { static string LogHeader = "[BULLETSIM TERRAIN MANAGER]"; // These height values are fractional so the odd values will be // noticable when debugging. public const float HEIGHT_INITIALIZATION = 24.987f; public const float HEIGHT_INITIAL_LASTHEIGHT = 24.876f; public const float HEIGHT_GETHEIGHT_RET = 24.765f; public const float WATER_HEIGHT_GETHEIGHT_RET = 19.998f; // If the min and max height are equal, we reduce the min by this // amount to make sure that a bounding box is built for the terrain. public const float HEIGHT_EQUAL_FUDGE = 0.2f; // Until the whole simulator is changed to pass us the region size, we rely on constants. public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); // The scene that I am part of private BSScene m_physicsScene { get; set; } // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; // If doing mega-regions, if we're region zero we will be managing multiple // region terrains since region zero does the physics for the whole mega-region. private Dictionary<Vector3, BSTerrainPhys> m_terrains; // Flags used to know when to recalculate the height. private bool m_terrainModified = false; // If we are doing mega-regions, terrains are added from TERRAIN_ID to m_terrainCount. // This is incremented before assigning to new region so it is the last ID allocated. private uint m_terrainCount = BSScene.CHILDTERRAIN_ID - 1; public uint HighestTerrainID { get {return m_terrainCount; } } // If doing mega-regions, this holds our offset from region zero of // the mega-regions. "parentScene" points to the PhysicsScene of region zero. private Vector3 m_worldOffset; // If the parent region (region 0), this is the extent of the combined regions // relative to the origin of region zero private Vector3 m_worldMax; private PhysicsScene MegaRegionParentPhysicsScene { get; set; } public BSTerrainManager(BSScene physicsScene, Vector3 regionSize) { m_physicsScene = physicsScene; DefaultRegionSize = regionSize; m_terrains = new Dictionary<Vector3,BSTerrainPhys>(); // Assume one region of default size m_worldOffset = Vector3.Zero; m_worldMax = new Vector3(DefaultRegionSize); MegaRegionParentPhysicsScene = null; } public void Dispose() { ReleaseGroundPlaneAndTerrain(); } // Create the initial instance of terrain and the underlying ground plane. // This is called from the initialization routine so we presume it is // safe to call Bullet in real time. We hope no one is moving prims around yet. public void CreateInitialGroundPlaneAndTerrain() { DetailLog("{0},BSTerrainManager.CreateInitialGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, m_physicsScene.RegionName); // The ground plane is here to catch things that are trying to drop to negative infinity BulletShape groundPlaneShape = m_physicsScene.PE.CreateGroundPlaneShape(BSScene.GROUNDPLANE_ID, 1f, BSParam.TerrainCollisionMargin); Vector3 groundPlaneAltitude = new Vector3(0f, 0f, BSParam.TerrainGroundPlane); m_groundPlane = m_physicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, BSScene.GROUNDPLANE_ID, groundPlaneAltitude, Quaternion.Identity); // Everything collides with the ground plane. m_groundPlane.collisionType = CollisionType.Groundplane; m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_groundPlane); m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_groundPlane); // Ground plane does not move m_physicsScene.PE.ForceActivationState(m_groundPlane, ActivationState.DISABLE_SIMULATION); BSTerrainPhys initialTerrain = new BSTerrainHeightmap(m_physicsScene, Vector3.Zero, BSScene.TERRAIN_ID, DefaultRegionSize); lock (m_terrains) { // Build an initial terrain and put it in the world. This quickly gets replaced by the real region terrain. m_terrains.Add(Vector3.Zero, initialTerrain); } } // Release all the terrain structures we might have allocated public void ReleaseGroundPlaneAndTerrain() { DetailLog("{0},BSTerrainManager.ReleaseGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, m_physicsScene.RegionName); if (m_groundPlane.HasPhysicalBody) { if (m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_groundPlane)) { m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_groundPlane); } m_groundPlane.Clear(); } ReleaseTerrain(); } // Release all the terrain we have allocated public void ReleaseTerrain() { lock (m_terrains) { foreach (KeyValuePair<Vector3, BSTerrainPhys> kvp in m_terrains) { kvp.Value.Dispose(); } m_terrains.Clear(); } } // The simulator wants to set a new heightmap for the terrain. public void SetTerrain(float[] heightMap) { float[] localHeightMap = heightMap; // If there are multiple requests for changes to the same terrain between ticks, // only do that last one. m_physicsScene.PostTaintObject("TerrainManager.SetTerrain-"+ m_worldOffset.ToString(), 0, delegate() { if (m_worldOffset != Vector3.Zero && MegaRegionParentPhysicsScene != null) { // If a child of a mega-region, we shouldn't have any terrain allocated for us ReleaseGroundPlaneAndTerrain(); // If doing the mega-prim stuff and we are the child of the zero region, // the terrain is added to our parent if (MegaRegionParentPhysicsScene is BSScene) { DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", BSScene.DetailLogZero, m_worldOffset, m_worldMax); ((BSScene)MegaRegionParentPhysicsScene).TerrainManager.AddMegaRegionChildTerrain( BSScene.CHILDTERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize); } } else { // If not doing the mega-prim thing, just change the terrain DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); UpdateTerrain(BSScene.TERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize); } }); } // Another region is calling this region and passing a terrain. // A region that is not the mega-region root will pass its terrain to the root region so the root region // physics engine will have all the terrains. private void AddMegaRegionChildTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { // Since we are called by another region's thread, the action must be rescheduled onto our processing thread. m_physicsScene.PostTaintObject("TerrainManager.AddMegaRegionChild" + minCoords.ToString(), id, delegate() { UpdateTerrain(id, heightMap, minCoords, maxCoords); }); } // If called for terrain has has not been previously allocated, a new terrain will be built // based on the passed information. The 'id' should be either the terrain id or // BSScene.CHILDTERRAIN_ID. If the latter, a new child terrain ID will be allocated and used. // The latter feature is for creating child terrains for mega-regions. // If there is an existing terrain body, a new // terrain shape is created and added to the body. // This call is most often used to update the heightMap and parameters of the terrain. // (The above does suggest that some simplification/refactoring is in order.) // Called during taint-time. private void UpdateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { // Find high and low points of passed heightmap. // The min and max passed in is usually the area objects can be in (maximum // object height, for instance). The terrain wants the bounding box for the // terrain so replace passed min and max Z with the actual terrain min/max Z. float minZ = float.MaxValue; float maxZ = float.MinValue; foreach (float height in heightMap) { if (height < minZ) minZ = height; if (height > maxZ) maxZ = height; } if (minZ == maxZ) { // If min and max are the same, reduce min a little bit so a good bounding box is created. minZ -= BSTerrainManager.HEIGHT_EQUAL_FUDGE; } minCoords.Z = minZ; maxCoords.Z = maxZ; DetailLog("{0},BSTerrainManager.UpdateTerrain,call,id={1},minC={2},maxC={3}", BSScene.DetailLogZero, id, minCoords, maxCoords); Vector3 terrainRegionBase = new Vector3(minCoords.X, minCoords.Y, 0f); lock (m_terrains) { BSTerrainPhys terrainPhys; if (m_terrains.TryGetValue(terrainRegionBase, out terrainPhys)) { // There is already a terrain in this spot. Free the old and build the new. DetailLog("{0},BSTerrainManager.UpdateTerrain:UpdateExisting,call,id={1},base={2},minC={3},maxC={4}", BSScene.DetailLogZero, id, terrainRegionBase, minCoords, maxCoords); // Remove old terrain from the collection m_terrains.Remove(terrainRegionBase); // Release any physical memory it may be using. terrainPhys.Dispose(); if (MegaRegionParentPhysicsScene == null) { // This terrain is not part of the mega-region scheme. Create vanilla terrain. BSTerrainPhys newTerrainPhys = BuildPhysicalTerrain(terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; } else { // It's possible that Combine() was called after this code was queued. // If we are a child of combined regions, we don't create any terrain for us. DetailLog("{0},BSTerrainManager.UpdateTerrain:AmACombineChild,taint", BSScene.DetailLogZero); // Get rid of any terrain that may have been allocated for us. ReleaseGroundPlaneAndTerrain(); // I hate doing this, but just bail return; } } else { // We don't know about this terrain so either we are creating a new terrain or // our mega-prim child is giving us a new terrain to add to the phys world // if this is a child terrain, calculate a unique terrain id uint newTerrainID = id; if (newTerrainID >= BSScene.CHILDTERRAIN_ID) newTerrainID = ++m_terrainCount; DetailLog("{0},BSTerrainManager.UpdateTerrain:NewTerrain,taint,newID={1},minCoord={2},maxCoord={3}", BSScene.DetailLogZero, newTerrainID, minCoords, maxCoords); BSTerrainPhys newTerrainPhys = BuildPhysicalTerrain(terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; } } } // TODO: redo terrain implementation selection to allow other base types than heightMap. private BSTerrainPhys BuildPhysicalTerrain(Vector3 terrainRegionBase, uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { m_physicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", LogHeader, m_physicsScene.RegionName, terrainRegionBase, (BSTerrainPhys.TerrainImplementation)BSParam.TerrainImplementation); BSTerrainPhys newTerrainPhys = null; switch ((int)BSParam.TerrainImplementation) { case (int)BSTerrainPhys.TerrainImplementation.Heightmap: newTerrainPhys = new BSTerrainHeightmap(m_physicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); break; case (int)BSTerrainPhys.TerrainImplementation.Mesh: newTerrainPhys = new BSTerrainMesh(m_physicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); break; default: m_physicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. Type={1}/{2},Region={3}/{4}", LogHeader, (int)BSParam.TerrainImplementation, BSParam.TerrainImplementation, m_physicsScene.RegionName, terrainRegionBase); break; } return newTerrainPhys; } // Return 'true' of this position is somewhere in known physical terrain space public bool IsWithinKnownTerrain(Vector3 pos) { Vector3 terrainBaseXYZ; BSTerrainPhys physTerrain; return GetTerrainPhysicalAtXYZ(pos, out physTerrain, out terrainBaseXYZ); } // Return a new position that is over known terrain if the position is outside our terrain. public Vector3 ClampPositionIntoKnownTerrain(Vector3 pPos) { float edgeEpsilon = 0.1f; Vector3 ret = pPos; // First, base addresses are never negative so correct for that possible problem. if (ret.X < 0f || ret.Y < 0f) { ret.X = Util.Clamp<float>(ret.X, 0f, 1000000f); ret.Y = Util.Clamp<float>(ret.Y, 0f, 1000000f); DetailLog("{0},BSTerrainManager.ClampPositionToKnownTerrain,zeroingNegXorY,oldPos={1},newPos={2}", BSScene.DetailLogZero, pPos, ret); } // Can't do this function if we don't know about any terrain. if (m_terrains.Count == 0) return ret; int loopPrevention = 10; Vector3 terrainBaseXYZ; BSTerrainPhys physTerrain; while (!GetTerrainPhysicalAtXYZ(ret, out physTerrain, out terrainBaseXYZ)) { // The passed position is not within a known terrain area. // NOTE that GetTerrainPhysicalAtXYZ will set 'terrainBaseXYZ' to the base of the unfound region. // Must be off the top of a region. Find an adjacent region to move into. // The returned terrain is always 'lower'. That is, closer to <0,0>. Vector3 adjacentTerrainBase = FindAdjacentTerrainBase(terrainBaseXYZ); if (adjacentTerrainBase.X < terrainBaseXYZ.X) { // moving down into a new region in the X dimension. New position will be the max in the new base. ret.X = adjacentTerrainBase.X + DefaultRegionSize.X - edgeEpsilon; } if (adjacentTerrainBase.Y < terrainBaseXYZ.Y) { // moving down into a new region in the X dimension. New position will be the max in the new base. ret.Y = adjacentTerrainBase.Y + DefaultRegionSize.Y - edgeEpsilon; } DetailLog("{0},BSTerrainManager.ClampPositionToKnownTerrain,findingAdjacentRegion,adjacentRegBase={1},oldPos={2},newPos={3}", BSScene.DetailLogZero, adjacentTerrainBase, pPos, ret); if (loopPrevention-- < 0f) { // The 'while' is a little dangerous so this prevents looping forever if the // mapping of the terrains ever gets messed up (like nothing at <0,0>) or // the list of terrains is in transition. DetailLog("{0},BSTerrainManager.ClampPositionToKnownTerrain,suppressingFindAdjacentRegionLoop", BSScene.DetailLogZero); break; } } return ret; } // Given an X and Y, find the height of the terrain. // Since we could be handling multiple terrains for a mega-region, // the base of the region is calcuated assuming all regions are // the same size and that is the default. // Once the heightMapInfo is found, we have all the information to // compute the offset into the array. private float lastHeightTX = 999999f; private float lastHeightTY = 999999f; private float lastHeight = HEIGHT_INITIAL_LASTHEIGHT; public float GetTerrainHeightAtXYZ(Vector3 pos) { float tX = pos.X; float tY = pos.Y; // You'd be surprized at the number of times this routine is called // with the same parameters as last time. if (!m_terrainModified && (lastHeightTX == tX) && (lastHeightTY == tY)) return lastHeight; m_terrainModified = false; lastHeightTX = tX; lastHeightTY = tY; float ret = HEIGHT_GETHEIGHT_RET; Vector3 terrainBaseXYZ; BSTerrainPhys physTerrain; if (GetTerrainPhysicalAtXYZ(pos, out physTerrain, out terrainBaseXYZ)) { ret = physTerrain.GetTerrainHeightAtXYZ(pos - terrainBaseXYZ); } else { m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", LogHeader, m_physicsScene.RegionName, tX, tY); DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXYZ,terrainNotFound,pos={1},base={2}", BSScene.DetailLogZero, pos, terrainBaseXYZ); } lastHeight = ret; return ret; } public float GetWaterLevelAtXYZ(Vector3 pos) { float ret = WATER_HEIGHT_GETHEIGHT_RET; Vector3 terrainBaseXYZ; BSTerrainPhys physTerrain; if (GetTerrainPhysicalAtXYZ(pos, out physTerrain, out terrainBaseXYZ)) { ret = physTerrain.GetWaterLevelAtXYZ(pos); } else { m_physicsScene.Logger.ErrorFormat("{0} GetWaterHeightAtXY: terrain not found: pos={1}, terrainBase={2}, height={3}", LogHeader, m_physicsScene.RegionName, pos, terrainBaseXYZ, ret); } return ret; } // Given an address, return 'true' of there is a description of that terrain and output // the descriptor class and the 'base' fo the addresses therein. private bool GetTerrainPhysicalAtXYZ(Vector3 pos, out BSTerrainPhys outPhysTerrain, out Vector3 outTerrainBase) { bool ret = false; Vector3 terrainBaseXYZ = Vector3.Zero; if (pos.X < 0f || pos.Y < 0f) { // We don't handle negative addresses so just make up a base that will not be found. terrainBaseXYZ = new Vector3(-DefaultRegionSize.X, -DefaultRegionSize.Y, 0f); } else { int offsetX = ((int)(pos.X / (int)DefaultRegionSize.X)) * (int)DefaultRegionSize.X; int offsetY = ((int)(pos.Y / (int)DefaultRegionSize.Y)) * (int)DefaultRegionSize.Y; terrainBaseXYZ = new Vector3(offsetX, offsetY, 0f); } BSTerrainPhys physTerrain = null; lock (m_terrains) { ret = m_terrains.TryGetValue(terrainBaseXYZ, out physTerrain); } outTerrainBase = terrainBaseXYZ; outPhysTerrain = physTerrain; return ret; } // Given a terrain base, return a terrain base for a terrain that is closer to <0,0> than // this one. Usually used to return an out of bounds object to a known place. private Vector3 FindAdjacentTerrainBase(Vector3 pTerrainBase) { Vector3 ret = pTerrainBase; // Can't do this function if we don't know about any terrain. if (m_terrains.Count == 0) return ret; // Just some sanity ret.X = Util.Clamp<float>(ret.X, 0f, 1000000f); ret.Y = Util.Clamp<float>(ret.Y, 0f, 1000000f); ret.Z = 0f; lock (m_terrains) { // Once down to the <0,0> region, we have to be done. while (ret.X > 0f || ret.Y > 0f) { if (ret.X > 0f) { ret.X = Math.Max(0f, ret.X - DefaultRegionSize.X); DetailLog("{0},BSTerrainManager.FindAdjacentTerrainBase,reducingX,terrainBase={1}", BSScene.DetailLogZero, ret); if (m_terrains.ContainsKey(ret)) break; } if (ret.Y > 0f) { ret.Y = Math.Max(0f, ret.Y - DefaultRegionSize.Y); DetailLog("{0},BSTerrainManager.FindAdjacentTerrainBase,reducingY,terrainBase={1}", BSScene.DetailLogZero, ret); if (m_terrains.ContainsKey(ret)) break; } } } return ret; } // Although no one seems to check this, I do support combining. public bool SupportsCombining() { return true; } // This routine is called two ways: // One with 'offset' and 'pScene' zero and null but 'extents' giving the maximum // extent of the combined regions. This is to inform the parent of the size // of the combined regions. // and one with 'offset' as the offset of the child region to the base region, // 'pScene' pointing to the parent and 'extents' of zero. This informs the // child of its relative base and new parent. public void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) { m_worldOffset = offset; m_worldMax = extents; MegaRegionParentPhysicsScene = pScene; if (pScene != null) { // We are a child. // We want m_worldMax to be the highest coordinate of our piece of terrain. m_worldMax = offset + DefaultRegionSize; } DetailLog("{0},BSTerrainManager.Combine,offset={1},extents={2},wOffset={3},wMax={4}", BSScene.DetailLogZero, offset, extents, m_worldOffset, m_worldMax); } // Unhook all the combining that I know about. public void UnCombine(PhysicsScene pScene) { // Just like ODE, we don't do anything yet. DetailLog("{0},BSTerrainManager.UnCombine", BSScene.DetailLogZero); } private void DetailLog(string msg, params Object[] args) { m_physicsScene.PhysicsLogging.Write(msg, args); } } }
// 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; using System.Collections.Generic; using System.Security.Principal; using System.ServiceModel; namespace System.IdentityModel.Claims { internal class ClaimComparer : IEqualityComparer<Claim> { private static IEqualityComparer<Claim> s_defaultComparer; private static IEqualityComparer<Claim> s_hashComparer; private static IEqualityComparer<Claim> s_dnsComparer; private static IEqualityComparer<Claim> s_rsaComparer; private static IEqualityComparer<Claim> s_thumbprintComparer; private static IEqualityComparer<Claim> s_upnComparer; private static IEqualityComparer<Claim> s_x500DistinguishedNameComparer; private IEqualityComparer _resourceComparer; private ClaimComparer(IEqualityComparer resourceComparer) { _resourceComparer = resourceComparer; } public static IEqualityComparer<Claim> GetComparer(string claimType) { if (claimType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(claimType)); } if (claimType == ClaimTypes.Dns) { return Dns; } if (claimType == ClaimTypes.Hash) { return Hash; } if (claimType == ClaimTypes.Rsa) { return Rsa; } if (claimType == ClaimTypes.Thumbprint) { return Thumbprint; } if (claimType == ClaimTypes.Upn) { return Upn; } if (claimType == ClaimTypes.X500DistinguishedName) { return X500DistinguishedName; } return Default; } public static IEqualityComparer<Claim> Default { get { if (s_defaultComparer == null) { s_defaultComparer = new ClaimComparer(new ObjectComparer()); } return s_defaultComparer; } } public static IEqualityComparer<Claim> Dns { get { if (s_dnsComparer == null) { s_dnsComparer = new ClaimComparer(StringComparer.OrdinalIgnoreCase); } return s_dnsComparer; } } public static IEqualityComparer<Claim> Hash { get { if (s_hashComparer == null) { s_hashComparer = new ClaimComparer(new BinaryObjectComparer()); } return s_hashComparer; } } public static IEqualityComparer<Claim> Rsa { get { if (s_rsaComparer == null) { s_rsaComparer = new ClaimComparer(new RsaObjectComparer()); } return s_rsaComparer; } } public static IEqualityComparer<Claim> Thumbprint { get { if (s_thumbprintComparer == null) { s_thumbprintComparer = new ClaimComparer(new BinaryObjectComparer()); } return s_thumbprintComparer; } } public static IEqualityComparer<Claim> Upn { get { if (s_upnComparer == null) { s_upnComparer = new ClaimComparer(new UpnObjectComparer()); } return s_upnComparer; } } public static IEqualityComparer<Claim> X500DistinguishedName { get { if (s_x500DistinguishedNameComparer == null) { s_x500DistinguishedNameComparer = new ClaimComparer(new X500DistinguishedNameObjectComparer()); } return s_x500DistinguishedNameComparer; } } // we still need to review how the default equals works, this is not how Doug envisioned it. public bool Equals(Claim claim1, Claim claim2) { if (ReferenceEquals(claim1, claim2)) { return true; } if (claim1 == null || claim2 == null) { return false; } if (claim1.ClaimType != claim2.ClaimType || claim1.Right != claim2.Right) { return false; } return _resourceComparer.Equals(claim1.Resource, claim2.Resource); } public int GetHashCode(Claim claim) { if (claim == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(claim)); } return claim.ClaimType.GetHashCode() ^ claim.Right.GetHashCode() ^ ((claim.Resource == null) ? 0 : _resourceComparer.GetHashCode(claim.Resource)); } private class ObjectComparer : IEqualityComparer { bool IEqualityComparer.Equals(object obj1, object obj2) { if (obj1 == null && obj2 == null) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.Equals(obj2); } int IEqualityComparer.GetHashCode(object obj) { if (obj == null) { return 0; } return obj.GetHashCode(); } } private class BinaryObjectComparer : IEqualityComparer { bool IEqualityComparer.Equals(object obj1, object obj2) { if (ReferenceEquals(obj1, obj2)) { return true; } byte[] bytes1 = obj1 as byte[]; byte[] bytes2 = obj2 as byte[]; if (bytes1 == null || bytes2 == null) { return false; } if (bytes1.Length != bytes2.Length) { return false; } for (int i = 0; i < bytes1.Length; ++i) { if (bytes1[i] != bytes2[i]) { return false; } } return true; } int IEqualityComparer.GetHashCode(object obj) { byte[] bytes = obj as byte[]; if (bytes == null) { return 0; } int hashCode = 0; for (int i = 0; i < bytes.Length && i < 4; ++i) { hashCode = (hashCode << 8) | bytes[i]; } return hashCode ^ bytes.Length; } } private class RsaObjectComparer : IEqualityComparer { bool IEqualityComparer.Equals(object obj1, object obj2) { if (ReferenceEquals(obj1, obj2)) { return true; } throw ExceptionHelper.PlatformNotSupported(); } int IEqualityComparer.GetHashCode(object obj) { throw ExceptionHelper.PlatformNotSupported(); } } private class X500DistinguishedNameObjectComparer : IEqualityComparer { private IEqualityComparer _binaryComparer; public X500DistinguishedNameObjectComparer() { _binaryComparer = new BinaryObjectComparer(); } bool IEqualityComparer.Equals(object obj1, object obj2) { if (ReferenceEquals(obj1, obj2)) { return true; } throw ExceptionHelper.PlatformNotSupported(); } int IEqualityComparer.GetHashCode(object obj) { throw ExceptionHelper.PlatformNotSupported(); } } private class UpnObjectComparer : IEqualityComparer { bool IEqualityComparer.Equals(object obj1, object obj2) { if (StringComparer.OrdinalIgnoreCase.Equals(obj1 as string, obj2 as string)) { return true; } string upn1 = obj1 as string; string upn2 = obj2 as string; if (upn1 == null || upn2 == null) { return false; } SecurityIdentifier sid1; if (!TryLookupSidFromName(upn1, out sid1)) { return false; } // Normalize to sid SecurityIdentifier sid2; if (!TryLookupSidFromName(upn2, out sid2)) { return false; } return sid1 == sid2; } int IEqualityComparer.GetHashCode(object obj) { string upn = obj as string; if (upn == null) { return 0; } // Normalize to sid SecurityIdentifier sid; if (TryLookupSidFromName(upn, out sid)) { return sid.GetHashCode(); } return StringComparer.OrdinalIgnoreCase.GetHashCode(upn); } private bool TryLookupSidFromName(string upn, out SecurityIdentifier sid) { sid = null; try { NTAccount acct = new NTAccount(upn); sid = acct.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier; } catch (IdentityNotMappedException) { } return sid != null; } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages server side native call lifecycle. /// </summary> internal class AsyncCallServer<TRequest, TResponse> : AsyncCallBase<TResponse, TRequest> { readonly TaskCompletionSource<object> finishedServersideTcs = new TaskCompletionSource<object>(); readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); readonly Server server; public AsyncCallServer(Func<TResponse, byte[]> serializer, Func<byte[], TRequest> deserializer, Server server) : base(serializer, deserializer) { this.server = GrpcPreconditions.CheckNotNull(server); } public void Initialize(CallSafeHandle call, CompletionQueueSafeHandle completionQueue) { call.Initialize(completionQueue); server.AddCallReference(this); InitializeInternal(call); } /// <summary> /// Only for testing purposes. /// </summary> public void InitializeForTesting(INativeCall call) { server.AddCallReference(this); InitializeInternal(call); } /// <summary> /// Starts a server side call. /// </summary> public Task ServerSideCallAsync() { lock (myLock) { GrpcPreconditions.CheckNotNull(call); started = true; call.StartServerSide(HandleFinishedServerside); return finishedServersideTcs.Task; } } /// <summary> /// Sends a streaming response. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TResponse msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming request. Only one pending read action is allowed at any given time. /// </summary> public Task<TRequest> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Initiates sending a initial metadata. /// Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation /// to make things simpler. /// </summary> public Task SendInitialMetadataAsync(Metadata headers) { lock (myLock) { GrpcPreconditions.CheckNotNull(headers, "metadata"); GrpcPreconditions.CheckState(started); GrpcPreconditions.CheckState(!initialMetadataSent, "Response headers can only be sent once per call."); GrpcPreconditions.CheckState(streamingWritesCounter == 0, "Response headers can only be sent before the first write starts."); var earlyResult = CheckSendAllowedOrEarlyResult(); if (earlyResult != null) { return earlyResult; } using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartSendInitialMetadata(HandleSendFinished, metadataArray); } this.initialMetadataSent = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Sends call result status, indicating we are done with writes. /// Sending a status different from StatusCode.OK will also implicitly cancel the call. /// </summary> public Task SendStatusFromServerAsync(Status status, Metadata trailers, Tuple<TResponse, WriteFlags> optionalWrite) { byte[] payload = optionalWrite != null ? UnsafeSerialize(optionalWrite.Item1) : null; var writeFlags = optionalWrite != null ? optionalWrite.Item2 : default(WriteFlags); lock (myLock) { GrpcPreconditions.CheckState(started); GrpcPreconditions.CheckState(!disposed); GrpcPreconditions.CheckState(!halfcloseRequested, "Can only send status from server once."); using (var metadataArray = MetadataArraySafeHandle.Create(trailers)) { call.StartSendStatusFromServer(HandleSendStatusFromServerFinished, status, metadataArray, !initialMetadataSent, payload, writeFlags); } halfcloseRequested = true; initialMetadataSent = true; sendStatusFromServerTcs = new TaskCompletionSource<object>(); if (optionalWrite != null) { streamingWritesCounter++; } return sendStatusFromServerTcs.Task; } } /// <summary> /// Gets cancellation token that gets cancelled once close completion /// is received and the cancelled flag is set. /// </summary> public CancellationToken CancellationToken { get { return cancellationTokenSource.Token; } } public string Peer { get { return call.GetPeer(); } } protected override bool IsClient { get { return false; } } protected override Exception GetRpcExceptionClientOnly() { throw new InvalidOperationException("Call be only called for client calls"); } protected override void OnAfterReleaseResources() { server.RemoveCallReference(this); } protected override Task CheckSendAllowedOrEarlyResult() { GrpcPreconditions.CheckState(!halfcloseRequested, "Response stream has already been completed."); GrpcPreconditions.CheckState(!finished, "Already finished."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time"); GrpcPreconditions.CheckState(!disposed); return null; } /// <summary> /// Handles the server side close completion. /// </summary> private void HandleFinishedServerside(bool success, bool cancelled) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_CLOSE_ON_SERVER, // success will be always set to true. lock (myLock) { finished = true; if (streamingReadTcs == null) { // if there's no pending read, readingDone=true will dispose now. // if there is a pending read, we will dispose once that read finishes. readingDone = true; streamingReadTcs = new TaskCompletionSource<TRequest>(); streamingReadTcs.SetResult(default(TRequest)); } ReleaseResourcesIfPossible(); } if (cancelled) { cancellationTokenSource.Cancel(); } finishedServersideTcs.SetResult(null); } } }
/* Copyright 2012-2022 Marco De Salvo 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 Microsoft.VisualStudio.TestTools.UnitTesting; using RDFSharp.Model; using System; using System.Collections.Generic; using System.Linq; namespace RDFSharp.Test.Model { [TestClass] public class RDFMinLengthConstraintTest { #region Tests [TestMethod] public void ShouldCreateMinLengthConstraint() { RDFMinLengthConstraint minLengthConstraint = new RDFMinLengthConstraint(2); Assert.IsNotNull(minLengthConstraint); Assert.IsTrue(minLengthConstraint.MinLength == 2); } [TestMethod] public void ShouldCreateMinLengthConstraintLowerThanZero() { RDFMinLengthConstraint minLengthConstraint = new RDFMinLengthConstraint(-2); Assert.IsNotNull(minLengthConstraint); Assert.IsTrue(minLengthConstraint.MinLength == 0); } [TestMethod] public void ShouldExportMinLengthConstraint() { RDFMinLengthConstraint minLengthConstraint = new RDFMinLengthConstraint(2); RDFGraph graph = minLengthConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 1); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.MIN_LENGTH) && t.Value.Object.Equals(new RDFTypedLiteral("2", RDFModelEnums.RDFDatatypes.XSD_INTEGER)))); } //NS-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //PS-CONFORMS:TRUE [TestMethod] public void ShouldConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinLengthConstraint(6)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //NS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMinLengthConstraint(7)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); nodeShape.AddConstraint(new RDFMinLengthConstraint(7)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinLengthConstraint(7)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinLengthConstraint(7)); nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage")); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } //PS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMinLengthConstraint(7)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 7 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); propertyShape.AddConstraint(new RDFMinLengthConstraint(9)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 9 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinLengthConstraint(7)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 7 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:S"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinLengthConstraint(5)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 5 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:S"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } //MIXED-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:name"), new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MinLengthExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:name")); propShape.AddConstraint(new RDFMinLengthConstraint(5)); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //MIXED-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:name"), new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MinLengthExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:name")); propShape.AddConstraint(new RDFMinLengthConstraint(6)); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 6 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFTypedLiteral("Bobby", RDFModelEnums.RDFDatatypes.XSD_STRING))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:name"))); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithPropertyShapeBecauseBlankValue() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:hasBlank"), new RDFResource("bnode:12345"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:MinLengthExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:hasBlank")); propShape.AddConstraint(new RDFMinLengthConstraint(6)); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have a minimum length of 6 characters and can't be a blank node"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("bnode:12345"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:hasBlank"))); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_LENGTH_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape"))); } #endregion } }
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 PSLLunch.Areas.HelpPage { /// <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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
// 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.Security.Util { using System.Text; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; using System.IO; using System.Diagnostics.Contracts; [Serializable] internal class StringExpressionSet { // This field, as well as the expressions fields below are critical since they may contain // canonicalized full path data potentially built out of relative data passed as input to the // StringExpressionSet. Full trust code using the string expression set needs to ensure that before // exposing this data out to partial trust, they protect against this. Possibilities include: // // 1. Using the throwOnRelative flag // 2. Ensuring that the partial trust code has permission to see full path data // 3. Not using this set for paths (eg EnvironmentStringExpressionSet) // [SecurityCritical] protected ArrayList m_list; protected bool m_ignoreCase; [SecurityCritical] protected String m_expressions; [SecurityCritical] protected String[] m_expressionsArray; protected bool m_throwOnRelative; protected static readonly char[] m_separators = { ';' }; protected static readonly char[] m_trimChars = { ' ' }; #if !PLATFORM_UNIX protected static readonly char m_directorySeparator = '\\'; protected static readonly char m_alternateDirectorySeparator = '/'; #else protected static readonly char m_directorySeparator = '/'; protected static readonly char m_alternateDirectorySeparator = '\\'; #endif // !PLATFORM_UNIX public StringExpressionSet() : this( true, null, false ) { } public StringExpressionSet( String str ) : this( true, str, false ) { } public StringExpressionSet( bool ignoreCase, bool throwOnRelative ) : this( ignoreCase, null, throwOnRelative ) { } [System.Security.SecuritySafeCritical] // auto-generated public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative ) { m_list = null; m_ignoreCase = ignoreCase; m_throwOnRelative = throwOnRelative; if (str == null) m_expressions = null; else AddExpressions( str ); } protected virtual StringExpressionSet CreateNewEmpty() { return new StringExpressionSet(); } [SecuritySafeCritical] public virtual StringExpressionSet Copy() { // SafeCritical: just copying this value around, not leaking it StringExpressionSet copy = CreateNewEmpty(); if (this.m_list != null) copy.m_list = new ArrayList(this.m_list); copy.m_expressions = this.m_expressions; copy.m_ignoreCase = this.m_ignoreCase; copy.m_throwOnRelative = this.m_throwOnRelative; return copy; } public void SetThrowOnRelative( bool throwOnRelative ) { this.m_throwOnRelative = throwOnRelative; } private static String StaticProcessWholeString( String str ) { return str.Replace( m_alternateDirectorySeparator, m_directorySeparator ); } private static String StaticProcessSingleString( String str ) { return str.Trim( m_trimChars ); } protected virtual String ProcessWholeString( String str ) { return StaticProcessWholeString(str); } protected virtual String ProcessSingleString( String str ) { return StaticProcessSingleString(str); } [System.Security.SecurityCritical] // auto-generated public void AddExpressions( String str ) { if (str == null) throw new ArgumentNullException( "str" ); Contract.EndContractBlock(); if (str.Length == 0) return; str = ProcessWholeString( str ); if (m_expressions == null) m_expressions = str; else m_expressions = m_expressions + m_separators[0] + str; m_expressionsArray = null; // We have to parse the string and compute the list here. // The logic in this class tries to delay this parsing but // since operations like IsSubsetOf are called during // demand evaluation, it is not safe to delay this step // as that would cause concurring threads to update the object // at the same time. The CheckList operation should ideally be // removed from this class, but for the sake of keeping the // changes to a minimum here, we simply make sure m_list // cannot be null by parsing m_expressions eagerly. String[] arystr = Split( str ); if (m_list == null) m_list = new ArrayList(); for (int index = 0; index < arystr.Length; ++index) { if (arystr[index] != null && !arystr[index].Equals( "" )) { String temp = ProcessSingleString( arystr[index] ); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && !temp.Equals( "" )) { if (m_throwOnRelative) { if (Path.IsRelative(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp ); } m_list.Add( temp ); } } } Reduce(); } [System.Security.SecurityCritical] // auto-generated public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath ) { AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates); } [System.Security.SecurityCritical] // auto-generated public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) { Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); m_expressionsArray = null; m_expressions = null; if (m_list != null) m_list.AddRange(exprArrayList); else m_list = new ArrayList(exprArrayList); if (checkForDuplicates) Reduce(); } [System.Security.SecurityCritical] // auto-generated internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath) { if (str == null) { throw new ArgumentNullException( "str" ); } Contract.EndContractBlock(); ArrayList retArrayList = new ArrayList(); for (int index = 0; index < str.Length; ++index) { if (str[index] == null) throw new ArgumentNullException( "str" ); // Replace alternate directory separators String oneString = StaticProcessWholeString( str[index] ); if (oneString != null && oneString.Length != 0) { // Trim leading and trailing spaces String temp = StaticProcessSingleString( oneString); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && temp.Length != 0) { if (PathInternal.IsPartiallyQualified(temp)) { throw new ArgumentException(Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp, needFullPath ); retArrayList.Add( temp ); } } } return retArrayList; } [System.Security.SecurityCritical] // auto-generated protected void CheckList() { if (m_list == null && m_expressions != null) { CreateList(); } } protected String[] Split( String expressions ) { if (m_throwOnRelative) { List<String> tempList = new List<String>(); String[] quoteSplit = expressions.Split( '\"' ); for (int i = 0; i < quoteSplit.Length; ++i) { if (i % 2 == 0) { String[] semiSplit = quoteSplit[i].Split( ';' ); for (int j = 0; j < semiSplit.Length; ++j) { if (semiSplit[j] != null && !semiSplit[j].Equals( "" )) tempList.Add( semiSplit[j] ); } } else { tempList.Add( quoteSplit[i] ); } } String[] finalArray = new String[tempList.Count]; IEnumerator enumerator = tempList.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { finalArray[index++] = (String)enumerator.Current; } return finalArray; } else { return expressions.Split( m_separators ); } } [System.Security.SecurityCritical] // auto-generated protected void CreateList() { String[] expressionsArray = Split( m_expressions ); m_list = new ArrayList(); for (int index = 0; index < expressionsArray.Length; ++index) { if (expressionsArray[index] != null && !expressionsArray[index].Equals( "" )) { String temp = ProcessSingleString( expressionsArray[index] ); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && !temp.Equals( "" )) { if (m_throwOnRelative) { if (Path.IsRelative(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp ); } m_list.Add( temp ); } } } } [SecuritySafeCritical] public bool IsEmpty() { // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their // contents - not the existence of the contents if (m_list == null) { return m_expressions == null; } else { return m_list.Count == 0; } } [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOf( StringExpressionSet ses ) { if (this.IsEmpty()) return true; if (ses == null || ses.IsEmpty()) return false; CheckList(); ses.CheckList(); for (int index = 0; index < this.m_list.Count; ++index) { if (!StringSubsetStringExpression( (String)this.m_list[index], ses, m_ignoreCase )) { return false; } } return true; } [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOfPathDiscovery( StringExpressionSet ses ) { if (this.IsEmpty()) return true; if (ses == null || ses.IsEmpty()) return false; CheckList(); ses.CheckList(); for (int index = 0; index < this.m_list.Count; ++index) { if (!StringSubsetStringExpressionPathDiscovery( (String)this.m_list[index], ses, m_ignoreCase )) { return false; } } return true; } [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Union( StringExpressionSet ses ) { // If either set is empty, the union represents a copy of the other. if (ses == null || ses.IsEmpty()) return this.Copy(); if (this.IsEmpty()) return ses.Copy(); CheckList(); ses.CheckList(); // Perform the union // note: insert smaller set into bigger set to reduce needed comparisons StringExpressionSet bigger = ses.m_list.Count > this.m_list.Count ? ses : this; StringExpressionSet smaller = ses.m_list.Count <= this.m_list.Count ? ses : this; StringExpressionSet unionSet = bigger.Copy(); unionSet.Reduce(); for (int index = 0; index < smaller.m_list.Count; ++index) { unionSet.AddSingleExpressionNoDuplicates( (String)smaller.m_list[index] ); } unionSet.GenerateString(); return unionSet; } [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Intersect( StringExpressionSet ses ) { // If either set is empty, the intersection is empty if (this.IsEmpty() || ses == null || ses.IsEmpty()) return CreateNewEmpty(); CheckList(); ses.CheckList(); // Do the intersection for real StringExpressionSet intersectSet = CreateNewEmpty(); for (int this_index = 0; this_index < this.m_list.Count; ++this_index) { for (int ses_index = 0; ses_index < ses.m_list.Count; ++ses_index) { if (StringSubsetString( (String)this.m_list[this_index], (String)ses.m_list[ses_index], m_ignoreCase )) { if (intersectSet.m_list == null) { intersectSet.m_list = new ArrayList(); } intersectSet.AddSingleExpressionNoDuplicates( (String)this.m_list[this_index] ); } else if (StringSubsetString( (String)ses.m_list[ses_index], (String)this.m_list[this_index], m_ignoreCase )) { if (intersectSet.m_list == null) { intersectSet.m_list = new ArrayList(); } intersectSet.AddSingleExpressionNoDuplicates( (String)ses.m_list[ses_index] ); } } } intersectSet.GenerateString(); return intersectSet; } [SecuritySafeCritical] protected void GenerateString() { // SafeCritical - moves critical data around, but doesn't expose it out if (m_list != null) { StringBuilder sb = new StringBuilder(); IEnumerator enumerator = this.m_list.GetEnumerator(); bool first = true; while (enumerator.MoveNext()) { if (!first) sb.Append( m_separators[0] ); else first = false; String currentString = (String)enumerator.Current; if (currentString != null) { int indexOfSeparator = currentString.IndexOf( m_separators[0] ); if (indexOfSeparator != -1) sb.Append( '\"' ); sb.Append( currentString ); if (indexOfSeparator != -1) sb.Append( '\"' ); } } m_expressions = sb.ToString(); } else { m_expressions = null; } } // We don't override ToString since that API must be either transparent or safe citical. If the // expressions contain paths that were canonicalized and expanded from the input that would cause // information disclosure, so we instead only expose this out to trusted code that can ensure they // either don't leak the information or required full path information. [SecurityCritical] public string UnsafeToString() { CheckList(); Reduce(); GenerateString(); return m_expressions; } [SecurityCritical] public String[] UnsafeToStringArray() { if (m_expressionsArray == null && m_list != null) { m_expressionsArray = (String[])m_list.ToArray(typeof(String)); } return m_expressionsArray; } //------------------------------- // protected static helper functions //------------------------------- [SecurityCritical] private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) { if (StringSubsetString( left, (String)right.m_list[index], ignoreCase )) { return true; } } return false; } [SecurityCritical] private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) { if (StringSubsetStringPathDiscovery( left, (String)right.m_list[index], ignoreCase )) { return true; } } return false; } protected virtual bool StringSubsetString( String left, String right, bool ignoreCase ) { StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (right == null || left == null || right.Length == 0 || left.Length == 0 || right.Length > left.Length) { return false; } else if (right.Length == left.Length) { // if they are equal in length, just do a normal compare return String.Compare( right, left, strComp) == 0; } else if (left.Length - right.Length == 1 && left[left.Length-1] == m_directorySeparator) { return String.Compare( left, 0, right, 0, right.Length, strComp) == 0; } else if (right[right.Length-1] == m_directorySeparator) { // right is definitely a directory, just do a substring compare return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; } else if (left[right.Length] == m_directorySeparator) { // left is hinting at being a subdirectory on right, do substring compare to make find out return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; } else { return false; } } protected static bool StringSubsetStringPathDiscovery( String left, String right, bool ignoreCase ) { StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (right == null || left == null || right.Length == 0 || left.Length == 0) { return false; } else if (right.Length == left.Length) { // if they are equal in length, just do a normal compare return String.Compare( right, left, strComp) == 0; } else { String shortString, longString; if (right.Length < left.Length) { shortString = right; longString = left; } else { shortString = left; longString = right; } if (String.Compare( shortString, 0, longString, 0, shortString.Length, strComp) != 0) { return false; } #if !PLATFORM_UNIX if (shortString.Length == 3 && shortString.EndsWith( ":\\", StringComparison.Ordinal ) && ((shortString[0] >= 'A' && shortString[0] <= 'Z') || (shortString[0] >= 'a' && shortString[0] <= 'z'))) #else if (shortString.Length == 1 && shortString[0]== m_directorySeparator) #endif // !PLATFORM_UNIX return true; return longString[shortString.Length] == m_directorySeparator; } } //------------------------------- // protected helper functions //------------------------------- [SecuritySafeCritical] protected void AddSingleExpressionNoDuplicates( String expression ) { // SafeCritical: We're not exposing out the string sets, just allowing modification of them int index = 0; m_expressionsArray = null; m_expressions = null; if (this.m_list == null) this.m_list = new ArrayList(); while (index < this.m_list.Count) { if (StringSubsetString( (String)this.m_list[index], expression, m_ignoreCase )) { this.m_list.RemoveAt( index ); } else if (StringSubsetString( expression, (String)this.m_list[index], m_ignoreCase )) { return; } else { index++; } } this.m_list.Add( expression ); } [System.Security.SecurityCritical] // auto-generated protected void Reduce() { CheckList(); if (this.m_list == null) return; int j; for (int i = 0; i < this.m_list.Count - 1; i++) { j = i + 1; while (j < this.m_list.Count) { if (StringSubsetString( (String)this.m_list[j], (String)this.m_list[i], m_ignoreCase )) { this.m_list.RemoveAt( j ); } else if (StringSubsetString( (String)this.m_list[i], (String)this.m_list[j], m_ignoreCase )) { // write the value at j into position i, delete the value at position j and keep going. this.m_list[i] = this.m_list[j]; this.m_list.RemoveAt( j ); j = i + 1; } else { j++; } } } } [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath ); [System.Security.SecurityCritical] // auto-generated internal static String CanonicalizePath( String path ) { return CanonicalizePath( path, true ); } [System.Security.SecurityCritical] // auto-generated internal static string CanonicalizePath(string path, bool needFullPath) { if (needFullPath) { string newPath = Path.GetFullPathInternal(path); if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal)) { if (newPath.EndsWith(m_directorySeparator)) { newPath += "."; } else { newPath += m_directorySeparator + "."; } } path = newPath; } #if !PLATFORM_UNIX else if (path.IndexOf('~') != -1) { // GetFullPathInternal() will expand 8.3 file names string longPath = null; GetLongPathName(path, JitHelpers.GetStringHandleOnStack(ref longPath)); path = (longPath != null) ? longPath : path; } // This blocks usage of alternate data streams and some extended syntax paths (\\?\C:\). Checking after // normalization allows valid paths such as " C:\" to be considered ok (as it will become "C:\"). if (path.IndexOf(':', 2) != -1) throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); #endif // !PLATFORM_UNIX return path; } } }
using System; using System.IO; namespace CatLib._3rd.SharpCompress.Compressors.LZMA.LZ { internal class OutWindow { private byte[] _buffer; private int _windowSize; private int _pos; private int _streamPos; private int _pendingLen; private int _pendingDist; private Stream _stream; public long Total; public long Limit; public void Create(int windowSize) { if (_windowSize != windowSize) { _buffer = new byte[windowSize]; } else { _buffer[windowSize - 1] = 0; } _windowSize = windowSize; _pos = 0; _streamPos = 0; _pendingLen = 0; Total = 0; Limit = 0; } public void Reset() { Create(_windowSize); } public void Init(Stream stream) { ReleaseStream(); _stream = stream; } public void Train(Stream stream) { long len = stream.Length; int size = (len < _windowSize) ? (int)len : _windowSize; stream.Position = len - size; Total = 0; Limit = size; _pos = _windowSize - size; CopyStream(stream, size); if (_pos == _windowSize) { _pos = 0; } _streamPos = _pos; } public void ReleaseStream() { Flush(); _stream = null; } public void Flush() { if (_stream == null) { return; } int size = _pos - _streamPos; if (size == 0) { return; } _stream.Write(_buffer, _streamPos, size); if (_pos >= _windowSize) { _pos = 0; } _streamPos = _pos; } public void CopyBlock(int distance, int len) { int size = len; int pos = _pos - distance - 1; if (pos < 0) { pos += _windowSize; } for (; size > 0 && _pos < _windowSize && Total < Limit; size--) { if (pos >= _windowSize) { pos = 0; } _buffer[_pos++] = _buffer[pos++]; Total++; if (_pos >= _windowSize) { Flush(); } } _pendingLen = size; _pendingDist = distance; } public void PutByte(byte b) { _buffer[_pos++] = b; Total++; if (_pos >= _windowSize) { Flush(); } } public byte GetByte(int distance) { int pos = _pos - distance - 1; if (pos < 0) { pos += _windowSize; } return _buffer[pos]; } public int CopyStream(Stream stream, int len) { int size = len; while (size > 0 && _pos < _windowSize && Total < Limit) { int curSize = _windowSize - _pos; if (curSize > Limit - Total) { curSize = (int)(Limit - Total); } if (curSize > size) { curSize = size; } int numReadBytes = stream.Read(_buffer, _pos, curSize); if (numReadBytes == 0) { throw new DataErrorException(); } size -= numReadBytes; _pos += numReadBytes; Total += numReadBytes; if (_pos >= _windowSize) { Flush(); } } return len - size; } public void SetLimit(long size) { Limit = Total + size; } public bool HasSpace { get { return _pos < _windowSize && Total < Limit; } } public bool HasPending { get { return _pendingLen > 0; } } public int Read(byte[] buffer, int offset, int count) { if (_streamPos >= _pos) { return 0; } int size = _pos - _streamPos; if (size > count) { size = count; } Buffer.BlockCopy(_buffer, _streamPos, buffer, offset, size); _streamPos += size; if (_streamPos >= _windowSize) { _pos = 0; _streamPos = 0; } return size; } public void CopyPending() { if (_pendingLen > 0) { CopyBlock(_pendingDist, _pendingLen); } } public int AvailableBytes { get { return _pos - _streamPos; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Net; using System.Linq; using Microsoft.Azure; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Test; using Microsoft.Rest.TransientFaultHandling; using Xunit; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Microsoft.Rest.Azure.OData; using System; namespace ResourceGroups.Tests { public class LiveResourceTests : TestBase { const string WebResourceProviderVersion = "2018-02-01"; const string SendGridResourceProviderVersion = "2015-01-01"; string ResourceGroupLocation { get { return "South Central US"; } } public static ResourceIdentity CreateResourceIdentity(GenericResource resource) { string[] parts = resource.Type.Split('/'); return new ResourceIdentity { ResourceType = parts[1], ResourceProviderNamespace = parts[0], ResourceName = resource.Name, ResourceProviderApiVersion = WebResourceProviderVersion }; } public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return this.GetResourceManagementClientWithHandler(context, handler); } public string GetWebsiteLocation(ResourceManagementClient client) { return "West US"; } public string GetMySqlLocation(ResourceManagementClient client) { return ResourcesManagementTestUtilities.GetResourceLocation(client, "SuccessBricks.ClearDB/databases"); } [Fact] public void CreateResourceWithPlan() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); string password = TestUtilities.GenerateName("p@ss"); var client = GetResourceManagementClient(context, handler); string mySqlLocation = "centralus"; var groupIdentity = new ResourceIdentity { ResourceName = resourceName, ResourceProviderNamespace = "Sendgrid.Email", ResourceType = "accounts", ResourceProviderApiVersion = SendGridResourceProviderVersion }; client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "centralus" }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity.ResourceProviderNamespace, "", groupIdentity.ResourceType, groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion, new GenericResource { Location = mySqlLocation, Plan = new Plan {Name = "free", Publisher= "Sendgrid",Product= "sendgrid_azure",PromotionCode="" }, Tags = new Dictionary<string, string> { { "provision_source", "RMS" } }, Properties = JObject.Parse("{'password':'" + password + "','acceptMarketingEmails':false,'email':'tiano@email.com'}"), } ); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Location), string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, mySqlLocation)); Assert.NotNull(createOrUpdateResult.Plan); Assert.Equal("free", createOrUpdateResult.Plan.Name); var getResult = client.Resources.Get(groupName, groupIdentity.ResourceProviderNamespace, "", groupIdentity.ResourceType, groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion); Assert.Equal(resourceName, getResult.Name); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Location), string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Location, mySqlLocation)); Assert.NotNull(getResult.Plan); Assert.Equal("free", getResult.Plan.Name); } } [Fact] public void CreatedResourceIsAvailableInList() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(context, handler); string location = GetWebsiteLocation(client); client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, "Microsoft.Web", "", "serverFarms",resourceName, WebResourceProviderVersion, new GenericResource { Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); Assert.NotNull(createOrUpdateResult.Id); Assert.Equal(resourceName, createOrUpdateResult.Name); Assert.True(string.Equals("Microsoft.Web/serverFarms", createOrUpdateResult.Type, StringComparison.InvariantCultureIgnoreCase)); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(location, createOrUpdateResult.Location), string.Format("Resource location for website '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, location)); var listResult = client.Resources.ListByResourceGroup(groupName); Assert.Single(listResult); Assert.Equal(resourceName, listResult.First().Name); Assert.True(string.Equals("Microsoft.Web/serverFarms", createOrUpdateResult.Type, StringComparison.InvariantCultureIgnoreCase)); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(location, listResult.First().Location), string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, location)); listResult = client.Resources.ListByResourceGroup(groupName, new ODataQuery<GenericResourceFilter> { Top = 10 }); Assert.Single(listResult); Assert.Equal(resourceName, listResult.First().Name); Assert.True(string.Equals("Microsoft.Web/serverFarms", createOrUpdateResult.Type, StringComparison.InvariantCultureIgnoreCase)); Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(location, listResult.First().Location), string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, location)); } } [Fact] public void CreatedResourceIsAvailableInListFilteredByTagName() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); string resourceNameNoTags = TestUtilities.GenerateName("csmr"); string tagName = TestUtilities.GenerateName("csmtn"); var client = GetResourceManagementClient(context, handler); string location = GetWebsiteLocation(client); client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", string.Empty, "serverFarms", resourceName, WebResourceProviderVersion, new GenericResource { Tags = new Dictionary<string, string> { { tagName, "" } }, Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") }); client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", string.Empty, "serverFarms", resourceNameNoTags, WebResourceProviderVersion, new GenericResource { Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") }); var listResult = client.Resources.ListByResourceGroup(groupName, new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName)); Assert.Single(listResult); Assert.Equal(resourceName, listResult.First().Name); var getResult = client.Resources.Get( groupName, "Microsoft.Web", string.Empty, "serverFarms", resourceName, WebResourceProviderVersion); Assert.Equal(resourceName, getResult.Name); Assert.True(getResult.Tags.Keys.Contains(tagName)); } } [Fact] public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); string resourceNameNoTags = TestUtilities.GenerateName("csmr"); string tagName = TestUtilities.GenerateName("csmtn"); string tagValue = TestUtilities.GenerateName("csmtv"); var client = GetResourceManagementClient(context, handler); string location = GetWebsiteLocation(client); client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation }); client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", "", "serverFarms", resourceName, WebResourceProviderVersion, new GenericResource { Tags = new Dictionary<string, string> { { tagName, tagValue } }, Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", "", "serverFarms", resourceNameNoTags, WebResourceProviderVersion, new GenericResource { Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); var listResult = client.Resources.ListByResourceGroup(groupName, new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName && r.Tagvalue == tagValue)); Assert.Single(listResult); Assert.Equal(resourceName, listResult.First().Name); var getResult = client.Resources.Get( groupName, "Microsoft.Web", "", "serverFarms", resourceName, WebResourceProviderVersion); Assert.Equal(resourceName, getResult.Name); Assert.True(getResult.Tags.Keys.Contains(tagName)); } } [Fact] public void CreatedAndDeleteResource() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(context, handler); client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); string location = this.GetWebsiteLocation(client); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location }); var createOrUpdateResult = client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", "", "serverfarms", resourceName, WebResourceProviderVersion, new GenericResource { Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); var listResult = client.Resources.ListByResourceGroup(groupName); Assert.Equal(resourceName, listResult.First().Name); client.Resources.Delete( groupName, "Microsoft.Web", "", "serverfarms", resourceName, WebResourceProviderVersion); } } [Fact] public void CreatedAndDeleteResourceById() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string subscriptionId = "a1bfa635-f2bf-42f1-86b5-848c674fc321"; string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(context, handler); client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1)); string location = this.GetWebsiteLocation(client); string resourceId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/serverFarms/{2}", subscriptionId, groupName, resourceName); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location }); var createOrUpdateResult = client.Resources.CreateOrUpdateById( resourceId, WebResourceProviderVersion, new GenericResource { Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); var listResult = client.Resources.ListByResourceGroup(groupName); Assert.Equal(resourceName, listResult.First().Name); client.Resources.DeleteById( resourceId, WebResourceProviderVersion); } } [Fact] public void CreatedAndListResource() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string groupName = TestUtilities.GenerateName("csmrg"); string resourceName = TestUtilities.GenerateName("csmr"); var client = GetResourceManagementClient(context, handler); string location = this.GetWebsiteLocation(client); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location }); var createOrUpdateResult = client.Resources.CreateOrUpdate( groupName, "Microsoft.Web", "", "serverFarms", resourceName, WebResourceProviderVersion, new GenericResource { Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } }, Location = location, Sku = new Sku { Name = "S1" }, Properties = JObject.Parse("{}") } ); var listResult = client.Resources.List(new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/serverFarms")); Assert.NotEmpty(listResult); Assert.Equal(2, listResult.First().Tags.Count); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Centralized error methods for the IO package. ** Mostly useful for translating Win32 HRESULTs into meaningful ** error strings & exceptions. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using Win32Native = Microsoft.Win32.Win32Native; using System.Text; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace System.IO { [Pure] internal static class __Error { internal static void EndOfFile() { throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF")); } internal static void FileNotOpen() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed")); } internal static void StreamIsClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); } internal static void MemoryStreamNotExpandable() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable")); } internal static void ReaderClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed")); } internal static void ReadNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); } internal static void SeekNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } internal static void WrongAsyncResult() { throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult")); } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple")); } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple")); } // Given a possible fully qualified path, ensure that we have path // discovery permission to that path. If we do not, return just the // file name. If we know it is a directory, then don't return the // directory name. internal static String GetDisplayablePath(String path, bool isInvalidPath) { if (String.IsNullOrEmpty(path)) return String.Empty; // Is it a fully qualified path? bool isFullyQualified = false; if (path.Length < 2) return path; if (PathInternal.IsDirectorySeparator(path[0]) && PathInternal.IsDirectorySeparator(path[1])) isFullyQualified = true; else if (path[1] == Path.VolumeSeparatorChar) { isFullyQualified = true; } if (!isFullyQualified && !isInvalidPath) return path; bool safeToReturn = false; try { if (!isInvalidPath) { safeToReturn = true; } } catch (SecurityException) { } catch (ArgumentException) { // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters // inside FileIOPermission.AddPathList } catch (NotSupportedException) { // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path // beyond string index position 1. } if (!safeToReturn) { if (PathInternal.IsDirectorySeparator(path[path.Length - 1])) path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName"); else path = Path.GetFileName(path); } return path; } internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } // After calling GetLastWin32Error(), it clears the last error field, // so you must save the HResult and pass it to this method. This method // will determine the appropriate exception to throw dependent on your // error, and depending on the error, insert a string into the message // gotten from the ResourceManager. internal static void WinIOError(int errorCode, String maybeFullPath) { // This doesn't have to be perfect, but is a perf optimization. bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; String str = GetDisplayablePath(maybeFullPath, isInvalidPath); switch (errorCode) { case Win32Native.ERROR_FILE_NOT_FOUND: if (str.Length == 0) throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound")); else throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str); case Win32Native.ERROR_PATH_NOT_FOUND: if (str.Length == 0) throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName")); else throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str)); case Win32Native.ERROR_ACCESS_DENIED: if (str.Length == 0) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName")); else throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str)); case Win32Native.ERROR_ALREADY_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILENAME_EXCED_RANGE: throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str)); case Win32Native.ERROR_INVALID_PARAMETER: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_SHARING_VIOLATION: if (str.Length == 0) throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); else throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILE_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(); default: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); } } // An alternative to WinIOError with friendlier messages for drives internal static void WinIODriveError(String driveName) { int errorCode = Marshal.GetLastWin32Error(); WinIODriveError(driveName, errorCode); } internal static void WinIODriveError(String driveName, int errorCode) { switch (errorCode) { case Win32Native.ERROR_PATH_NOT_FOUND: case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", driveName)); default: WinIOError(errorCode, driveName); break; } } internal static void WriteNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); } internal static void WriterClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_WriterClosed")); } // From WinError.h internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } }
using System; using System.Collections; using System.Text; using System.Web; using System.IO; using System.Net; using System.Web.Script.Serialization; public class AfricasTalkingGatewayException: Exception { public AfricasTalkingGatewayException(string message) : base(message) { } } public class AfricasTalkingGateway { private string _username; private string _apiKey; private int responseCode; private JavaScriptSerializer serializer; private static string SMS_URLString = "https://api.africastalking.com/version1/messaging"; private static string VOICE_URLString = "https://voice.africastalking.com"; private static string SUBSCRIPTION_URLString = "https://api.africastalking.com/subscription"; private static string USERDATA_URLString = "https://api.africastalking.com/version1/user"; private static string AIRTIME_URLString = "https://api.africastalking.com/version1/airtime"; //Change the debug flag to true to view the full response private Boolean DEBUG = false; public AfricasTalkingGateway(string username_, string apiKey_) { _username = username_; _apiKey = apiKey_; serializer = new JavaScriptSerializer (); } public dynamic sendMessage (string to_, string message_, string from_ = null, int bulkSMSMode_ = 1, Hashtable options_ = null) { Hashtable data = new Hashtable (); data ["username"] = _username; data ["to"] = to_; data ["message"] = message_; if (from_ != null) { data ["from"] = from_; data ["bulkSMSMode"] = Convert.ToString (bulkSMSMode_); if (options_ != null) { if (options_.Contains("keyword")) { data["keyword"] = options_["keyword"]; } if (options_.Contains("linkId")) { data["linkId"] = options_["linkId"]; } if (options_.Contains("enqueue")) { data["enqueue"] = options_["enqueue"]; } if(options_.Contains("retryDurationInHours")) data["retryDurationInHours"] = options_["retryDurationInHours"]; } } string response = sendPostRequest (data, SMS_URLString); if (responseCode == (int)HttpStatusCode.Created) { var json = serializer.Deserialize <dynamic> (response); dynamic recipients = json ["SMSMessageData"] ["Recipients"]; if(recipients.Length > 0) { return recipients; } throw new AfricasTalkingGatewayException(json ["SMSMessageData"] ["Message"]); } throw new AfricasTalkingGatewayException(response); } public dynamic fetchMessages(int lastReceivedId_) { string url = SMS_URLString + "?username=" + _username + "&lastReceivedId=" + Convert.ToString(lastReceivedId_); string response = sendGetRequest (url); if (responseCode == (int)HttpStatusCode.OK) { dynamic json = serializer.DeserializeObject (response); return json ["SMSMessageData"] ["Messages"]; } throw new AfricasTalkingGatewayException (response); } public dynamic createSubscription(string phoneNumber_, string shortCode_, string keyword_) { if(phoneNumber_.Length == 0 || shortCode_.Length == 0 || keyword_.Length == 0) throw new AfricasTalkingGatewayException("Please supply phone number, short code and keyword"); Hashtable data_ = new Hashtable (); data_ ["username"] = _username; data_ ["phoneNumber"] = phoneNumber_; data_ ["shortCode"] = shortCode_; data_ ["keyword"] = keyword_; string urlString = SUBSCRIPTION_URLString + "/create"; string response = sendPostRequest (data_, urlString); if (responseCode == (int)HttpStatusCode.Created) { dynamic json = serializer.Deserialize<dynamic> (response); return json; } throw new AfricasTalkingGatewayException (response); } public dynamic deleteSubscription(string phoneNumber_, string shortCode_, string keyword_) { if(phoneNumber_.Length == 0 || shortCode_.Length == 0 || keyword_.Length == 0) throw new AfricasTalkingGatewayException("Please supply phone number, short code and keyword"); Hashtable data_ = new Hashtable (); data_ ["username"] = _username; data_ ["phoneNumber"] = phoneNumber_; data_ ["shortCode"] = shortCode_; data_ ["keyword"] = keyword_; string urlString = SUBSCRIPTION_URLString + "/delete"; string response = sendPostRequest (data_, urlString); if (responseCode == (int)HttpStatusCode.Created) { dynamic json = serializer.Deserialize<dynamic> (response); return json; } throw new AfricasTalkingGatewayException (response); } public dynamic call (string from_, string to_) { Hashtable data = new Hashtable (); data ["username"] = _username; data ["from"] = from_; data ["to"] = to_; string urlString = VOICE_URLString + "/call"; string response = sendPostRequest (data, urlString); dynamic json = serializer.Deserialize<dynamic> (response); if ((string)json ["errorMessage"] == "None") { return json["entries"]; } throw new AfricasTalkingGatewayException (json ["errorMessage"]); } public int getNumQueuedCalls(string phoneNumber_, string queueName_ = null) { Hashtable data = new Hashtable (); data ["username"] = _username; data ["phoneNumbers"] = phoneNumber_; if (queueName_ != null) data ["queueName"] = queueName_; string urlString = VOICE_URLString + "/queueStatus"; string response = sendPostRequest (data, urlString); dynamic json = serializer.Deserialize<dynamic> (response); if ((string)json["errorMessage"] == "None") { return json["entries"]; } throw new AfricasTalkingGatewayException (json["errorMessage"]); } public void uploadMediaFile(string url_) { Hashtable data = new Hashtable (); data ["username"] = _username; data ["url"] = url_; string urlString = VOICE_URLString + "/mediaUpload"; string response = sendPostRequest (data, urlString); dynamic json = serializer.Deserialize<dynamic> (response); if((string)json["errorMessage"] != "None") throw new AfricasTalkingGatewayException (json["errorMessage"]); } public dynamic sendAirtime(ArrayList recipients_) { string urlString = AIRTIME_URLString + "/send"; string recipients = new JavaScriptSerializer ().Serialize (recipients_); Hashtable data = new Hashtable (); data ["username"] = _username; data ["recipients"] = recipients; string response = sendPostRequest (data, urlString); if (responseCode == (int)HttpStatusCode.Created) { dynamic json = serializer.Deserialize<dynamic> (response); if (json ["responses"].Count > 0) return json ["responses"]; throw new AfricasTalkingGatewayException (json ["errorMessage"]); } throw new AfricasTalkingGatewayException (response); } public dynamic getUserData() { string urlString = USERDATA_URLString + "?username=" + _username; string response = sendGetRequest (urlString); if (responseCode == (int)HttpStatusCode.OK) { dynamic json = serializer.Deserialize<dynamic> (response); return json ["UserData"]; } throw new AfricasTalkingGatewayException (response); } private string sendPostRequest (Hashtable dataMap_, string urlString_) { try { string dataStr = ""; foreach (string key in dataMap_.Keys) { if (dataStr.Length > 0 ) dataStr += "&"; string value = (string)dataMap_[key]; dataStr += HttpUtility.UrlEncode (key, Encoding.UTF8); dataStr += "=" + HttpUtility.UrlEncode (value, Encoding.UTF8); } byte[] byteArray = Encoding.UTF8.GetBytes (dataStr); System.Net.ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlString_); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; webRequest.Accept = "application/json"; webRequest.Headers.Add ("apiKey", _apiKey); Stream webpageStream = webRequest.GetRequestStream (); webpageStream.Write (byteArray, 0, byteArray.Length); webpageStream.Close (); HttpWebResponse httpResponse = (HttpWebResponse) webRequest.GetResponse (); responseCode = (int)httpResponse.StatusCode; StreamReader webpageReader = new StreamReader (httpResponse.GetResponseStream ()); string response = webpageReader.ReadToEnd(); if(DEBUG) Console.WriteLine("Full response: " + response); return response; } catch (WebException ex) { if(ex.Response == null) throw new AfricasTalkingGatewayException(ex.Message); using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { string response = reader.ReadToEnd (); if (DEBUG) Console.WriteLine ("Full response: " + response); return response; } } catch(AfricasTalkingGatewayException ex) { throw ex; } } private string sendGetRequest (string urlString_) { try{ System.Net.ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlString_); webRequest.Method = "GET"; webRequest.Accept = "application/json"; webRequest.Headers.Add ("apiKey", _apiKey); HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse (); responseCode = (int)httpResponse.StatusCode; StreamReader webpageReader = new StreamReader (httpResponse.GetResponseStream ()); string response = webpageReader.ReadToEnd(); if(DEBUG) Console.WriteLine("Full response: " + response); return response; } catch (WebException ex) { if(ex.Response == null) throw new AfricasTalkingGatewayException(ex.Message); using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { string response = reader.ReadToEnd (); if (DEBUG) Console.WriteLine ("Full response: " + response); return response; } } catch(AfricasTalkingGatewayException ex) { throw ex; } } private Boolean RemoteCertificateValidationCallback (object sender_, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain_, System.Net.Security.SslPolicyErrors errors_) { return true; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WeddingPlanner.CommunicationBus.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.Globalization; using Xunit; namespace System.Globalization.CalendarTests { // GregorianCalendar.IsLeapDay(Int32, Int32, Int32, Int32) public class GregorianCalendarIsLeapDay { private const int c_DAYS_IN_LEAP_YEAR = 366; private const int c_DAYS_IN_COMMON_YEAR = 365; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private static readonly int[] s_daysInMonth365 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static readonly int[] s_daysInMonth366 = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive tests // PosTest1: February 29 in leap year [Fact] public void PosTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetALeapYear(myCalendar); month = 2; day = 29; expectedValue = true; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest2: February 28 in common year [Fact] public void PosTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetACommonYear(myCalendar); month = 2; day = 28; expectedValue = false; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest3: any year, any month, any day [Fact] public void PosTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest4: any day and month in maximum supported year [Fact] public void PosTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = myCalendar.MaxSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } // PosTest5: any day and month in minimum supported year [Fact] public void PosTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; bool expectedValue; bool actualValue; year = myCalendar.MinSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; expectedValue = this.IsLeapYear(year) && 2 == month && 29 == day; actualValue = myCalendar.IsLeapDay(year, month, day, 1); Assert.Equal(expectedValue, actualValue); } #endregion #region Negtive Tests // NegTest1: year is greater than maximum supported value [Fact] public void NegTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; year = myCalendar.MaxSupportedDateTime.Year + 100; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, 1); }); } // NegTest2: year is less than minimum supported value [Fact] public void NegTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; year = myCalendar.MinSupportedDateTime.Year - 100; month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, 1); }); } // NegTest3: era is outside the range supported by the calendar [Fact] public void NegTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; era = 2 + _generator.GetInt32(-55) % (int.MaxValue - 1); Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest4: month is outside the range supported by the calendar [Fact] public void NegTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = -1 * _generator.GetInt32(-55); day = 1; era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest5: month is outside the range supported by the calendar [Fact] public void NegTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12); day = 1; era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } // NegTest6: day is outside the range supported by the calendar [Fact] public void NegTest6() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month, day; int era; year = this.GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; day = -1 * _generator.GetInt32(-55); era = _generator.GetInt32(-55) & 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.IsLeapDay(year, month, day, era); }); } #endregion #region Helper methods for all the tests //Indicate whether the specified year is leap year or not private bool IsLeapYear(int year) { if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3))) { return true; } return false; } //Get a random year beween minmum supported year and maximum supported year of the specified calendar private int GetAYear(Calendar calendar) { int retVal; int maxYear, minYear; maxYear = calendar.MaxSupportedDateTime.Year; minYear = calendar.MinSupportedDateTime.Year; retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear); return retVal; } //Get a leap year of the specified calendar private int GetALeapYear(Calendar calendar) { int retVal; // A leap year is any year divisible by 4 except for centennial years(those ending in 00) // which are only leap years if they are divisible by 400. retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0 retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400 // if retVal was 100, 200, or 300 the above logic will result in 0 if (0 == retVal) { retVal = 400; } return retVal; } //Get a common year of the specified calendar private int GetACommonYear(Calendar calendar) { int retVal; do { retVal = GetAYear(calendar); } while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400); return retVal; } #endregion } }
#region License // /* // See license included in this library folder. // */ #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading; using Sqloogle.Libs.NLog.Internal; namespace Sqloogle.Libs.NLog.Common { /// <summary> /// Helpers for asynchronous operations. /// </summary> public static class AsyncHelpers { /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation"> /// The asynchronous continuation to invoke once all items /// have been iterated. /// </param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; var enumerator = items.GetEnumerator(); invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (!enumerator.MoveNext()) { asyncContinuation(null); return; } action(enumerator.Current, PreventMultipleCalls(invokeNext)); }; invokeNext(null); } /// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; var remaining = repeatCount; invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (remaining-- <= 0) { asyncContinuation(null); return; } action(PreventMultipleCalls(invokeNext)); }; invokeNext(null); } /// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation continuation = ex => { if (ex != null) { // if got exception from from original invocation, don't execute action asyncContinuation(ex); return; } // call the action and continue action(PreventMultipleCalls(asyncContinuation)); }; return continuation; } /// <summary> /// Attaches a timeout to a continuation which will invoke the continuation when the specified /// timeout has elapsed. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">The timeout.</param> /// <returns>Wrapped continuation.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Continuation will be disposed of elsewhere.")] public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout) { return new TimeoutContinuation(asyncContinuation, timeout).Function; } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation"> /// The asynchronous continuation to invoke once all items /// have been iterated. /// </param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel<T>(IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); var items = new List<T>(values); var remaining = items.Count; var exceptions = new List<Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); int r; if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (var item in items) { var itemCopy = item; ThreadPool.QueueUserWorkItem(s => action(itemCopy, PreventMultipleCalls(continuation))); } } /// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(AsynchronousAction action) { var ev = new ManualResetEvent(false); Exception lastException = null; action(PreventMultipleCalls(ex => { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } } /// <summary> /// Wraps the continuation with a guard which will only make sure that the continuation function /// is invoked only once. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Wrapped asynchronous continuation.</returns> public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation) { #if !NETCF2_0 // target is not available on .NET CF 2.0 if (asyncContinuation.Target is SingleCallContinuation) { return asyncContinuation; } #endif return new SingleCallContinuation(asyncContinuation).Function; } /// <summary> /// Gets the combined exception from all exceptions in the list. /// </summary> /// <param name="exceptions">The exceptions.</param> /// <returns>Combined exception or null if no exception was thrown.</returns> public static Exception GetCombinedException(IList<Exception> exceptions) { if (exceptions.Count == 0) { return null; } if (exceptions.Count == 1) { return exceptions[0]; } var sb = new StringBuilder(); var separator = string.Empty; var newline = EnvironmentHelper.NewLine; foreach (var ex in exceptions) { sb.Append(separator); sb.Append(ex); sb.Append(newline); separator = newline; } return new NLogRuntimeException("Got multiple exceptions:\r\n" + sb); } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { return cont => { try { action(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } private static AsynchronousAction<T> ExceptionGuard<T>(AsynchronousAction<T> action) { return (T argument, AsyncContinuation cont) => { try { action(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Hosting { using System.Collections.Generic; using System.Linq; using System.Runtime; using System.Activities.Tracking; // One workflow host should have one manager, and one manager should have one catalog. // One workflow instance should have one container as the instance itself would be // added as one extension to the container as well public class WorkflowInstanceExtensionManager { // using an empty list instead of null simplifies our calculations immensely internal static List<KeyValuePair<Type, WorkflowInstanceExtensionProvider>> EmptyExtensionProviders = new List<KeyValuePair<Type, WorkflowInstanceExtensionProvider>>(0); internal static List<object> EmptySingletonExtensions = new List<object>(0); bool isReadonly; List<object> additionalSingletonExtensions; List<object> allSingletonExtensions; bool hasSingletonTrackingParticipant; bool hasSingletonPersistenceModule; public WorkflowInstanceExtensionManager() { } internal SymbolResolver SymbolResolver { get; private set; } internal List<object> SingletonExtensions { get; private set; } internal List<object> AdditionalSingletonExtensions { get { return this.additionalSingletonExtensions; } } internal List<KeyValuePair<Type, WorkflowInstanceExtensionProvider>> ExtensionProviders { get; private set; } internal bool HasSingletonIWorkflowInstanceExtensions { get; private set; } internal bool HasSingletonTrackingParticipant { get { return this.hasSingletonTrackingParticipant; } } internal bool HasSingletonPersistenceModule { get { return this.hasSingletonPersistenceModule; } } internal bool HasAdditionalSingletonIWorkflowInstanceExtensions { get; private set; } // use this method to add the singleton extension public virtual void Add(object singletonExtension) { if (singletonExtension == null) { throw FxTrace.Exception.ArgumentNull("singletonExtension"); } ThrowIfReadOnly(); if (singletonExtension is SymbolResolver) { if (this.SymbolResolver != null) { throw FxTrace.Exception.Argument("singletonExtension", SR.SymbolResolverAlreadyExists); } this.SymbolResolver = (SymbolResolver)singletonExtension; } else { if (singletonExtension is IWorkflowInstanceExtension) { HasSingletonIWorkflowInstanceExtensions = true; } if (!this.HasSingletonTrackingParticipant && singletonExtension is TrackingParticipant) { this.hasSingletonTrackingParticipant = true; } if (!this.HasSingletonPersistenceModule && singletonExtension is IPersistencePipelineModule) { this.hasSingletonPersistenceModule = true; } } if (this.SingletonExtensions == null) { this.SingletonExtensions = new List<object>(); } this.SingletonExtensions.Add(singletonExtension); } // use this method to add a per-instance extension public virtual void Add<T>(Func<T> extensionCreationFunction) where T : class { if (extensionCreationFunction == null) { throw FxTrace.Exception.ArgumentNull("extensionCreationFunction"); } ThrowIfReadOnly(); if (this.ExtensionProviders == null) { this.ExtensionProviders = new List<KeyValuePair<Type, WorkflowInstanceExtensionProvider>>(); } this.ExtensionProviders.Add(new KeyValuePair<Type, WorkflowInstanceExtensionProvider>(typeof(T), new WorkflowInstanceExtensionProvider<T>(extensionCreationFunction))); } internal List<object> GetAllSingletonExtensions() { return this.allSingletonExtensions; } internal void AddAllExtensionTypes(HashSet<Type> extensionTypes) { Fx.Assert(this.isReadonly, "should be read only at this point"); for (int i = 0; i < this.SingletonExtensions.Count; i++) { extensionTypes.Add(this.SingletonExtensions[i].GetType()); } for (int i = 0; i < this.ExtensionProviders.Count; i++) { extensionTypes.Add(this.ExtensionProviders[i].Key); } } internal static WorkflowInstanceExtensionCollection CreateInstanceExtensions(Activity workflowDefinition, WorkflowInstanceExtensionManager extensionManager) { Fx.Assert(workflowDefinition.IsRuntimeReady, "activity should be ready with extensions after a successful CacheMetadata call"); if (extensionManager != null) { extensionManager.MakeReadOnly(); return new WorkflowInstanceExtensionCollection(workflowDefinition, extensionManager); } else if ((workflowDefinition.DefaultExtensionsCount > 0) || (workflowDefinition.RequiredExtensionTypesCount > 0)) { return new WorkflowInstanceExtensionCollection(workflowDefinition, null); } else { return null; } } internal static void AddExtensionClosure(object newExtension, ref List<object> targetCollection, ref bool addedTrackingParticipant, ref bool addedPersistenceModule) { // see if we need to process "additional" extensions IWorkflowInstanceExtension currentInstanceExtension = newExtension as IWorkflowInstanceExtension; if (currentInstanceExtension == null) { return; // bail early } Queue<IWorkflowInstanceExtension> additionalInstanceExtensions = null; if (targetCollection == null) { targetCollection = new List<object>(); } while (currentInstanceExtension != null) { IEnumerable<object> additionalExtensions = currentInstanceExtension.GetAdditionalExtensions(); if (additionalExtensions != null) { foreach (object additionalExtension in additionalExtensions) { targetCollection.Add(additionalExtension); if (additionalExtension is IWorkflowInstanceExtension) { if (additionalInstanceExtensions == null) { additionalInstanceExtensions = new Queue<IWorkflowInstanceExtension>(); } additionalInstanceExtensions.Enqueue((IWorkflowInstanceExtension)additionalExtension); } if (!addedTrackingParticipant && additionalExtension is TrackingParticipant) { addedTrackingParticipant = true; } if (!addedPersistenceModule && additionalExtension is IPersistencePipelineModule) { addedPersistenceModule = true; } } } if (additionalInstanceExtensions != null && additionalInstanceExtensions.Count > 0) { currentInstanceExtension = additionalInstanceExtensions.Dequeue(); } else { currentInstanceExtension = null; } } } public void MakeReadOnly() { // if any singleton extensions have dependents, calculate them now so that we're only // doing this process once per-host if (!this.isReadonly) { if (this.SingletonExtensions != null) { if (HasSingletonIWorkflowInstanceExtensions) { foreach (IWorkflowInstanceExtension additionalExtensionProvider in this.SingletonExtensions.OfType<IWorkflowInstanceExtension>()) { AddExtensionClosure(additionalExtensionProvider, ref this.additionalSingletonExtensions, ref this.hasSingletonTrackingParticipant, ref this.hasSingletonPersistenceModule); } if (this.AdditionalSingletonExtensions != null) { for (int i = 0; i < this.AdditionalSingletonExtensions.Count; i++) { object extension = this.AdditionalSingletonExtensions[i]; if (extension is IWorkflowInstanceExtension) { HasAdditionalSingletonIWorkflowInstanceExtensions = true; break; } } } } this.allSingletonExtensions = this.SingletonExtensions; if (this.AdditionalSingletonExtensions != null && this.AdditionalSingletonExtensions.Count > 0) { this.allSingletonExtensions = new List<object>(this.SingletonExtensions); this.allSingletonExtensions.AddRange(this.AdditionalSingletonExtensions); } } else { this.SingletonExtensions = EmptySingletonExtensions; this.allSingletonExtensions = EmptySingletonExtensions; } if (this.ExtensionProviders == null) { this.ExtensionProviders = EmptyExtensionProviders; } this.isReadonly = true; } } void ThrowIfReadOnly() { if (this.isReadonly) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ExtensionsCannotBeModified)); } } } }
using System; using System.Collections; using Jovian.Tools.Support; namespace Jovian.Tools.Styles { /// <summary> /// Summary description for Keywords. /// </summary> public class JavaScriptExport : StyleExp { public bool inString1; public bool inString2; public bool inBigComment; public JavaScriptExport() { inString1 = false; inString2 = false; inBigComment = false; } public JavaScriptExport clone() { JavaScriptExport JSE = new JavaScriptExport(); JSE.inString1 = this.inString1; JSE.inString2 = this.inString2; JSE.inBigComment = this.inBigComment; return JSE; } public bool diff(StyleExp e) { JavaScriptExport JSE = e as JavaScriptExport; if(JSE.inString1 != this.inString1) return true; if(JSE.inString2 != this.inString2) return true; if(JSE.inBigComment != this.inBigComment) return true; return false; } } public class JavaScript : StyleEng { public ArrayList L; public JavaScript(){ L = new ArrayList(); L.Add("new"); L.Add("if"); L.Add("function"); L.Add("null"); L.Add("break"); L.Add("return"); L.Add("else"); // L.Add("foreach"); // L.Add("string"); // L.Add("void"); L.Add("while"); L.Add("var"); L.Add("this"); L.Add("for"); L.Add("true"); L.Add("false"); } public int CheckKeyword(rtfLine l, int s, string keyword, int k) { if(k >= keyword.Length) { return keyword.Length; } if(l.charAt(s).v == keyword[k]) { return CheckKeyword(l,s+1,keyword,k+1); } return -1; } public int ProcKeyword(rtfLine l, int s) { rtfChar c = l.charAt(s); c.s = 0; foreach(string x in L) { if(s + x.Length <= l.Length()) { int ck = CheckKeyword(l,s,x,0); if(ck > 0) { bool good = true; if(s + ck < l.Length()) { if(Char.IsLetterOrDigit(l.charAt(s + ck).v)) { good = false; } } if(s > 0) { if(Char.IsLetterOrDigit(l.charAt(s - 1).v)) { good = false; } } if(good) { for(int j = 0; j < ck; j++) l.charAt(s + j).s = 1; return ck; } } } } return 0; } public JavaScriptExport ProcLine(rtfLine l, JavaScriptExport JJ) { JavaScriptExport JSE = JJ.clone(); bool EndComment = false; for(int k = 0; k < l.Length();k++) { rtfChar C = l.charAt(k); if(JSE.inString1) C.s = 3; if(JSE.inString2) C.s = 3; if(JSE.inBigComment) C.s = 2; if(EndComment) { C.s = 2; } else if(!(JSE.inString1 || JSE.inString2 || JSE.inBigComment)) { if(C.v == '"') { C.s = 3; JSE.inString1 = true; } else if(C.v == '\'') { C.s = 3; JSE.inString2 = true; } else if(C.v == '/') { if(k + 1 < l.Length()) { rtfChar CC = l.charAt(k+1); if(CC.v == '*') { C.s = 2; CC.s = 2; JSE.inBigComment = true; k++; } else if(CC.v == '/') { C.s = 2; CC.s = 2; EndComment = true; k++; } } } if(!(JSE.inString1 || JSE.inString2 || JSE.inBigComment || EndComment)) { int dk = ProcKeyword(l,k); if(dk > 0) k += dk - 1; } } else if(JSE.inString1) { if(C.v == '\\') { k++; if(k < l.Length()) l.charAt(k).s = 3; } else if(C.v == '"') { JSE.inString1 = false; } } else if(JSE.inString2) { if(C.v == '\\') { k++; if(k < l.Length()) l.charAt(k).s = 3; } else if(C.v == '\'') { JSE.inString2 = false; } } else if(JSE.inBigComment) { if(C.v == '*') { if(k + 1 < l.Length()) { if(l.charAt(k+1).v == '/') { k++; l.charAt(k).s = 2; JSE.inBigComment = false; } } } } } return JSE; } public StyleExp StyleFirstLine(rtfLine l) { return ProcLine(l,new JavaScriptExport()); } public StyleExp StyleSuccLine(StyleExp prior, rtfLine l) { return ProcLine(l, prior as JavaScriptExport); } } }
// 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 BlendInt161() { var test = new ImmBinaryOpTest__BlendInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmBinaryOpTest__BlendInt161 { private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendInt161 testClass) { var result = Avx2.Blend(_fld1, _fld2, 1); 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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable; static ImmBinaryOpTest__BlendInt161() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmBinaryOpTest__BlendInt161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), 1 ); 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.Blend( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), 1 ); 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.Blend( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), 1 ); 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.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendInt161(); var result = Avx2.Blend(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 1); 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.Blend(test._fld1, test._fld2, 1); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((1 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((i < 8) ? (((1 & (1 << i)) == 0) ? left[i] : right[i]) : (((1 & (1 << (i - 8))) == 0) ? left[i] : right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int16>(Vector256<Int16>.1, Vector256<Int16>): {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; } } } }
using System; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace JovianTools.Support { /// <summary> /// Summary description for rtfFormatting. /// </summary> public class rtfFormatting : System.Windows.Forms.UserControl { private System.Windows.Forms.Button btnXML; private System.Windows.Forms.Button btnTabBraces; private System.Windows.Forms.Button btnExplode; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button btnCollapse; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Button btnTabXML; private System.Windows.Forms.Button btnStyXML; private System.Windows.Forms.Button btnStyJS; private System.Windows.Forms.Button btnExtraNewLines; private System.Windows.Forms.Button btnStySQL; private System.Windows.Forms.Button btnCollapseExtraSpaces; private System.Windows.Forms.Button btnSqlSmash; private System.Windows.Forms.Button btnTrim; private System.Windows.Forms.Button btnStyCSS; private Button btnGrillScript; private JovianEdit _Owner; public rtfFormatting(JovianEdit O) { _Owner = O; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call SyncCmds(); } public void Colorize(Button B) { if(B.Enabled) { B.BackColor = Color.Yellow; } else { B.BackColor = Color.DarkGray; } } public void SyncCmds() { btnCollapse.Enabled = _Owner.Engine is JovianTools.Styles.JavaScript || _Owner.Engine is JovianTools.Styles.CSS|| _Owner.Engine is JovianTools.Styles.GrillScript; btnExplode.Enabled = _Owner.Engine is JovianTools.Styles.JavaScript || _Owner.Engine is JovianTools.Styles.CSS|| _Owner.Engine is JovianTools.Styles.GrillScript; btnTabBraces.Enabled = _Owner.Engine is JovianTools.Styles.JavaScript || _Owner.Engine is JovianTools.Styles.CSS|| _Owner.Engine is JovianTools.Styles.GrillScript; btnXML.Enabled = (_Owner.Engine is JovianTools.Styles.XML); btnSqlSmash.Enabled = _Owner.Engine is JovianTools.Styles.SQL; btnTrim.Enabled = _Owner.Engine is JovianTools.Styles.XML; btnTabXML.Enabled = _Owner.Engine is JovianTools.Styles.XML; //btnGrillScript.Enabled = _Owner.Engine is JovianTools.Styles.GrillScript; Colorize(btnCollapse); Colorize(btnExplode); Colorize(btnTabBraces); Colorize(btnXML); Colorize(btnTabXML); Colorize(btnSqlSmash); Colorize(btnTrim); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnXML = new System.Windows.Forms.Button(); this.btnTabBraces = new System.Windows.Forms.Button(); this.btnExplode = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btnStyCSS = new System.Windows.Forms.Button(); this.btnTrim = new System.Windows.Forms.Button(); this.btnSqlSmash = new System.Windows.Forms.Button(); this.btnCollapseExtraSpaces = new System.Windows.Forms.Button(); this.btnStySQL = new System.Windows.Forms.Button(); this.btnExtraNewLines = new System.Windows.Forms.Button(); this.btnStyJS = new System.Windows.Forms.Button(); this.btnStyXML = new System.Windows.Forms.Button(); this.btnTabXML = new System.Windows.Forms.Button(); this.btnCollapse = new System.Windows.Forms.Button(); this.btnGrillScript = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // btnXML // this.btnXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.btnXML.Location = new System.Drawing.Point(8, 46); this.btnXML.Name = "btnXML"; this.btnXML.Size = new System.Drawing.Size(53, 24); this.btnXML.TabIndex = 0; this.btnXML.Text = "Explode"; this.btnXML.UseVisualStyleBackColor = false; this.btnXML.Click += new System.EventHandler(this.btnXML_Click); // // btnTabBraces // this.btnTabBraces.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.btnTabBraces.Location = new System.Drawing.Point(8, 16); this.btnTabBraces.Name = "btnTabBraces"; this.btnTabBraces.Size = new System.Drawing.Size(78, 24); this.btnTabBraces.TabIndex = 1; this.btnTabBraces.Text = "Tab Braces"; this.btnTabBraces.UseVisualStyleBackColor = false; this.btnTabBraces.Click += new System.EventHandler(this.btnTabBraces_Click); // // btnExplode // this.btnExplode.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.btnExplode.Location = new System.Drawing.Point(92, 16); this.btnExplode.Name = "btnExplode"; this.btnExplode.Size = new System.Drawing.Size(66, 24); this.btnExplode.TabIndex = 2; this.btnExplode.Text = "Explode {}"; this.btnExplode.UseVisualStyleBackColor = false; this.btnExplode.Click += new System.EventHandler(this.btnExplode_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.btnGrillScript); this.groupBox1.Controls.Add(this.btnStyCSS); this.groupBox1.Controls.Add(this.btnTrim); this.groupBox1.Controls.Add(this.btnSqlSmash); this.groupBox1.Controls.Add(this.btnCollapseExtraSpaces); this.groupBox1.Controls.Add(this.btnStySQL); this.groupBox1.Controls.Add(this.btnExtraNewLines); this.groupBox1.Controls.Add(this.btnStyJS); this.groupBox1.Controls.Add(this.btnStyXML); this.groupBox1.Controls.Add(this.btnTabXML); this.groupBox1.Controls.Add(this.btnCollapse); this.groupBox1.Controls.Add(this.btnExplode); this.groupBox1.Controls.Add(this.btnTabBraces); this.groupBox1.Controls.Add(this.btnXML); this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(236, 140); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // // btnStyCSS // this.btnStyCSS.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.btnStyCSS.Location = new System.Drawing.Point(184, 76); this.btnStyCSS.Name = "btnStyCSS"; this.btnStyCSS.Size = new System.Drawing.Size(40, 24); this.btnStyCSS.TabIndex = 12; this.btnStyCSS.Text = "fCSS"; this.btnStyCSS.UseVisualStyleBackColor = false; this.btnStyCSS.Click += new System.EventHandler(this.btnStyCSS_Click); // // btnTrim // this.btnTrim.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.btnTrim.Location = new System.Drawing.Point(111, 46); this.btnTrim.Name = "btnTrim"; this.btnTrim.Size = new System.Drawing.Size(40, 24); this.btnTrim.TabIndex = 11; this.btnTrim.Text = "Trim"; this.btnTrim.UseVisualStyleBackColor = false; this.btnTrim.Click += new System.EventHandler(this.btnTrim_Click); // // btnSqlSmash // this.btnSqlSmash.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.btnSqlSmash.Location = new System.Drawing.Point(157, 46); this.btnSqlSmash.Name = "btnSqlSmash"; this.btnSqlSmash.Size = new System.Drawing.Size(74, 24); this.btnSqlSmash.TabIndex = 10; this.btnSqlSmash.Text = "SQL Smash"; this.btnSqlSmash.UseVisualStyleBackColor = false; this.btnSqlSmash.Click += new System.EventHandler(this.btnSqlSmash_Click); // // btnCollapseExtraSpaces // this.btnCollapseExtraSpaces.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.btnCollapseExtraSpaces.Location = new System.Drawing.Point(54, 106); this.btnCollapseExtraSpaces.Name = "btnCollapseExtraSpaces"; this.btnCollapseExtraSpaces.Size = new System.Drawing.Size(40, 24); this.btnCollapseExtraSpaces.TabIndex = 9; this.btnCollapseExtraSpaces.Text = "\" \""; this.btnCollapseExtraSpaces.UseVisualStyleBackColor = false; this.btnCollapseExtraSpaces.Click += new System.EventHandler(this.btnCollapseExtraSpaces_Click); // // btnStySQL // this.btnStySQL.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.btnStySQL.Location = new System.Drawing.Point(138, 76); this.btnStySQL.Name = "btnStySQL"; this.btnStySQL.Size = new System.Drawing.Size(40, 24); this.btnStySQL.TabIndex = 8; this.btnStySQL.Text = "fSQL"; this.btnStySQL.UseVisualStyleBackColor = false; this.btnStySQL.Click += new System.EventHandler(this.btnStySQL_Click); // // btnExtraNewLines // this.btnExtraNewLines.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.btnExtraNewLines.Location = new System.Drawing.Point(8, 106); this.btnExtraNewLines.Name = "btnExtraNewLines"; this.btnExtraNewLines.Size = new System.Drawing.Size(40, 24); this.btnExtraNewLines.TabIndex = 7; this.btnExtraNewLines.Text = "\\n\\n"; this.btnExtraNewLines.UseVisualStyleBackColor = false; this.btnExtraNewLines.Click += new System.EventHandler(this.btnExtraNewLines_Click); // // btnStyJS // this.btnStyJS.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.btnStyJS.Location = new System.Drawing.Point(54, 76); this.btnStyJS.Name = "btnStyJS"; this.btnStyJS.Size = new System.Drawing.Size(32, 24); this.btnStyJS.TabIndex = 6; this.btnStyJS.Text = "fJS"; this.btnStyJS.UseVisualStyleBackColor = false; this.btnStyJS.Click += new System.EventHandler(this.btnStyJS_Click); // // btnStyXML // this.btnStyXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.btnStyXML.Location = new System.Drawing.Point(8, 76); this.btnStyXML.Name = "btnStyXML"; this.btnStyXML.Size = new System.Drawing.Size(40, 24); this.btnStyXML.TabIndex = 5; this.btnStyXML.Text = "fXML"; this.btnStyXML.UseVisualStyleBackColor = false; this.btnStyXML.Click += new System.EventHandler(this.btnStyXML_Click); // // btnTabXML // this.btnTabXML.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.btnTabXML.Location = new System.Drawing.Point(67, 46); this.btnTabXML.Name = "btnTabXML"; this.btnTabXML.Size = new System.Drawing.Size(38, 24); this.btnTabXML.TabIndex = 4; this.btnTabXML.Text = "Tab"; this.btnTabXML.UseVisualStyleBackColor = false; this.btnTabXML.Click += new System.EventHandler(this.btnTabXML_Click); // // btnCollapse // this.btnCollapse.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.btnCollapse.Location = new System.Drawing.Point(164, 16); this.btnCollapse.Name = "btnCollapse"; this.btnCollapse.Size = new System.Drawing.Size(67, 24); this.btnCollapse.TabIndex = 3; this.btnCollapse.Text = "Collapse {}"; this.btnCollapse.UseVisualStyleBackColor = false; this.btnCollapse.Click += new System.EventHandler(this.btnCollapse_Click); // // btnGrillScript // this.btnGrillScript.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.btnGrillScript.Location = new System.Drawing.Point(94, 76); this.btnGrillScript.Name = "btnGrillScript"; this.btnGrillScript.Size = new System.Drawing.Size(38, 24); this.btnGrillScript.TabIndex = 13; this.btnGrillScript.Text = "fGS"; this.btnGrillScript.UseVisualStyleBackColor = false; this.btnGrillScript.Click += new System.EventHandler(this.btnGrillScript_Click); // // rtfFormatting // this.BackColor = System.Drawing.Color.White; this.Controls.Add(this.groupBox1); this.Cursor = System.Windows.Forms.Cursors.Arrow; this.Name = "rtfFormatting"; this.Size = new System.Drawing.Size(240, 143); this.Load += new System.EventHandler(this.rtfFormatting_Load); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void btnCollapse_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.CollapseBraces()); } private void btnTabBraces_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.TabBraces()); } private void btnXML_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.XMLSmash()); } private void btnExplode_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.ExplodeBraces()); } private void btnTabXML_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.TabXML()); } private void btnStyXML_Click(object sender, System.EventArgs e) { _Owner.Engine = new JovianTools.Styles.XML(); SyncCmds(); } private void btnStyJS_Click(object sender, System.EventArgs e) { _Owner.Engine = new JovianTools.Styles.JavaScript(); SyncCmds(); } private void btnExtraNewLines_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.CollapseExtraNewlines()); } private void btnCollapseExtraSpaces_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.CollapseExtraSpaces()); } private void btnStySQL_Click(object sender, System.EventArgs e) { _Owner.Engine = new JovianTools.Styles.SQL(); SyncCmds(); } private void btnSqlSmash_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.BlueSmash()); } private void groupBox1_Enter(object sender, System.EventArgs e) { } private void btnTrim_Click(object sender, System.EventArgs e) { _Owner.ApplyFormatter(new JovianTools.Formating.XMLPack()); } private void rtfFormatting_Load(object sender, System.EventArgs e) { } private void btnStyCSS_Click(object sender, System.EventArgs e) { _Owner.Engine = new JovianTools.Styles.CSS(); SyncCmds(); } private void btnGrillScript_Click(object sender, EventArgs e) { _Owner.Engine = new JovianTools.Styles.GrillScript(); SyncCmds(); } private void btnClipEmptyLines_Click(object sender, EventArgs e) { } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; using static Interop.Advapi32; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, "."); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { // Performance optimization for the local machine: // First try to OpenProcess by id, if valid handle is returned, the process is definitely running // Otherwise enumerate all processes and compare ids if (!IsRemoteMachine(machineName)) { using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId)) { if (!processHandle.IsInvalid) { return true; } } } return Array.IndexOf(GetProcessIds(machineName), processId) >= 0; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true) : NtProcessInfoHelper.GetProcessInfos(); } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { if (IsRemoteMachine(machineName)) { // remote case: we take the hit of looping through all results ProcessInfo[] processInfos = NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } } else { // local case: do not use performance counter and also attempt to get the matching (by pid) process only ProcessInfo[] processInfos = NtProcessInfoHelper.GetProcessInfos(pid => pid == processId); if (processInfos.Length == 1) { return processInfos[0]; } } return null; } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ProcessModuleCollection GetModules(int processId) { return NtProcessManager.GetModules(processId); } private static bool IsRemoteMachineCore(string machineName) { ReadOnlySpan<char> baseName = machineName.AsSpan(machineName.StartsWith("\\", StringComparison.Ordinal) ? 2 : 0); return !baseName.Equals(".", StringComparison.Ordinal) && !baseName.Equals(Interop.Kernel32.GetComputerName(), StringComparison.OrdinalIgnoreCase); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static unsafe ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID(); if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.Advapi32.TOKEN_PRIVILEGE tp; tp.PrivilegeCount = 1; tp.Privileges.Luid = luid; tp.Privileges.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, &tp, 0, null, null); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. // Assume the process is still running if the error was ERROR_ACCESS_DENIED for better performance if (result != Interop.Errors.ERROR_ACCESS_DENIED && !IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString())); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString())); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static partial class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static readonly Dictionary<string, ValueId> s_valueIds = new Dictionary<string, ValueId>(19) { { "Pool Paged Bytes", ValueId.PoolPagedBytes }, { "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes }, { "Elapsed Time", ValueId.ElapsedTime }, { "Virtual Bytes Peak", ValueId.VirtualBytesPeak }, { "Virtual Bytes", ValueId.VirtualBytes }, { "Private Bytes", ValueId.PrivateBytes }, { "Page File Bytes", ValueId.PageFileBytes }, { "Page File Bytes Peak", ValueId.PageFileBytesPeak }, { "Working Set Peak", ValueId.WorkingSetPeak }, { "Working Set", ValueId.WorkingSet }, { "ID Thread", ValueId.ThreadId }, { "ID Process", ValueId.ProcessId }, { "Priority Base", ValueId.BasePriority }, { "Priority Current", ValueId.CurrentPriority }, { "% User Time", ValueId.UserTime }, { "% Privileged Time", ValueId.PrivilegedTime }, { "Start Address", ValueId.StartAddress }, { "Thread State", ValueId.ThreadState }, { "Thread Wait Reason", ValueId.ThreadWaitReason } }; internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; while (true) { if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ProcessModuleCollection GetModules(int processId) { return GetModules(processId, firstModuleOnly: false); } public static ProcessModule GetFirstModule(int processId) { ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true); return modules.Count == 0 ? null : modules[0]; } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread caused this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return Interop.Kernel32.GetProcessId(processHandle); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, ReadOnlySpan<byte> data) { Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); ref readonly PERF_DATA_BLOCK dataBlock = ref MemoryMarshal.AsRef<PERF_DATA_BLOCK>(data); int typePos = dataBlock.HeaderLength; for (int i = 0; i < dataBlock.NumObjectTypes; i++) { ref readonly PERF_OBJECT_TYPE type = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(typePos)); PERF_COUNTER_DEFINITION[] counters = new PERF_COUNTER_DEFINITION[type.NumCounters]; int counterPos = typePos + type.HeaderLength; for (int j = 0; j < type.NumCounters; j++) { ref readonly PERF_COUNTER_DEFINITION counter = ref MemoryMarshal.AsRef<PERF_COUNTER_DEFINITION>(data.Slice(counterPos)); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); counters[j] = counter; if (type.ObjectNameTitleIndex == processIndex) counters[j].CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counters[j].CounterNameTitlePtr = (int)GetValueId(counterName); counterPos += counter.ByteLength; } int instancePos = typePos + type.DefinitionLength; for (int j = 0; j < type.NumInstances; j++) { ref readonly PERF_INSTANCE_DEFINITION instance = ref MemoryMarshal.AsRef<PERF_INSTANCE_DEFINITION>(data.Slice(instancePos)); ReadOnlySpan<char> instanceName = PERF_INSTANCE_DEFINITION.GetName(in instance, data.Slice(instancePos)); if (instanceName.Equals("_Total", StringComparison.Ordinal)) { // continue } else if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(in type, data.Slice(instancePos + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && !instanceName.Equals("Idle", StringComparison.OrdinalIgnoreCase)) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpful to the user? Should we just ignore? } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. if (instanceName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) instanceName = instanceName.Slice(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) instanceName = instanceName.Slice(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) instanceName = instanceName.Slice(0, 12); } processInfo.ProcessName = instanceName.ToString(); processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(in type, data.Slice(instancePos + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePos += instance.ByteLength; instancePos += MemoryMarshal.AsRef<PERF_COUNTER_BLOCK>(data.Slice(instancePos)).ByteLength; } typePos += type.TotalByteLength; } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = threadInfos[i]; if (processInfos.TryGetValue(threadInfo._processId, out ProcessInfo processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } private static ThreadInfo GetThreadInfo(in PERF_OBJECT_TYPE type, ReadOnlySpan<byte> instanceData, PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, instanceData.Slice(counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } private static ProcessInfo GetProcessInfo(in PERF_OBJECT_TYPE type, ReadOnlySpan<byte> instanceData, PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, instanceData.Slice(counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; } } return processInfo; } private static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } private static long ReadCounterValue(int counterType, ReadOnlySpan<byte> data) { if ((counterType & PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return MemoryMarshal.Read<long>(data); else return (long)MemoryMarshal.Read<int>(data); } private enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } }
//------------------------------------------------------------------------------ // <copyright file="XmlSchema.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { #if SILVERLIGHT public class XmlSchema : XmlSchemaObject { //Empty XmlSchema class to enable backward compatibility of interface method IXmlSerializable.GetSchema() //Add private ctor to prevent constructing of this class XmlSchema() { } } #else using System.IO; using System.Collections; using System.ComponentModel; using System.Xml.Serialization; using System.Threading; using System.Diagnostics; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlRoot("schema", Namespace=XmlSchema.Namespace)] public class XmlSchema : XmlSchemaObject { /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Namespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string Namespace = XmlReservedNs.NsXs; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.InstanceNamespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string InstanceNamespace = XmlReservedNs.NsXsi; XmlSchemaForm attributeFormDefault = XmlSchemaForm.None; XmlSchemaForm elementFormDefault = XmlSchemaForm.None; XmlSchemaDerivationMethod blockDefault = XmlSchemaDerivationMethod.None; XmlSchemaDerivationMethod finalDefault = XmlSchemaDerivationMethod.None; string targetNs; string version; XmlSchemaObjectCollection includes = new XmlSchemaObjectCollection(); XmlSchemaObjectCollection items = new XmlSchemaObjectCollection(); string id; XmlAttribute[] moreAttributes; // compiled info bool isCompiled = false; bool isCompiledBySet = false; bool isPreprocessed = false; bool isRedefined = false; int errorCount = 0; XmlSchemaObjectTable attributes; XmlSchemaObjectTable attributeGroups = new XmlSchemaObjectTable(); XmlSchemaObjectTable elements = new XmlSchemaObjectTable(); XmlSchemaObjectTable types = new XmlSchemaObjectTable(); XmlSchemaObjectTable groups = new XmlSchemaObjectTable(); XmlSchemaObjectTable notations = new XmlSchemaObjectTable(); XmlSchemaObjectTable identityConstraints = new XmlSchemaObjectTable(); static int globalIdCounter = -1; ArrayList importedSchemas; ArrayList importedNamespaces; int schemaId = -1; //Not added to a set Uri baseUri; bool isChameleon; Hashtable ids = new Hashtable(); XmlDocument document; XmlNameTable nameTable; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.XmlSchema"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema() {} /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(reader), validationEventHandler); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(stream), validationEventHandler); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler) { XmlNameTable nameTable = reader.NameTable; Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler); try { parser.Parse(reader, null); } catch(XmlSchemaException e) { if (validationEventHandler != null) { validationEventHandler(null, new ValidationEventArgs(e)); } else { throw e; } return null; } return parser.XmlSchema; } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(Stream stream) { Write(stream, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(Stream stream, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(TextWriter writer) { Write(writer, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(TextWriter writer, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(writer); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(XmlWriter writer) { Write(writer, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager) { XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema)); XmlSerializerNamespaces ns; if (namespaceManager != null) { ns = new XmlSerializerNamespaces(); bool ignoreXS = false; if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs); } if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && namespaceManager.LookupNamespace("xs") == null ) { ns.Add("xs", XmlReservedNs.NsXs); } foreach(string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { ns.Add(prefix, namespaceManager.LookupNamespace(prefix)); } } } else if (this.Namespaces != null && this.Namespaces.Count > 0) { Hashtable serializerNS = this.Namespaces.Namespaces; if (serializerNS["xs"] == null && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); } ns = this.Namespaces; } else { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); if (targetNs != null && targetNs.Length != 0) { ns.Add("tns", targetNs); } } serializer.Serialize(writer, this, ns); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, System.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver(), sInfo, null, validationEventHandler, NameTable, false); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compileq"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false); } #pragma warning disable 618 internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel) { //Need to lock here to prevent multi-threading problems when same schema is added to set and compiled lock (this) { //Preprocessing SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler); prep.XmlResolver = resolver; if (!prep.Execute(this, ns, true, xsc)) { return false; } //Compilation SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler); isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel); this.SetIsCompiled(isCompiled); // return isCompiled; } } #pragma warning restore 618 internal void CompileSchemaInSet(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings) { Debug.Assert(this.isPreprocessed); Compiler setCompiler = new Compiler(nameTable, eventHandler, null, compilationSettings); setCompiler.Prepare(this, true); this.isCompiledBySet = setCompiler.Compile(); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeFormDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("attributeFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm AttributeFormDefault { get { return attributeFormDefault; } set { attributeFormDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.BlockDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("blockDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod BlockDefault { get { return blockDefault; } set { blockDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.FinalDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("finalDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod FinalDefault { get { return finalDefault; } set { finalDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.ElementFormDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("elementFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm ElementFormDefault { get { return elementFormDefault; } set { elementFormDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.TargetNamespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("targetNamespace", DataType="anyURI")] public string TargetNamespace { get { return targetNs; } set { targetNs = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Version"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("version", DataType="token")] public string Version { get { return version; } set { version = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Includes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("include", typeof(XmlSchemaInclude)), XmlElement("import", typeof(XmlSchemaImport)), XmlElement("redefine", typeof(XmlSchemaRedefine))] public XmlSchemaObjectCollection Includes { get { return includes; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Items"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("annotation", typeof(XmlSchemaAnnotation)), XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup)), XmlElement("complexType", typeof(XmlSchemaComplexType)), XmlElement("simpleType", typeof(XmlSchemaSimpleType)), XmlElement("element", typeof(XmlSchemaElement)), XmlElement("group", typeof(XmlSchemaGroup)), XmlElement("notation", typeof(XmlSchemaNotation))] public XmlSchemaObjectCollection Items { get { return items; } } // Compiled info /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.IsCompiled"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public bool IsCompiled { get { return isCompiled || isCompiledBySet ; } } [XmlIgnore] internal bool IsCompiledBySet { get { return isCompiledBySet; } set { isCompiledBySet = value; } } [XmlIgnore] internal bool IsPreprocessed { get { return isPreprocessed; } set { isPreprocessed = value; } } [XmlIgnore] internal bool IsRedefined { get { return isRedefined; } set { isRedefined = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Attributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Attributes { get { if (attributes == null) { attributes = new XmlSchemaObjectTable(); } return attributes; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeGroups"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable AttributeGroups { get { if (attributeGroups == null) { attributeGroups = new XmlSchemaObjectTable(); } return attributeGroups; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.SchemaTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable SchemaTypes { get { if (types == null) { types = new XmlSchemaObjectTable(); } return types; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Elements"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Elements { get { if (elements == null) { elements = new XmlSchemaObjectTable(); } return elements; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Id"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("id", DataType="ID")] public string Id { get { return id; } set { id = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.UnhandledAttributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAnyAttribute] public XmlAttribute[] UnhandledAttributes { get { return moreAttributes; } set { moreAttributes = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Groups"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Groups { get { return groups; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Notations"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Notations { get { return notations; } } [XmlIgnore] internal XmlSchemaObjectTable IdentityConstraints { get { return identityConstraints; } } [XmlIgnore] internal Uri BaseUri { get { return baseUri; } set { baseUri = value; } } [XmlIgnore] // Please be careful with this property. Since it lazy initialized and its value depends on a global state // if it gets called on multiple schemas in a different order the schemas will end up with different IDs // Unfortunately the IDs are used to sort the schemas in the schema set and thus changing the IDs might change // the order which would be a breaking change!! // Simply put if you are planning to add or remove a call to this getter you need to be extra carefull // or better don't do it at all. internal int SchemaId { get { if (schemaId == -1) { schemaId = Interlocked.Increment(ref globalIdCounter); } return schemaId; } } [XmlIgnore] internal bool IsChameleon { get { return isChameleon; } set { isChameleon = value; } } [XmlIgnore] internal Hashtable Ids { get { return ids; } } [XmlIgnore] internal XmlDocument Document { get { if (document == null) document = new XmlDocument(); return document; } } [XmlIgnore] internal int ErrorCount { get { return errorCount; } set { errorCount = value; } } internal new XmlSchema Clone() { XmlSchema that = new XmlSchema(); that.attributeFormDefault = this.attributeFormDefault; that.elementFormDefault = this.elementFormDefault; that.blockDefault = this.blockDefault; that.finalDefault = this.finalDefault; that.targetNs = this.targetNs; that.version = this.version; that.includes = this.includes; that.Namespaces = this.Namespaces; that.items = this.items; that.BaseUri = this.BaseUri; SchemaCollectionCompiler.Cleanup(that); return that; } internal XmlSchema DeepClone() { XmlSchema that = new XmlSchema(); that.attributeFormDefault = this.attributeFormDefault; that.elementFormDefault = this.elementFormDefault; that.blockDefault = this.blockDefault; that.finalDefault = this.finalDefault; that.targetNs = this.targetNs; that.version = this.version; that.isPreprocessed = this.isPreprocessed; //that.IsProcessing = this.IsProcessing; //Not sure if this is needed //Clone its Items for (int i = 0; i < this.items.Count; ++i) { XmlSchemaObject newItem; XmlSchemaComplexType complexType; XmlSchemaElement element; XmlSchemaGroup group; if ((complexType = items[i] as XmlSchemaComplexType) != null) { newItem = complexType.Clone(this); } else if ((element = items[i] as XmlSchemaElement) != null) { newItem = element.Clone(this); } else if ((group = items[i] as XmlSchemaGroup) != null) { newItem = group.Clone(this); } else { newItem = items[i].Clone(); } that.Items.Add(newItem); } //Clone Includes for (int i = 0; i < this.includes.Count; ++i) { XmlSchemaExternal newInclude = (XmlSchemaExternal)this.includes[i].Clone(); that.Includes.Add(newInclude); } that.Namespaces = this.Namespaces; //that.includes = this.includes; //Need to verify this is OK for redefines that.BaseUri = this.BaseUri; return that; } [XmlIgnore] internal override string IdAttribute { get { return Id; } set { Id = value; } } internal void SetIsCompiled(bool isCompiled) { this.isCompiled = isCompiled; } internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes) { this.moreAttributes = moreAttributes; } internal override void AddAnnotation(XmlSchemaAnnotation annotation) { items.Add(annotation); } internal XmlNameTable NameTable { get { if (nameTable == null) nameTable = new System.Xml.NameTable(); return nameTable; } } internal ArrayList ImportedSchemas { get { if (importedSchemas == null) { importedSchemas = new ArrayList(); } return importedSchemas; } } internal ArrayList ImportedNamespaces { get { if (importedNamespaces == null) { importedNamespaces = new ArrayList(); } return importedNamespaces; } } internal void GetExternalSchemasList(IList extList, XmlSchema schema) { Debug.Assert(extList != null && schema != null); if (extList.Contains(schema)) { return; } extList.Add(schema); for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i]; if (ext.Schema != null) { GetExternalSchemasList(extList, ext.Schema); } } } #if TRUST_COMPILE_STATE internal void AddCompiledInfo(SchemaInfo schemaInfo) { XmlQualifiedName itemName; foreach (XmlSchemaElement element in elements.Values) { itemName = element.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.ElementDecls.Add(itemName, element.ElementDecl); } } foreach (XmlSchemaAttribute attribute in attributes.Values) { itemName = attribute.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef); } } foreach (XmlSchemaType type in types.Values) { itemName = type.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; XmlSchemaComplexType complexType = type as XmlSchemaComplexType; if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) { schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl); } } foreach (XmlSchemaNotation notation in notations.Values) { itemName = notation.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; SchemaNotation no = new SchemaNotation(itemName); no.SystemLiteral = notation.System; no.Pubid = notation.Public; if (schemaInfo.Notations[itemName.Name] == null) { schemaInfo.Notations.Add(itemName.Name, no); } } } #endif//TRUST_COMPILE_STATE } #endif//!SILVERLIGHT }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 Service Stack LLC. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Linq; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { public static class DeserializeDictionary<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); const int KeyIndex = 0; const int ValueIndex = 1; public static ParseStringDelegate GetParseMethod(Type type) { var mapInterface = type.GetTypeWithGenericInterfaceOf(typeof(IDictionary<,>)); if (mapInterface == null) { var fn = PclExport.Instance.GetDictionaryParseMethod<TSerializer>(type); if (fn != null) return fn; if (type == typeof(IDictionary)) { return GetParseMethod(typeof(Dictionary<object, object>)); } if (typeof(IDictionary).IsAssignableFromType(type)) { return s => ParseIDictionary(s, type); } throw new ArgumentException(string.Format("Type {0} is not of type IDictionary<,>", type.FullName)); } //optimized access for regularly used types if (type == typeof(Dictionary<string, string>)) { return ParseStringDictionary; } if (type == typeof(JsonObject)) { return ParseJsonObject; } var dictionaryArgs = mapInterface.GenericTypeArguments(); var keyTypeParseMethod = Serializer.GetParseFn(dictionaryArgs[KeyIndex]); if (keyTypeParseMethod == null) return null; var valueTypeParseMethod = Serializer.GetParseFn(dictionaryArgs[ValueIndex]); if (valueTypeParseMethod == null) return null; var createMapType = type.HasAnyTypeDefinitionsOf(typeof(Dictionary<,>), typeof(IDictionary<,>)) ? null : type; return value => ParseDictionaryType(value, createMapType, dictionaryArgs, keyTypeParseMethod, valueTypeParseMethod); } public static JsonObject ParseJsonObject(string value) { var index = VerifyAndGetStartIndex(value, typeof(JsonObject)); var result = new JsonObject(); if (JsonTypeSerializer.IsEmptyMap(value, index)) return result; var valueLength = value.Length; while (index < valueLength) { var keyValue = Serializer.EatMapKey(value, ref index); Serializer.EatMapKeySeperator(value, ref index); var elementValue = Serializer.EatValue(value, ref index); if (keyValue == null) continue; var mapKey = keyValue; var mapValue = elementValue; result[mapKey] = mapValue; Serializer.EatItemSeperatorOrMapEndChar(value, ref index); } return result; } public static Dictionary<string, string> ParseStringDictionary(string value) { var index = VerifyAndGetStartIndex(value, typeof(Dictionary<string, string>)); var result = new Dictionary<string, string>(); if (JsonTypeSerializer.IsEmptyMap(value, index)) return result; var valueLength = value.Length; while (index < valueLength) { var keyValue = Serializer.EatMapKey(value, ref index); Serializer.EatMapKeySeperator(value, ref index); var elementValue = Serializer.EatValue(value, ref index); if (keyValue == null) continue; var mapKey = Serializer.UnescapeString(keyValue); var mapValue = Serializer.UnescapeString(elementValue); result[mapKey] = mapValue; Serializer.EatItemSeperatorOrMapEndChar(value, ref index); } return result; } public static IDictionary ParseIDictionary(string value, Type dictType) { if (value == null) return null; var index = VerifyAndGetStartIndex(value, dictType); var valueParseMethod = Serializer.GetParseFn(typeof(object)); if (valueParseMethod == null) return null; var to = (IDictionary)dictType.CreateInstance(); if (JsonTypeSerializer.IsEmptyMap(value, index)) return to; var valueLength = value.Length; while (index < valueLength) { var keyValue = Serializer.EatMapKey(value, ref index); Serializer.EatMapKeySeperator(value, ref index); var elementStartIndex = index; var elementValue = Serializer.EatTypeValue(value, ref index); if (keyValue == null) continue; var mapKey = valueParseMethod(keyValue); if (elementStartIndex < valueLength) { Serializer.EatWhitespace(value, ref elementStartIndex); to[mapKey] = DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[elementStartIndex]); } else { to[mapKey] = valueParseMethod(elementValue); } Serializer.EatItemSeperatorOrMapEndChar(value, ref index); } return to; } public static IDictionary<TKey, TValue> ParseDictionary<TKey, TValue>( string value, Type createMapType, ParseStringDelegate parseKeyFn, ParseStringDelegate parseValueFn) { if (value == null) return null; var tryToParseItemsAsDictionaries = JsConfig.ConvertObjectTypesIntoStringDictionary && typeof(TValue) == typeof(object); var tryToParseItemsAsPrimitiveTypes = JsConfig.TryToParsePrimitiveTypeValues && typeof(TValue) == typeof(object); var index = VerifyAndGetStartIndex(value, createMapType); var to = (createMapType == null) ? new Dictionary<TKey, TValue>() : (IDictionary<TKey, TValue>)createMapType.CreateInstance(); if (JsonTypeSerializer.IsEmptyMap(value, index)) return to; var valueLength = value.Length; while (index < valueLength) { var keyValue = Serializer.EatMapKey(value, ref index); Serializer.EatMapKeySeperator(value, ref index); var elementStartIndex = index; var elementValue = Serializer.EatTypeValue(value, ref index); if (keyValue == null) continue; TKey mapKey = (TKey)parseKeyFn(keyValue); if (tryToParseItemsAsDictionaries) { Serializer.EatWhitespace(value, ref elementStartIndex); if (elementStartIndex < valueLength && value[elementStartIndex] == JsWriter.MapStartChar) { var tmpMap = ParseDictionary<TKey, TValue>(elementValue, createMapType, parseKeyFn, parseValueFn); if (tmpMap != null && tmpMap.Count > 0) { to[mapKey] = (TValue)tmpMap; } } else if (elementStartIndex < valueLength && value[elementStartIndex] == JsWriter.ListStartChar) { to[mapKey] = (TValue)DeserializeList<List<object>, TSerializer>.Parse(elementValue); } else { to[mapKey] = (TValue)(tryToParseItemsAsPrimitiveTypes && elementStartIndex < valueLength ? DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[elementStartIndex]) : parseValueFn(elementValue)); } } else { if (tryToParseItemsAsPrimitiveTypes && elementStartIndex < valueLength) { Serializer.EatWhitespace(value, ref elementStartIndex); to[mapKey] = (TValue)DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[elementStartIndex]); } else { to[mapKey] = (TValue)parseValueFn(elementValue); } } Serializer.EatItemSeperatorOrMapEndChar(value, ref index); } return to; } private static int VerifyAndGetStartIndex(string value, Type createMapType) { var index = 0; if (!Serializer.EatMapStartChar(value, ref index)) { //Don't throw ex because some KeyValueDataContractDeserializer don't have '{}' Tracer.Instance.WriteDebug("WARN: Map definitions should start with a '{0}', expecting serialized type '{1}', got string starting with: {2}", JsWriter.MapStartChar, createMapType != null ? createMapType.Name : "Dictionary<,>", value.Substring(0, value.Length < 50 ? value.Length : 50)); } return index; } private static Dictionary<string, ParseDictionaryDelegate> ParseDelegateCache = new Dictionary<string, ParseDictionaryDelegate>(); private delegate object ParseDictionaryDelegate(string value, Type createMapType, ParseStringDelegate keyParseFn, ParseStringDelegate valueParseFn); public static object ParseDictionaryType(string value, Type createMapType, Type[] argTypes, ParseStringDelegate keyParseFn, ParseStringDelegate valueParseFn) { ParseDictionaryDelegate parseDelegate; var key = GetTypesKey(argTypes); if (ParseDelegateCache.TryGetValue(key, out parseDelegate)) return parseDelegate(value, createMapType, keyParseFn, valueParseFn); var mi = typeof(DeserializeDictionary<TSerializer>).GetStaticMethod("ParseDictionary"); var genericMi = mi.MakeGenericMethod(argTypes); parseDelegate = (ParseDictionaryDelegate)genericMi.MakeDelegate(typeof(ParseDictionaryDelegate)); Dictionary<string, ParseDictionaryDelegate> snapshot, newCache; do { snapshot = ParseDelegateCache; newCache = new Dictionary<string, ParseDictionaryDelegate>(ParseDelegateCache); newCache[key] = parseDelegate; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot)); return parseDelegate(value, createMapType, keyParseFn, valueParseFn); } private static string GetTypesKey(params Type[] types) { var sb = new StringBuilder(256); foreach (var type in types) { if (sb.Length > 0) sb.Append(">"); sb.Append(type.FullName); } return sb.ToString(); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using System.Text; using Encog.Engine.Network.Activation; using Encog.MathUtil.Matrices; using Encog.Util.CSV; namespace Encog.Persist { /// <summary> /// Used to write an Encog EG/EGA file. EG files are used to hold Encog objects. /// EGA files are used to hold Encog Analyst scripts. /// </summary> /// public class EncogWriteHelper { /// <summary> /// The current large array that we are on. /// </summary> private int _largeArrayNumber; /// <summary> /// A quote char. /// </summary> /// public const char QUOTE = '\"'; /// <summary> /// A comma char. /// </summary> /// public const char COMMA = ','; /// <summary> /// The current line. /// </summary> /// private readonly StringBuilder line; /// <summary> /// The file to write to. /// </summary> /// private readonly StreamWriter xout; /// <summary> /// The current section. /// </summary> /// private String currentSection; /// <summary> /// Construct the object. /// </summary> /// /// <param name="stream">The stream to write to.</param> public EncogWriteHelper(Stream stream) { line = new StringBuilder(); xout = new StreamWriter(stream); } /// <value>The current section.</value> public String CurrentSection { get { return currentSection; } } /// <summary> /// Add a boolean value as a column. /// </summary> /// /// <param name="b">The boolean value.</param> public void AddColumn(bool b) { if (line.Length > 0) { line.Append(COMMA); } line.Append((b) ? 1 : 0); } /// <summary> /// Add a column as a double. /// </summary> /// /// <param name="d">The double to add.</param> public void AddColumn(double d) { if (line.Length > 0) { line.Append(COMMA); } line.Append(CSVFormat.English.Format(d, EncogFramework.DefaultPrecision)); } /// <summary> /// Add a column as a long. /// </summary> /// /// <param name="v">The long to add.</param> public void AddColumn(long v) { if (line.Length > 0) { line.Append(COMMA); } line.Append(v); } /// <summary> /// Add a column as an integer. /// </summary> /// /// <param name="i">The integer to add.</param> public void AddColumn(int i) { if (line.Length > 0) { line.Append(COMMA); } line.Append(i); } /// <summary> /// Add a column as a string. /// </summary> /// /// <param name="str">The string to add.</param> public void AddColumn(String str) { if (line.Length > 0) { line.Append(COMMA); } line.Append(QUOTE); line.Append(str); line.Append(QUOTE); } /// <summary> /// Add a list of string columns. /// </summary> /// /// <param name="cols">The columns to add.</param> public void AddColumns(IList<String> cols) { foreach (String str in cols) { AddColumn(str); } } /// <summary> /// Add a line. /// </summary> /// /// <param name="l">The line to add.</param> public void AddLine(String l) { if (line.Length > 0) { WriteLine(); } xout.WriteLine(l); } /// <summary> /// Add the specified properties. /// </summary> /// /// <param name="properties">The properties.</param> public void AddProperties(IDictionary<String, String> properties) { foreach (String key in properties.Keys) { String value_ren = properties[key]; WriteProperty(key, value_ren); } } /// <summary> /// Add a new section. /// </summary> /// /// <param name="str">The section to add.</param> public void AddSection(String str) { currentSection = str; xout.WriteLine("[" + str + "]"); } /// <summary> /// Add a new subsection. /// </summary> /// /// <param name="str">The subsection.</param> public void AddSubSection(String str) { xout.WriteLine("[" + currentSection + ":" + str + "]"); _largeArrayNumber = 0; } /// <summary> /// Flush the file. /// </summary> /// public void Flush() { xout.Flush(); } /// <summary> /// Write the specified string. /// </summary> /// /// <param name="str">The string to write.</param> public void Write(String str) { xout.Write(str); } /// <summary> /// Write the line. /// </summary> /// public void WriteLine() { xout.WriteLine(line.ToString()); line.Length = 0; } /// <summary> /// Write a property as an activation function. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="act">The activation function.</param> public void WriteProperty(String name, IActivationFunction act) { var result = new StringBuilder(); result.Append(act.GetType().Name); for (int i = 0; i < act.Params.Length; i++) { result.Append('|'); result.Append(CSVFormat.EgFormat.Format(act.Params[i], EncogFramework.DefaultPrecision)); } WriteProperty(name, result.ToString()); } /// <summary> /// Write the property as a boolean. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="value_ren">The boolean value.</param> public void WriteProperty(String name, bool value_ren) { xout.WriteLine(name + "=" + ((value_ren) ? 't' : 'f')); } /// <summary> /// Write a property as a CSV format. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="csvFormat">The format.</param> public void WriteProperty(String name, CSVFormat csvFormat) { String fmt; if ((csvFormat == CSVFormat.English) || (csvFormat == CSVFormat.English) || (csvFormat == CSVFormat.DecimalPoint)) { fmt = "decpnt"; } else if (csvFormat == CSVFormat.DecimalComma) { fmt = "deccomma"; } else { fmt = "decpnt"; } xout.WriteLine(name + "=" + fmt); } /// <summary> /// Write the property as a double. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="value_ren">The value.</param> public void WriteProperty(String name, double value_ren) { xout.WriteLine(name + "=" + CSVFormat.EgFormat.Format(value_ren, EncogFramework.DefaultPrecision)); } /// <summary> /// Write the property as a long. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="v">The value.</param> public void WriteProperty(String name, long v) { xout.WriteLine(name + "=" + v); } /// <summary> /// Write the property as a double array. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="d">The double value.</param> public void WriteProperty(String name, double[] d) { if (d.Length < 2048) { var result = new StringBuilder(); NumberList.ToList(CSVFormat.EgFormat, result, d); WriteProperty(name, result.ToString()); } else { xout.Write(name); xout.Write("=##"); xout.WriteLine(_largeArrayNumber++); xout.Write("##double#"); xout.WriteLine(d.Length); int index = 0; while (index < d.Length) { bool first = true; for (int i = 0; (i < 2048) && (index < d.Length); i++) { if (!first) { xout.Write(","); } else { xout.Write(" "); } xout.Write(CSVFormat.EgFormat.Format(d[index], EncogFramework.DefaultPrecision)); index++; first = false; } xout.WriteLine(); } xout.WriteLine("##end"); } } /// <summary> /// Write a property as an int value. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="value_ren">The int value.</param> public void WriteProperty(String name, int value_ren) { xout.WriteLine(name + "=" + value_ren); } /// <summary> /// Write a property as an int array. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="array">The array.</param> public void WriteProperty(String name, int[] array) { var result = new StringBuilder(); NumberList.ToListInt(CSVFormat.EgFormat, result, array); WriteProperty(name, result.ToString()); } /// <summary> /// Write a matrix as a property. /// </summary> /// /// <param name="name">The property name.</param> /// <param name="matrix">The matrix.</param> public void WriteProperty(String name, Matrix matrix) { var result = new StringBuilder(); result.Append(matrix.Rows); result.Append(','); result.Append(matrix.Cols); for (int row = 0; row < matrix.Rows; row++) { for (int col = 0; col < matrix.Cols; col++) { result.Append(','); result.Append(CSVFormat.EgFormat.Format(matrix[row, col], EncogFramework.DefaultPrecision)); } } WriteProperty(name, result.ToString()); } /// <summary> /// Write the property a s string. /// </summary> /// /// <param name="name">The name of the property.</param> /// <param name="value_ren">The value.</param> public void WriteProperty(String name, String value_ren) { xout.WriteLine(name + "=" + value_ren); } private String MakeActivationFunctionString(IActivationFunction act) { StringBuilder result = new StringBuilder(); result.Append(act.GetType().Name); for (int i = 0; i < act.Params.Length; i++) { result.Append('|'); result.Append(CSVFormat.EgFormat.Format(act.Params[i], EncogFramework.DefaultPrecision)); } return result.ToString(); } public void AddColumn(IActivationFunction act) { AddColumn(MakeActivationFunctionString(act)); } } }
#define __USE_Dynamsoft__ using System; using System.IO; using System.Net; using System.Reflection; using System.Text; using CodePlex.TfsLibrary; using SvnBridge.Handlers; using SvnBridge.Handlers.Renderers; using SvnBridge.Infrastructure; using SvnBridge.Infrastructure.Statistics; using SvnBridge.Interfaces; using SvnBridge.SourceControl; using System.Web; using SvnBridge.RequestHandlers.SAWSHandlers; namespace SvnBridge.Net { public class HttpContextDispatcher { protected readonly IPathParser parser; protected readonly ActionTrackingViaPerfCounter actionTracking; public HttpContextDispatcher(IPathParser parser, ActionTrackingViaPerfCounter actionTracking) { this.parser = parser; this.actionTracking = actionTracking; } public virtual RequestHandlerBase GetHandler(string httpMethod) { switch (httpMethod.ToLowerInvariant()) { #if __USE_Dynamsoft__ case "lock": return new SAWSLockHandler(); case "unlock": return new SAWSUnlockHandler(); #endif case "checkout": #if __USE_Dynamsoft__ return new SAWSCheckOutHandler(); #else return new CheckOutHandler(); #endif case "copy": #if __USE_Dynamsoft__ return new SAWSCopyHandler(); #else return new CopyHandler(); #endif case "delete": #if __USE_Dynamsoft__ return new SAWSDeleteHandler(); #else return new DeleteHandler(); #endif case "merge": #if __USE_Dynamsoft__ return new SAWSMergeHandler(); #else return new MergeHandler(); #endif case "mkactivity": #if __USE_Dynamsoft__ return new SAWSMkActivityHandler(); #else return new MkActivityHandler(); #endif case "mkcol": #if __USE_Dynamsoft__ return new SAWSMkColHandler(); #else return new MkColHandler(); #endif case "options": #if __USE_Dynamsoft__ return new SAWSOptionsHandler(); #else return new OptionsHandler(); #endif case "propfind": #if __USE_Dynamsoft__ return new SAWSPropFindHandler(); #else return new PropFindHandler(); #endif case "proppatch": #if __USE_Dynamsoft__ return new SAWSPropPatchHandler(); #else return new PropPatchHandler(); #endif case "put": #if __USE_Dynamsoft__ return new SAWSPutHandler(); #else return new PutHandler(); #endif case "report": #if __USE_Dynamsoft__ return new SAWSReportHandler(); #else return new ReportHandler(); #endif case "get": #if __USE_Dynamsoft__ return new SAWSGetHandler(); #else return new GetHandler(); #endif default: return null; } } public void Dispatch(IHttpContext connection) { RequestHandlerBase handler = null; try { IHttpRequest request = connection.Request; if ("/!stats/request".Equals(request.LocalPath, StringComparison.InvariantCultureIgnoreCase)) { new StatsRenderer(Container.Resolve<ActionTrackingViaPerfCounter>()).Render(connection); return; } NetworkCredential credential = GetCredential(connection); string tfsUrl = parser.GetServerUrl(request, credential); if (string.IsNullOrEmpty(tfsUrl)) { SendFileNotFoundResponse(connection); return; } if (credential != null && (tfsUrl.ToLowerInvariant().EndsWith("codeplex.com") || tfsUrl.ToLowerInvariant().Contains("tfs.codeplex.com"))) { string username = credential.UserName; string domain = credential.Domain; if (!username.ToLowerInvariant().EndsWith("_cp")) { username += "_cp"; } if (domain == "") { domain = "snd"; } credential = new NetworkCredential(username, credential.Password, domain); } RequestCache.Items["serverUrl"] = tfsUrl; RequestCache.Items["projectName"] = parser.GetProjectName(request); RequestCache.Items["credentials"] = credential; handler = GetHandler(connection.Request.HttpMethod); if (handler == null) { actionTracking.Error(); SendUnsupportedMethodResponse(connection); return; } try { actionTracking.Request(handler); handler.Handle(connection, parser, credential); } catch (TargetInvocationException e) { ExceptionHelper.PreserveStackTrace(e.InnerException); throw e.InnerException; } } catch (WebException ex) { actionTracking.Error(); HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { SendUnauthorizedResponse(connection); } else { throw; } } catch (NetworkAccessDeniedException) { SendUnauthorizedResponse(connection); } catch (IOException) { // Error caused by client cancelling operation under IIS 6 if (Configuration.LogCancelErrors) throw; } catch (HttpException ex) { // Check if error caused by client cancelling operation under IIS 7 if (!ex.Message.StartsWith("An error occurred while communicating with the remote host.") && !ex.Message.StartsWith("The remote host closed the connection.")) throw; if (Configuration.LogCancelErrors) throw; } finally { if (handler != null) handler.Cancel(); } } private static NetworkCredential GetCredential(IHttpContext context) { string authorizationHeader = context.Request.Headers["Authorization"]; if (!string.IsNullOrEmpty(authorizationHeader)) { if (authorizationHeader.StartsWith("Digest")) { return (NetworkCredential)CredentialCache.DefaultCredentials; } else if (authorizationHeader.StartsWith("Basic")) { string encodedCredential = authorizationHeader.Substring(authorizationHeader.IndexOf(' ') + 1); string credential = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredential)); string[] credentialParts = credential.Split(':'); string username = credentialParts[0]; string password = credentialParts[1]; if (username.IndexOf('\\') >= 0) { string domain = username.Substring(0, username.IndexOf('\\')); username = username.Substring(username.IndexOf('\\') + 1); return new NetworkCredential(username, password, domain); } return new NetworkCredential(username, password); } else { throw new Exception("Unrecognized authorization header: " + authorizationHeader.StartsWith("Basic")); } } return CredentialsHelper.NullCredentials; } private static void SendUnauthorizedResponse(IHttpContext connection) { IHttpRequest request = connection.Request; IHttpResponse response = connection.Response; response.ClearHeaders(); response.StatusCode = (int)HttpStatusCode.Unauthorized; response.ContentType = "text/html; charset=iso-8859-1"; response.AppendHeader("WWW-Authenticate", "Basic realm=\"Subversion Repository\""); string content = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>401 Authorization Required</title>\n" + "</head><body>\n" + "<h1>Authorization Required</h1>\n" + "<p>This server could not verify that you\n" + "are authorized to access the document\n" + "requested. Either you supplied the wrong\n" + "credentials (e.g., bad password), or your\n" + "browser doesn't understand how to supply\n" + "the credentials required.</p>\n" + "<hr>\n" + "<address>Apache" + request.Url.Host + " Port " + request.Url.Port + "</address>\n" + "</body></html>\n"; byte[] buffer = Encoding.UTF8.GetBytes(content); response.OutputStream.Write(buffer, 0, buffer.Length); } private static void SendUnsupportedMethodResponse(IHttpContext connection) { IHttpResponse response = connection.Response; response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; response.ContentType = "text/html"; response.AppendHeader("Allow", "PROPFIND, REPORT, OPTIONS, MKACTIVITY, CHECKOUT, PROPPATCH, PUT, MERGE, DELETE, MKCOL"); string content = @" <html> <head> <title>405 Method Not Allowed</title> </head> <body> <h1>The requested method is not supported.</h1> </body> </html>"; byte[] buffer = Encoding.UTF8.GetBytes(content); response.OutputStream.Write(buffer, 0, buffer.Length); } protected void SendFileNotFoundResponse(IHttpContext connection) { IHttpResponse response = connection.Response; response.StatusCode = (int)HttpStatusCode.NotFound; response.ContentType = "text/html; charset=iso-8859-1"; string content = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>404 Not Found</title>\n" + "</head><body>\n" + "<h1>Not Found</h1>\n" + "<hr>\n" + "</body></html>\n"; byte[] buffer = Encoding.UTF8.GetBytes(content); response.OutputStream.Write(buffer, 0, buffer.Length); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Braintree; using System.Xml; namespace Braintree.Tests { [TestFixture] public class ValidationErrorsTest { [Test] public void OnField_WithValidationError() { ValidationErrors errors = new ValidationErrors(); errors.AddError("country_name", new ValidationError("country_name", "91803", "invalid country")); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.OnField("country_name")[0].Code); Assert.AreEqual("invalid country", errors.OnField("country_name")[0].Message); } [Test] public void OnField_WorksWithAllCommonCasing() { ValidationError fieldError = new ValidationError("", "1", ""); ValidationErrors errors = new ValidationErrors(); errors.AddError("country_name", fieldError); Assert.AreEqual(fieldError, errors.OnField("country_name")[0]); Assert.AreEqual(fieldError, errors.OnField("country-name")[0]); Assert.AreEqual(fieldError, errors.OnField("countryName")[0]); Assert.AreEqual(fieldError, errors.OnField("CountryName")[0]); } [Test] public void OnField_WithNonExistingField() { ValidationErrors errors = new ValidationErrors(); Assert.IsNull(errors.OnField("foo")); } [Test] public void ForObject_WithNestedErrors() { ValidationErrors addressErrors = new ValidationErrors(); addressErrors.AddError("country_name", new ValidationError("country_name", "91803", "invalid country")); ValidationErrors errors = new ValidationErrors(); errors.AddErrors("address", addressErrors); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code); Assert.AreEqual("invalid country", errors.ForObject("address").OnField("country_name")[0].Message); } [Test] public void ForObject_WithNonExistingObject() { ValidationErrors errors = new ValidationErrors(); Assert.AreEqual(0, errors.ForObject("address").Count); } [Test] public void ForObject_WorksWithAllCommonCasing() { ValidationErrors nestedErrors = new ValidationErrors(); ValidationErrors errors = new ValidationErrors(); errors.AddErrors("credit-card", nestedErrors); Assert.AreEqual(nestedErrors, errors.ForObject("credit-card")); Assert.AreEqual(nestedErrors, errors.ForObject("credit_card")); Assert.AreEqual(nestedErrors, errors.ForObject("creditCard")); Assert.AreEqual(nestedErrors, errors.ForObject("CreditCard")); } [Test] public void Size_WithShallowErrors() { ValidationErrors errors = new ValidationErrors(); errors.AddError("country_name", new ValidationError("country_name", "1", "invalid country")); errors.AddError("another_field", new ValidationError("another_field", "2", "another message")); Assert.AreEqual(2, errors.Count); } [Test] public void DeepCount_WithNestedErrors() { ValidationErrors addressErrors = new ValidationErrors(); addressErrors.AddError("country_name", new ValidationError("country_name", "1", "invalid country")); addressErrors.AddError("another_field", new ValidationError("another_field", "2", "another message")); ValidationErrors errors = new ValidationErrors(); errors.AddError("some_field", new ValidationError("some_field", "3", "some message")); errors.AddErrors("address", addressErrors); Assert.AreEqual(3, errors.DeepCount); Assert.AreEqual(1, errors.Count); Assert.AreEqual(2, errors.ForObject("address").DeepCount); Assert.AreEqual(2, errors.ForObject("address").Count); } [Test] public void Constructor_ParsesSimpleValidationErrors() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <address>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>91803</code>"); builder.Append(" <message>Country name is not an accepted country.</message>"); builder.Append(" <attribute type=\"symbol\">country_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </address>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(1, errors.DeepCount); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code); } [Test] public void Constructor_ParsesMulitpleValidationErrorsOnOneObject() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <address>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>91803</code>"); builder.Append(" <message>Country name is not an accepted country.</message>"); builder.Append(" <attribute type=\"symbol\">country_name</attribute>"); builder.Append(" </error>"); builder.Append(" <error>"); builder.Append(" <code>81812</code>"); builder.Append(" <message>Street address is too long.</message>"); builder.Append(" <attribute type=\"symbol\">street_address</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </address>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(2, errors.DeepCount); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("address").OnField("country_name")[0].Code); Assert.AreEqual(ValidationErrorCode.ADDRESS_STREET_ADDRESS_IS_TOO_LONG, errors.ForObject("address").OnField("street_address")[0].Code); } [Test] public void Constructor_ParsesValidationErrorOnNestedObject() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" <credit-card>"); builder.Append(" <billing-address>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>91803</code>"); builder.Append(" <message>Country name is not an accepted country.</message>"); builder.Append(" <attribute type=\"symbol\">country_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </billing-address>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </credit-card>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(1, errors.DeepCount); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("credit-card").ForObject("billing-address").OnField("country_name")[0].Code); } [Test] public void Constructor_ParsesMultipleErrorsOnSingleField() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <transaction>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>91516</code>"); builder.Append(" <message>Cannot provide both payment_method_token and customer_id unless the payment_method belongs to the customer.</message>"); builder.Append(" <attribute type=\"symbol\">base</attribute>"); builder.Append(" </error>"); builder.Append(" <error>"); builder.Append(" <code>91515</code>"); builder.Append(" <message>Cannot provide both payment_method_token and credit_card attributes.</message>"); builder.Append(" <attribute type=\"symbol\">base</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </transaction>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(2, errors.DeepCount); Assert.AreEqual(2, errors.ForObject("transaction").OnField("base").Count); } [Test] public void Constructor_ParsesValidationErrorsAtMultipleLevels() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <customer>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81608</code>"); builder.Append(" <message>First name is too long.</message>"); builder.Append(" <attribute type=\"symbol\">first_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" <credit-card>"); builder.Append(" <billing-address>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>91803</code>"); builder.Append(" <message>Country name is not an accepted country.</message>"); builder.Append(" <attribute type=\"symbol\">country_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </billing-address>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81715</code>"); builder.Append(" <message>Credit card number is invalid.</message>"); builder.Append(" <attribute type=\"symbol\">number</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </credit-card>"); builder.Append(" </customer>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(3, errors.DeepCount); Assert.AreEqual(0, errors.Count); Assert.AreEqual(3, errors.ForObject("customer").DeepCount); Assert.AreEqual(1, errors.ForObject("customer").Count); Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").OnField("first_name")[0].Code); Assert.AreEqual(2, errors.ForObject("customer").ForObject("credit-card").DeepCount); Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").Count); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").OnField("number")[0].Code); Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").DeepCount); Assert.AreEqual(1, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").Count); Assert.AreEqual(ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, errors.ForObject("customer").ForObject("credit-card").ForObject("billing-address").OnField("country_name")[0].Code); } [Test] public void ByFormField_FlattensErrorsToFormElementNames() { var errors = new ValidationErrors(); errors.AddError("some_error", new ValidationError("some_error", "1", "some error")); errors.AddError("some_error", new ValidationError("some_error", "2", "some other error")); var nestedErrors = new ValidationErrors(); nestedErrors.AddError("some_nested_error", new ValidationError("some_nested_error", "3", "some nested error")); nestedErrors.AddError("some_nested_error", new ValidationError("some_nested_error", "4", "some other nested error")); var nestedNestedErrors = new ValidationErrors(); nestedNestedErrors.AddError("some_nested_nested_error", new ValidationError("some_nested_nested_error", "5", "some nested nested error")); nestedNestedErrors.AddError("some_nested_nested_error", new ValidationError("some_nested_nested_error", "6", "some other nested nested error")); nestedErrors.AddErrors("some_nested_object", nestedNestedErrors); errors.AddErrors("some_object", nestedErrors); Dictionary<String, List<String>> formErrors = errors.ByFormField(); Assert.AreEqual("some error", formErrors["some_error"][0]); Assert.AreEqual("some other error", formErrors["some_error"][1]); Assert.AreEqual("some nested error", formErrors["some_object[some_nested_error]"][0]); Assert.AreEqual("some other nested error", formErrors["some_object[some_nested_error]"][1]); Assert.AreEqual("some nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][0]); Assert.AreEqual("some other nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][1]); } [Test] public void ByFormField_UnderscoresNodes() { var errors = new ValidationErrors(); errors.AddError("some-error", new ValidationError("some-error", "1", "some error")); errors.AddError("some-error", new ValidationError("some-error", "2", "some other error")); var nestedErrors = new ValidationErrors(); nestedErrors.AddError("some-nested-error", new ValidationError("some-nested-error", "3", "some nested error")); nestedErrors.AddError("some-nested-error", new ValidationError("some-nested-error", "4", "some other nested error")); var nestedNestedErrors = new ValidationErrors(); nestedNestedErrors.AddError("some-nested-nested-error", new ValidationError("some-nested-nested-error", "5", "some nested nested error")); nestedNestedErrors.AddError("some-nested-nested-error", new ValidationError("some-nested-nested-error", "6", "some other nested nested error")); nestedErrors.AddErrors("some-nested-object", nestedNestedErrors); errors.AddErrors("some-object", nestedErrors); Dictionary<String, List<String>> formErrors = errors.ByFormField(); Assert.AreEqual("some error", formErrors["some_error"][0]); Assert.AreEqual("some other error", formErrors["some_error"][1]); Assert.AreEqual("some nested error", formErrors["some_object[some_nested_error]"][0]); Assert.AreEqual("some other nested error", formErrors["some_object[some_nested_error]"][1]); Assert.AreEqual("some nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][0]); Assert.AreEqual("some other nested nested error", formErrors["some_object[some_nested_object][some_nested_nested_error]"][1]); } [Test] public void All_ReturnsValidationErrorsAtOneLevel() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <customer>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81608</code>"); builder.Append(" <message>First name is too long.</message>"); builder.Append(" <attribute type=\"symbol\">first_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" <credit-card>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81715</code>"); builder.Append(" <message>Credit card number is invalid.</message>"); builder.Append(" <attribute type=\"symbol\">number</attribute>"); builder.Append(" </error>"); builder.Append(" <error>"); builder.Append(" <code>81710</code>"); builder.Append(" <message>Expiration date is invalid.</message>"); builder.Append(" <attribute type=\"symbol\">expiration_date</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </credit-card>"); builder.Append(" </customer>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(0, errors.All().Count); Assert.AreEqual(1, errors.ForObject("customer").All().Count); Assert.AreEqual("first_name", errors.ForObject("customer").All()[0].Attribute); Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").All()[0].Code); Assert.AreEqual(2, errors.ForObject("customer").ForObject("credit-card").All().Count); Assert.AreEqual("number", errors.ForObject("customer").ForObject("credit-card").All()[0].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").All()[0].Code); Assert.AreEqual("expiration_date", errors.ForObject("customer").ForObject("credit-card").All()[1].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.ForObject("customer").ForObject("credit-card").All()[1].Code); } [Test] public void DeepAll_ReturnsValidationErrorsAtEveryLevel() { StringBuilder builder = new StringBuilder(); builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); builder.Append("<api-error-response>"); builder.Append(" <errors>"); builder.Append(" <customer>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81608</code>"); builder.Append(" <message>First name is too long.</message>"); builder.Append(" <attribute type=\"symbol\">first_name</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" <credit-card>"); builder.Append(" <errors type=\"array\">"); builder.Append(" <error>"); builder.Append(" <code>81715</code>"); builder.Append(" <message>Credit card number is invalid.</message>"); builder.Append(" <attribute type=\"symbol\">number</attribute>"); builder.Append(" </error>"); builder.Append(" <error>"); builder.Append(" <code>81710</code>"); builder.Append(" <message>Expiration date is invalid.</message>"); builder.Append(" <attribute type=\"symbol\">expiration_date</attribute>"); builder.Append(" </error>"); builder.Append(" </errors>"); builder.Append(" </credit-card>"); builder.Append(" </customer>"); builder.Append(" <errors type=\"array\"/>"); builder.Append(" </errors>"); builder.Append("</api-error-response>"); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); ValidationErrors errors = new ValidationErrors(new NodeWrapper(doc.ChildNodes[1])); Assert.AreEqual(3, errors.DeepAll().Count); Assert.AreEqual("first_name", errors.DeepAll()[0].Attribute); Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.DeepAll()[0].Code); Assert.AreEqual("number", errors.DeepAll()[1].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.DeepAll()[1].Code); Assert.AreEqual("expiration_date", errors.DeepAll()[2].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.DeepAll()[2].Code); Assert.AreEqual(3, errors.ForObject("customer").DeepAll().Count); Assert.AreEqual("first_name", errors.ForObject("customer").DeepAll()[0].Attribute); Assert.AreEqual(ValidationErrorCode.CUSTOMER_FIRST_NAME_IS_TOO_LONG, errors.ForObject("customer").DeepAll()[0].Code); Assert.AreEqual("number", errors.ForObject("customer").DeepAll()[1].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID, errors.ForObject("customer").DeepAll()[1].Code); Assert.AreEqual("expiration_date", errors.ForObject("customer").DeepAll()[2].Attribute); Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, errors.ForObject("customer").DeepAll()[2].Code); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Batch.Tests.Helpers; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; using Microsoft.Rest; using Microsoft.Rest.Azure; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Microsoft.Azure.Batch.Tests { public class InMemoryAccountTests { [Fact] public void AccountCreateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Create(null, "bar", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", null, new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", "bar", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("invalid+", "account", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "invalid%", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "/invalid", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "s", new BatchAccountCreateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "account_name_that_is_too_long", new BatchAccountCreateParameters())); } [Fact] public void AccountCreateAsyncValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = Task.Factory.StartNew(() => client.BatchAccount.CreateWithHttpMessagesAsync( "foo", "acctName", new BatchAccountCreateParameters { Location = "South Central US", Tags = tags })).Unwrap().GetAwaiter().GetResult(); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Put, handler.Requests[0].Method); Assert.NotNull(handler.Requests[0].Headers.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Body.Location); Assert.NotEmpty(result.Body.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.Body.ProvisioningState); Assert.Equal(2, result.Body.Tags.Count); } [Fact] public void CreateAccountWithAutoStorageAsyncValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var utcNow = DateTime.UtcNow; var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'autoStorage' :{ 'storageAccountId' : '//storageAccount1', 'lastKeySync': '" + utcNow.ToString("o") + @"', } }, }") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.Create("resourceGroupName", "acctName", new BatchAccountCreateParameters { Location = "South Central US", AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//storageAccount1" } }); // Validate result Assert.Equal("//storageAccount1", result.AutoStorage.StorageAccountId); Assert.Equal(utcNow, result.AutoStorage.LastKeySync); } [Fact] public void AccountUpdateWithAutoStorageValidateMessage() { var utcNow = DateTime.UtcNow; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'autoStorage' : { 'storageAccountId' : '//StorageAccountId', 'lastKeySync': '" + utcNow.ToString("o") + @"', } }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Update("foo", "acctName", new BatchAccountUpdateParameters { Tags = tags, }); // Validate headers - User-Agent for certs, Authorization for tokens //Assert.Equal(HttpMethod.Patch, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState); Assert.Equal("//StorageAccountId", result.AutoStorage.StorageAccountId); Assert.Equal(utcNow, result.AutoStorage.LastKeySync); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountCreateSyncValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Create("foo", "acctName", new BatchAccountCreateParameters("westus") { Tags = tags, AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//storageAccount1" } }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(result.ProvisioningState, ProvisioningState.Succeeded); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountUpdateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; var handler = new RecordedDelegatingHandler(response); var client = BatchTestHelper.GetBatchManagementClient(handler); var tags = new Dictionary<string, string>(); tags.Add("tag1", "value for tag1"); tags.Add("tag2", "value for tag2"); var result = client.BatchAccount.Update("foo", "acctName", new BatchAccountUpdateParameters { Tags = tags, AutoStorage = new AutoStorageBaseProperties() { StorageAccountId = "//StorageAccountId" } }); // Validate headers - User-Agent for certs, Authorization for tokens Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState); Assert.Equal(2, result.Tags.Count); } [Fact] public void AccountUpdateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Update(null, null, new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", null, new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", "bar", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("invalid+", "account", new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "invalid%", new BatchAccountUpdateParameters())); Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "/invalid", new BatchAccountUpdateParameters())); } [Fact] public void AccountDeleteValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var okResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); client.BatchAccount.Delete("resGroup", "acctName"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); } [Fact] public void AccountDeleteNotFoundValidateMessage() { var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(@"") }; acceptedResponse.Headers.Add("x-ms-request-id", "1"); acceptedResponse.Headers.Add("Location", @"http://someLocationURL"); var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(@"") }; var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, notFoundResponse }); var client = BatchTestHelper.GetBatchManagementClient(handler); var result = Assert.Throws<CloudException>(() => Task.Factory.StartNew(() => client.BatchAccount.DeleteWithHttpMessagesAsync( "resGroup", "acctName")).Unwrap().GetAwaiter().GetResult()); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); Assert.Equal(HttpStatusCode.NotFound, result.Response.StatusCode); } [Fact] public void AccountDeleteOkValidateMessage() { var noContentResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"") }; noContentResponse.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(noContentResponse); var client = BatchTestHelper.GetBatchManagementClient(handler); client.BatchAccount.Delete("resGroup", "acctName"); // Validate headers Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method); } [Fact] public void AccountDeleteThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete(null, "bar")); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("invalid+", "account")); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "invalid%")); Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "/invalid")); } [Fact] public void AccountGetValidateResponse() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.Get("foo", "acctName"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal("South Central US", result.Location); Assert.Equal("acctName", result.Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Id); Assert.NotEmpty(result.AccountEndpoint); Assert.Equal(20, result.CoreQuota); Assert.Equal(100, result.PoolQuota); Assert.Equal(200, result.ActiveJobAndJobScheduleQuota); Assert.True(result.Tags.ContainsKey("tag1")); } [Fact] public void AccountGetThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.Get(null, "bar")); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("invalid+", "account")); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "invalid%")); Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "/invalid")); } [Fact] public void AccountListValidateMessage() { var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : '' }") }; var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } } ], 'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack' } ") }; allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1"); allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1"); // all accounts under sub and empty next link var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = Task.Factory.StartNew(() => client.BatchAccount.ListWithHttpMessagesAsync()) .Unwrap() .GetAwaiter() .GetResult(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); // Validate result Assert.Equal(2, result.Body.Count()); var account1 = result.Body.ElementAt(0); var account2 = result.Body.ElementAt(1); Assert.Equal("West US", account1.Location); Assert.Equal("acctName", account1.Name); Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", account1.Id); Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1", account2.Id); Assert.NotEmpty(account1.AccountEndpoint); Assert.Equal(20, account1.CoreQuota); Assert.Equal(100, account1.PoolQuota); Assert.Equal(200, account2.ActiveJobAndJobScheduleQuota); Assert.True(account1.Tags.ContainsKey("tag1")); // all accounts under sub and a non-empty nextLink handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK }; client = BatchTestHelper.GetBatchManagementClient(handler); var result1 = client.BatchAccount.List(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // all accounts under sub with a non-empty nextLink response handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1) { StatusCodeToReturn = HttpStatusCode.OK }; client = BatchTestHelper.GetBatchManagementClient(handler); result1 = client.BatchAccount.ListNext(result1.NextPageLink); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); } [Fact] public void AccountListByResourceGroupValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@" { 'value': [ { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName', 'location': 'West US', 'properties': { 'accountEndpoint' : 'http://acctName.batch.core.windows.net/', 'provisioningState' : 'Succeeded', 'coreQuota' : '20', 'poolQuota' : '100', 'activeJobAndJobScheduleQuota' : '200' }, 'tags' : { 'tag1' : 'value for tag1', 'tag2' : 'value for tag2', } }, { 'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1', 'type' : 'Microsoft.Batch/batchAccounts', 'name': 'acctName1', 'location': 'South Central US', 'properties': { 'accountEndpoint' : 'http://acctName1.batch.core.windows.net/', 'provisioningState' : 'Failed', 'coreQuota' : '10', 'poolQuota' : '50', 'activeJobAndJobScheduleQuota' : '100' }, 'tags' : { 'tag1' : 'value for tag1' } } ], 'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack' }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.List(); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.Equal(2, result.Count()); var account1 = result.ElementAt(0); var account2 = result.ElementAt(1); Assert.Equal("West US", account1.Location); Assert.Equal("acctName", account1.Name); Assert.Equal( @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", account1.Id); Assert.Equal(@"http://acctName.batch.core.windows.net/", account1.AccountEndpoint); Assert.Equal(ProvisioningState.Succeeded, account1.ProvisioningState); Assert.Equal(20, account1.CoreQuota); Assert.Equal(100, account1.PoolQuota); Assert.Equal(200, account1.ActiveJobAndJobScheduleQuota); Assert.Equal("South Central US", account2.Location); Assert.Equal("acctName1", account2.Name); Assert.Equal(@"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1", account2.Id); Assert.Equal(@"http://acctName1.batch.core.windows.net/", account2.AccountEndpoint); Assert.Equal(ProvisioningState.Failed, account2.ProvisioningState); Assert.Equal(10, account2.CoreQuota); Assert.Equal(50, account2.PoolQuota); Assert.Equal(100, account2.ActiveJobAndJobScheduleQuota); Assert.Equal(2, account1.Tags.Count); Assert.True(account1.Tags.ContainsKey("tag2")); Assert.Equal(1, account2.Tags.Count); Assert.True(account2.Tags.ContainsKey("tag1")); Assert.Equal(@"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack", result.NextPageLink); } [Fact] public void AccountListNextThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.BatchAccount.ListNext(null)); } [Fact] public void AccountKeysListValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.GetKeys("foo", "acctName"); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.Primary); Assert.Equal(primaryKeyString, result.Primary); Assert.NotEmpty(result.Secondary); Assert.Equal(secondaryKeyString, result.Secondary); } [Fact] public void AccountKeysListThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys("foo", null)); Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys(null, "bar")); } [Fact] public void AccountKeysRegenerateValidateMessage() { var primaryKeyString = "primary key string which is alot longer than this"; var secondaryKeyString = "secondary key string which is alot longer than this"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'primary' : 'primary key string which is alot longer than this', 'secondary' : 'secondary key string which is alot longer than this', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = BatchTestHelper.GetBatchManagementClient(handler); var result = client.BatchAccount.RegenerateKey( "foo", "acctName", AccountKeyType.Primary); // Validate headers - User-Agent for certs, Authorization for tokens Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent")); // Validate result Assert.NotEmpty(result.Primary); Assert.Equal(primaryKeyString, result.Primary); Assert.NotEmpty(result.Secondary); Assert.Equal(secondaryKeyString, result.Secondary); } [Fact] public void AccountKeysRegenerateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = BatchTestHelper.GetBatchManagementClient(handler); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey(null, "bar", AccountKeyType.Primary)); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("foo", null, AccountKeyType.Primary)); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("invalid+", "account", AccountKeyType.Primary)); Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("rg", "invalid%", AccountKeyType.Primary)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Agrotera.Setting; using Agrotera.Core; using Agrotera.Core.Entities; using Agrotera.Core.Types; namespace AgroteraScripts.StandardCampaign { public static class AssemblyFinder { public static System.Reflection.Assembly GetThisAssembly() { return System.Reflection.Assembly.GetExecutingAssembly(); } } public class DefaultShipTemplates : Agrotera.Scripting.IScript { private bool UseWarp = true; public void InitAgroteraScript() { Campaign campaign = Campaign.Get("Standard"); campaign.Configuration.Add(new BooleanConfigruationItem("UseWarp", "Enable Warp Drive", "When selected, allows ships to have warp drive as an option instead of just JumpDrives", true)); campaign.QueryShipForFaction += GetShipForFaction; campaign.QueryPlayerShipType += GetPlayerShipType; campaign.CampaignLoaded += campaign_CampaignLoaded; } void campaign_CampaignLoaded(object sender, Campaign.CampaignRuntimeEventInfo e) { Campaign campaign = e.CurrentCampaign; if(campaign.Configuration.Exists("UseWarp")) UseWarp = (campaign.Configuration.Find("UseWarp") as BooleanConfigruationItem).Value; // common stations Station.StationTemplate smallStation = campaign.NewTemplate<Station.StationTemplate>("Small Station"); smallStation.Model = "space_staton_4"; smallStation.Hull = 150; smallStation.Shields = 300; smallStation.Radius = 50; smallStation.ControllerName = "StationController"; Station.StationTemplate mediumStation = campaign.NewTemplate<Station.StationTemplate>("Medium Station"); mediumStation.Model = "space_station_3"; mediumStation.Hull = 400; mediumStation.Shields = 800; mediumStation.Radius = 75; mediumStation.ControllerName = "StationController"; Station.StationTemplate largeStation = campaign.NewTemplate<Station.StationTemplate>("Large Station"); largeStation.Model = "space_station_2"; largeStation.Hull = 500; largeStation.Shields = 1000; largeStation.Radius = 100; largeStation.ControllerName = "StationController"; Station.StationTemplate hugeStation = campaign.NewTemplate<Station.StationTemplate>("Huge Station"); hugeStation.Model = "space_station_1"; hugeStation.Hull = 800; hugeStation.Shields = 1200; hugeStation.Radius = 150; hugeStation.ControllerName = "StationController"; // player ships SetupPlayerCruiser(campaign.NewTemplate<Ship.ShipTemplate>("Player Cruiser"), campaign); SetupPlayerMissileCruiser(campaign.NewTemplate<Ship.ShipTemplate>("Player Missile Cruiser"), campaign); SetupPlayerFighter(campaign.NewTemplate<Ship.ShipTemplate>("Player Fighter"), campaign); // AI Ships // Merchant ships SetupTug(campaign.NewTemplate<Ship.ShipTemplate>("Tug"), campaign); // fighters SetupSmallFighter(campaign.NewTemplate<Ship.ShipTemplate>("Fighter"), campaign); // Fleet Ships SetupKarnackCruiserMk1(campaign.NewTemplate<Ship.ShipTemplate>("Cruiser"), campaign); SetupKarnackCruiserMk2(campaign.NewTemplate<Ship.ShipTemplate>("Upgraded Cruiser"), campaign); SetupPolarisCruiser(campaign.NewTemplate<Ship.ShipTemplate>("Missile Cruiser"), campaign); SetupGunship(campaign.NewTemplate<Ship.ShipTemplate>("Advanced Gunship"), campaign); SetupStrikeShip(campaign.NewTemplate<Ship.ShipTemplate>("Strikeship"), campaign); SetupAdvancedStrikeShip(campaign.NewTemplate<Ship.ShipTemplate>("Advanced Strikeship"), campaign); SetupDreadnought(campaign.NewTemplate<Ship.ShipTemplate>("Dreadnought"), campaign); SetupBattleStation(campaign.NewTemplate<Ship.ShipTemplate>("Battle Station"), campaign); SetupBlockadeRunner(campaign.NewTemplate<Ship.ShipTemplate>("Blockade Runner"), campaign); // Fleet Stations SetupWeaponsPlatform(campaign.NewTemplate<Station.StationTemplate>("Weapons Platform"), campaign); } void GetPlayerShipType(object sender, Campaign.CampaignTemplateQueryEventArgs args) { string desiredShip = string.Empty; if(args.Arguments.Length > 0) desiredShip = args.Arguments[0]; args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(desiredShip); if (args.ReturnedTemplate == null) args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate("Player Cruiser"); } void GetShipForFaction(object sender, Campaign.CampaignTemplateQueryEventArgs args) { switch(args.Query) { case "Independent": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] { "Tug", "Blockade Runner" })); break; case "Human Navy": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] { "Cruiser", "Upgraded Cruiser", "Missile Cruiser" })); break; case "Kraylor": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] { "Cruiser", "Upgraded Cruiser", "Dreadnought" })); break; case "Arlenians": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] { "Cruiser", "Blockade Runner", "Upgraded Cruiser" })); break; case "Exuari": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] { "Cruiser", "Blockade Runner", "Strikeship" })); break; case "Ghosts": args.ReturnedTemplate = args.RuntimeEventArgs.CurrentCampaign.FindTemplate(Agrotera.Core.Utilities.RandomElement(new string[] {"Upgraded Cruiser", "Blockade Runner", "Dreadnought" })); break; } } void SetupWeaponsPlatform(Station.StationTemplate station, Campaign campaign) { var item = campaign.ScienceDB.New("Station", "Weapons Platform"); item.AddDescriptionLine("The weapons-platform is a stationary platform with beam-weapons."); item.AddDescriptionLine("It's not maneuverable, but it's beam weapons deal huge amounts of damage from any angle"); item.Known = true; station.ScienceDBID = item.ID; station.Model = "space_staton_4"; station.NewBeamWeapon(30, 0, 4000.0f, 1.5f, 20); station.NewBeamWeapon(30, 60, 4000.0f, 1.5f, 20); station.NewBeamWeapon(30, 120, 4000.0f, 1.5f, 20); station.NewBeamWeapon(30, 180, 4000.0f, 1.5f, 20); station.NewBeamWeapon(30, 240, 4000.0f, 1.5f, 20); station.NewBeamWeapon(30, 300, 4000.0f, 1.5f, 20); station.Hull = 70; station.Shields = 120; station.DefaultBehavor = "battle_station_AI"; station.SetScienceItemFields(item); } void SetupBlockadeRunner(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Blockade Runner"); item.AddDescriptionLine("Fabricated by: Zoop"); item.AddDescriptionLine("Blockade runner is a reasonably fast, high shield, slow on weapons ship designed to break trough defense lines and deliver/smuggle goods."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "battleship_destroyer_3_upgraded"; ship.NewBeamWeapon(50, -15, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(50, 15, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(60, -15, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(60, 15, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(25, 170, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(25, 190, 1000.0f, 6.0f, 8); ship.Hull = 70; ship.FrontShields = 100; ship.RearShields = 150; ship.SublightSpeed = 60; ship.RotatonSpeed = 15; ship.SublightAcceleration = 25; ship.FTLType = Ship.FTLTypes.None; ship.AddStores("Trade Goods", 250); ship.AddWeaponStores(MissileWeaponTypes.Homing, 25); ship.AddWeaponStores(MissileWeaponTypes.Nuke, 25); ship.AddWeaponStores(MissileWeaponTypes.Mine, 50); ship.AddWeaponStores(MissileWeaponTypes.EMP, 50); ship.DefaultBehavor = "runner_AI"; ship.SetScienceItemFields(item); } void SetupBattleStation(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Battle Station"); item.AddDescriptionLine("The battle station is a huge ship with many defensive features."); item.AddDescriptionLine("More station than ship, it can provide docking facilities for smaller ships."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "Ender Battlecruiser"; ship.NewBeamWeapon(120, -90, 2500.0f, 6.1f, 4); ship.NewBeamWeapon(120, -90, 2500.0f, 6.0f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 6.1f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 6.0f, 4); ship.NewBeamWeapon(120, -90, 2500.0f, 5.9f, 4); ship.NewBeamWeapon(120, -90, 2500.0f, 6.2f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 5.9f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 6.2f, 4); ship.NewBeamWeapon(120, -90, 2500.0f, 6.1f, 4); ship.NewBeamWeapon(120, -90, 2500.0f, 6.0f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 6.1f, 4); ship.NewBeamWeapon(120, 90, 2500.0f, 6.0f, 4); ship.Hull = 120; ship.FrontShields = 1500; ship.RearShields = 1500; ship.SublightSpeed = 20; ship.RotatonSpeed = 1.5f; ship.SublightAcceleration = 3; ship.FTLType = Ship.FTLTypes.JumpDrive; ship.FTLLimit = 100; ship.DefaultBehavor = "battle_cruiser_AI"; ship.SetScienceItemFields(item); } void SetupDreadnought(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Dreadnought"); item.AddDescriptionLine("The Dreadnought is a flying fortress, it's slow, slow to turn, but packs a huge amount of beam weapons in the front."); item.AddDescriptionLine("Attacking this type of ship head-on is suicide for most vessels."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "battleship_destroyer_1_upgraded"; ship.NewBeamWeapon(90, -25, 1500.0f, 6.0f, 8); ship.NewBeamWeapon(90, 25, 1500.0f, 6.0f, 8); ship.NewBeamWeapon(100, -60, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(100, 60, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(30, 0, 2000.0f, 6.0f, 8); ship.NewBeamWeapon(100, 180, 1200.0f, 6.0f, 8); ship.Hull = 120; ship.FrontShields = 300; ship.RearShields = 300; ship.SublightSpeed = 30; ship.RotatonSpeed = 1.5f; ship.SublightAcceleration = 5; ship.FTLType = Ship.FTLTypes.JumpDrive; ship.FTLLimit = 50; ship.DefaultBehavor = "battle_cruiser_AI"; ship.SetScienceItemFields(item); } void SetupAdvancedStrikeShip(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Advanced Strikeship"); item.AddDescriptionLine("Fabricated by: Void-Tech LLC"); item.AddDescriptionLine("A competitor to the strikeship, equipped with a jump drive instead of traditional warp capability"); item.AddDescriptionLine("Built for fast attack assaults, it focuses on offensive capabilities at the expense of defenses."); item.AddDescriptionLine("While not quite as tough as a traditional strikeship, the jump drive allows it arrive on site much faster."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "dark_fighter_6"; ship.NewBeamWeapon(50, -15, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(50, 15, 1000.0f, 6.0f, 6); ship.Hull = 70; ship.FrontShields = 50; ship.RearShields = 30; ship.SublightSpeed = 45; ship.RotatonSpeed = 12; ship.SublightAcceleration = 15; ship.FTLType = Ship.FTLTypes.JumpDrive; ship.FTLLimit = 1000; ship.DefaultBehavor = "strike_cruiser_AI"; ship.SetScienceItemFields(item); } void SetupStrikeShip(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Strikeship"); item.AddDescriptionLine("Fabricated by: Insight Corporation."); item.AddDescriptionLine("An upgraded and warp capable agile fighter."); item.AddDescriptionLine("Built for fast attack assaults, it focuses on offensive capabilities at the expense of defenses."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "dark_fighter_6"; ship.NewBeamWeapon(40, -5, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(40, 5, 1000.0f, 6.0f, 6); ship.Hull = 100; ship.FrontShields = 100; ship.RearShields = 30; ship.SublightSpeed = 70; ship.RotatonSpeed = 12; ship.SublightAcceleration = 11; ship.FTLType = UseWarp ? Ship.FTLTypes.WarpDrive : Ship.FTLTypes.JumpDrive; ship.FTLLimit = 1000; ship.DefaultBehavor = "strike_cruiser_AI"; ship.SetScienceItemFields(item); } void SetupGunship(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Advanced Gunship"); item.AddDescriptionLine("Fabricated by: Insight Corporation."); item.AddDescriptionLine("The advanced gunship is quipped with 2 homing missiles to do initial damage and 2 front firing beams to complete the kill."); item.AddDescriptionLine("It's designed to quickly take out the enemies weaker then itself."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "battleship_destroyer_4_upgraded"; ship.NewBeamWeapon(50, -15, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(50, 15, 1000.0f, 6.0f, 6); ship.AddMissileTubes(2, 8); ship.Hull = 100; ship.FrontShields = 100; ship.RearShields = 80; ship.SublightSpeed = 60; ship.RotatonSpeed = 5; ship.SublightAcceleration = 10; ship.AddWeaponStores(MissileWeaponTypes.Homing, 8); ship.FTLType = Ship.FTLTypes.None; ship.DefaultBehavor = "strike_cruiser_AI"; ship.SetScienceItemFields(item); } void SetupPolarisCruiser(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Polaris Missile Cruiser Mark 1"); item.AddDescriptionLine("Fabricated by: Repulse shipyards."); item.AddDescriptionLine("The missile cruiser is a long range missile firing platform employed by numerous governments."); item.AddDescriptionLine("It cannot handle much punishment, but can deal massive damage if not dealt with properly."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "space_cruiser_4"; ship.AddMissileTubes(4, 25.0f); ship.Hull = 40; ship.FrontShields = 50; ship.RearShields = 50; ship.SublightSpeed = 45; ship.RotatonSpeed = 3; ship.SublightAcceleration = 10; ship.FTLType = Ship.FTLTypes.None; ship.AddWeaponStores(MissileWeaponTypes.Homing, 50); ship.DefaultBehavor = "fighter_AI"; ship.SetScienceItemFields(item); } void SetupKarnackCruiserMk1(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Karnack Cruiser Mark I"); item.AddDescriptionLine("Fabricated by: Repulse shipyards."); item.AddDescriptionLine("Due to it's versatility, this ship has found wide adaptation in numerous governments."); item.AddDescriptionLine("Most vessels have been extensively retrofitted to suit their desired combat doctrines."); item.AddDescriptionLine("Because it's an older model, most factions have been selling stripped versions."); item.AddDescriptionLine("This practice has made the class a favorite with smugglers and other mercenary groups."); item.AddDescriptionLine("Many have used the ship's adaptable nature to facilitate re-fits incorporate illegal weaponry."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "space_frigate_6"; ship.NewBeamWeapon(75, -15, 1000.0f, 6.0f, 6); ship.NewBeamWeapon(75, 15, 1000.0f, 6.0f, 6); ship.Hull = 70; ship.FrontShields = 40; ship.RearShields = 40; ship.SublightSpeed = 60; ship.RotatonSpeed = 6; ship.SublightAcceleration = 10; ship.FTLType = Ship.FTLTypes.None; ship.DefaultBehavor = "cruiser_AI"; ship.SetScienceItemFields(item); } void SetupKarnackCruiserMk2(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Karnack Cruiser Mark II"); item.AddDescriptionLine("Fabricated by: Repulse shipyards."); item.AddDescriptionLine("The successor to the wildly successfullyMark I cruiser. "); item.AddDescriptionLine("This ship has several notable improvements over the original model, including hull reinforcements, improved weaponry and increased performance."); item.AddDescriptionLine("These improvements were mainly requested by customers once they realized that their old surplus mark I ships were being used against them by pirates and smugglers."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "space_frigate_6"; ship.NewBeamWeapon(90, -15, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(90, 15, 1000.0f, 6.0f, 8); ship.AddMissileTubes(1, 15.0f); ship.AddWeaponStores(MissileWeaponTypes.Homing, 5); ship.AddStores("Trade Goods", 25); ship.Hull = 80; ship.FrontShields = 60; ship.RearShields = 60; ship.SublightSpeed = 65; ship.RotatonSpeed = 8; ship.SublightAcceleration = 12; ship.FTLType = Ship.FTLTypes.None; ship.DefaultBehavor = "cruiser_AI"; ship.SetScienceItemFields(item); } void SetupSmallFighter(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Snub Fighter"); item.AddDescriptionLine("Fabricated by: Various."); item.AddDescriptionLine("A small fighter class ship, generally attached to a larger ship or station."); item.AddDescriptionLine("Lightweight and poorly armored, these small ships rely on maneuverability to deliver weapon payloads to strategic locations on larger ships."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "small_fighter_1"; ship.NewBeamWeapon(60, -0, 1000.0f, 4.0f, 4); ship.Hull = 30; ship.FrontShields = 30; ship.RearShields = 30; ship.SublightSpeed = 120; ship.RotatonSpeed = 30; ship.SublightAcceleration = 25; ship.FTLType = Ship.FTLTypes.None; ship.DefaultBehavor = "cruiser_AI"; ship.SetScienceItemFields(item); } void SetupTug(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Tug"); item.AddDescriptionLine("Fabricated by: Various."); item.AddDescriptionLine("A small cargo/utility ship used for various means of commerce"); item.AddDescriptionLine("Slow and unarmored these commercial vehicles can be found anywhere there is space-based infrastructure."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "space_tug"; ship.Hull = 50; ship.FrontShields = 20; ship.RearShields = 20; ship.SublightSpeed = 90; ship.RotatonSpeed = 6; ship.SublightAcceleration = 10; ship.FTLType = Ship.FTLTypes.None; ship.AddWeaponStores(MissileWeaponTypes.Homing, 5); ship.AddWeaponStores(MissileWeaponTypes.Nuke, 1); ship.AddWeaponStores(MissileWeaponTypes.Mine, 3); ship.AddWeaponStores(MissileWeaponTypes.EMP, 2); ship.AddStores("Trade Goods", 100); ship.SetScienceItemFields(item); } void SetupPlayerCruiser(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Cruiser"); item.AddDescriptionLine("Fabricated by: Various Faction Navies"); item.AddDescriptionLine("The cruiser is a long range patrol ship employed by numerous governments."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "battleship_destroyer_5_upgraded"; ship.NewBeamWeapon(90, -15, 1000.0f, 6.0f, 10); ship.NewBeamWeapon(90, 15, 1000.0f, 6.0f, 10); ship.AddMissileTubes(2, 8.0f); ship.Hull = 200; ship.FrontShields = 80; ship.RearShields = 80; ship.SublightSpeed = 90; ship.RotatonSpeed = 10; ship.SublightAcceleration = 20; ship.FTLType = Ship.FTLTypes.JumpDrive; ship.FTLLimit = 50; ship.CanCloak = false; ship.AddWeaponStores(MissileWeaponTypes.Homing, 12); ship.AddWeaponStores(MissileWeaponTypes.Nuke, 4); ship.AddWeaponStores(MissileWeaponTypes.Mine, 8); ship.AddWeaponStores(MissileWeaponTypes.EMP, 6); ship.NewRoomSystem(new Vector2F(1, 0), new Vector2F(2, 1), Ship.SystemTypes.Maneuver); ship.NewRoomSystem(new Vector2F(1, 1), new Vector2F(2, 1), Ship.SystemTypes.BeamWeapons); ship.NewRoom(new Vector2F(2, 2), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(0, 3), new Vector2F(1, 2), Ship.SystemTypes.RearShield); ship.NewRoomSystem(new Vector2F(1, 3), new Vector2F(2, 2), Ship.SystemTypes.Reactor); ship.NewRoomSystem(new Vector2F(3, 3), new Vector2F(2, 2), Ship.SystemTypes.WarpDrive); ship.NewRoomSystem(new Vector2F(5, 3), new Vector2F(1, 2), Ship.SystemTypes.JumpDrive); ship.NewRoom(new Vector2F(6, 3), new Vector2F(2, 1)); ship.NewRoom(new Vector2F(6, 4), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(8, 3), new Vector2F(1, 2), Ship.SystemTypes.FrontShield); ship.NewRoom(new Vector2F(2, 5), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(1, 6), new Vector2F(2, 1), Ship.SystemTypes.MissileSystem); ship.NewRoomSystem(new Vector2F(1, 7), new Vector2F(2, 1), Ship.SystemTypes.Impulse); ship.NewDoor(new Vector2F(1, 1), true); ship.NewDoor(new Vector2F(2, 2), true); ship.NewDoor(new Vector2F(3, 3), true); ship.NewDoor(new Vector2F(1, 3), false); ship.NewDoor(new Vector2F(3, 4), false); ship.NewDoor(new Vector2F(3, 5), true); ship.NewDoor(new Vector2F(2, 6), true); ship.NewDoor(new Vector2F(1, 7), true); ship.NewDoor(new Vector2F(5, 3), false); ship.NewDoor(new Vector2F(6, 3), false); ship.NewDoor(new Vector2F(6, 4), false); ship.NewDoor(new Vector2F(8, 3), false); ship.NewDoor(new Vector2F(8, 4), false); ship.SetScienceItemFields(item); } void SetupPlayerMissileCruiser(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Missile Cruiser"); item.AddDescriptionLine("Fabricated by: Various Faction Navies"); item.AddDescriptionLine("The missile cruiser is a patrol ship employed by numerous governments."); item.AddDescriptionLine("The ships are generally outfitted with a larger compliment of missile weapons for long range operations"); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "space_cruiser_4"; ship.AddMissileTubes(4, 8.0f); ship.Hull = 200; ship.FrontShields = 110; ship.RearShields = 70; ship.SublightSpeed = 60; ship.RotatonSpeed = 8; ship.SublightAcceleration = 15; ship.FTLType = UseWarp ? Ship.FTLTypes.WarpDrive : Ship.FTLTypes.JumpDrive; ship.FTLLimit = 800; ship.CanCloak = false; ship.AddWeaponStores(MissileWeaponTypes.Homing, 30); ship.AddWeaponStores(MissileWeaponTypes.Nuke, 8); ship.AddWeaponStores(MissileWeaponTypes.Mine, 12); ship.AddWeaponStores(MissileWeaponTypes.EMP, 10); ship.NewRoomSystem(new Vector2F(1, 0), new Vector2F(2, 1), Ship.SystemTypes.Maneuver); ship.NewRoomSystem(new Vector2F(1, 1), new Vector2F(2, 1), Ship.SystemTypes.BeamWeapons); ship.NewRoom(new Vector2F(2, 2), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(0, 3), new Vector2F(1, 2), Ship.SystemTypes.RearShield); ship.NewRoomSystem(new Vector2F(1, 3), new Vector2F(2, 2), Ship.SystemTypes.Reactor); ship.NewRoomSystem(new Vector2F(3, 3), new Vector2F(2, 2), Ship.SystemTypes.WarpDrive); ship.NewRoomSystem(new Vector2F(5, 3), new Vector2F(1, 2), Ship.SystemTypes.JumpDrive); ship.NewRoom(new Vector2F(6, 3), new Vector2F(2, 1)); ship.NewRoom(new Vector2F(6, 4), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(8, 3), new Vector2F(1, 2), Ship.SystemTypes.FrontShield); ship.NewRoom(new Vector2F(2, 5), new Vector2F(2, 1)); ship.NewRoomSystem(new Vector2F(1, 6), new Vector2F(2, 1), Ship.SystemTypes.MissileSystem); ship.NewRoomSystem(new Vector2F(1, 7), new Vector2F(2, 1), Ship.SystemTypes.Impulse); ship.NewDoor(new Vector2F(1, 1), true); ship.NewDoor(new Vector2F(2, 2), true); ship.NewDoor(new Vector2F(3, 3), true); ship.NewDoor(new Vector2F(1, 3), false); ship.NewDoor(new Vector2F(3, 4), false); ship.NewDoor(new Vector2F(3, 5), true); ship.NewDoor(new Vector2F(2, 6), true); ship.NewDoor(new Vector2F(1, 7), true); ship.NewDoor(new Vector2F(5, 3), false); ship.NewDoor(new Vector2F(6, 3), false); ship.NewDoor(new Vector2F(6, 4), false); ship.NewDoor(new Vector2F(8, 3), false); ship.NewDoor(new Vector2F(8, 4), false); ship.SetScienceItemFields(item); } void SetupPlayerFighter(Ship.ShipTemplate ship, Campaign campaign) { var item = campaign.ScienceDB.New("Ships", "Snub Fighter"); item.AddDescriptionLine("Fabricated by: Various."); item.AddDescriptionLine("A small fighter class ship, generally attached to a larger ship or station."); item.AddDescriptionLine("Lightweight and poorly armored, these small ships rely on maneuverability to deliver weapon payloads to strategic locations on larger ships."); item.Known = true; ship.ScienceDBID = item.ID; ship.Model = "small_fighter_1"; ship.NewBeamWeapon(40, -10, 1000.0f, 6.0f, 8); ship.NewBeamWeapon(40, 10, 1000.0f, 6.0f, 8); ship.AddMissileTubes(1, 10.0f); ship.Hull = 60; ship.FrontShields = 40; ship.RearShields = 40; ship.SublightSpeed = 110; ship.RotatonSpeed = 20; ship.SublightAcceleration = 40; ship.FTLType = Ship.FTLTypes.None; ship.FTLLimit = 0; ship.CanCloak = false; ship.AddWeaponStores(MissileWeaponTypes.Homing, 4); ship.NewRoomSystem(new Vector2F(3, 0), new Vector2F(1, 1), Ship.SystemTypes.Maneuver); ship.NewRoomSystem(new Vector2F(1, 0), new Vector2F(2, 1), Ship.SystemTypes.BeamWeapons); ship.NewRoomSystem(new Vector2F(0, 1), new Vector2F(1, 2), Ship.SystemTypes.RearShield); ship.NewRoomSystem(new Vector2F(1, 1), new Vector2F(2, 2), Ship.SystemTypes.Reactor); ship.NewRoomSystem(new Vector2F(3, 1), new Vector2F(2, 1), Ship.SystemTypes.WarpDrive); ship.NewRoomSystem(new Vector2F(3, 2), new Vector2F(2, 1), Ship.SystemTypes.JumpDrive); ship.NewRoomSystem(new Vector2F(5, 1), new Vector2F(1, 2), Ship.SystemTypes.FrontShield); ship.NewRoomSystem(new Vector2F(1, 3), new Vector2F(2, 1), Ship.SystemTypes.MissileSystem); ship.NewRoomSystem(new Vector2F(3, 3), new Vector2F(1, 1), Ship.SystemTypes.Impulse); ship.NewDoor(new Vector2F(2, 1), true); ship.NewDoor(new Vector2F(3, 1), true); ship.NewDoor(new Vector2F(1, 1), false); ship.NewDoor(new Vector2F(3, 1), false); ship.NewDoor(new Vector2F(3, 2), false); ship.NewDoor(new Vector2F(3, 3), true); ship.NewDoor(new Vector2F(2, 3), true); ship.NewDoor(new Vector2F(5, 1), false); ship.NewDoor(new Vector2F(5, 2), false); ship.SetScienceItemFields(item); } } }
using System; using System.Linq; using Baseline; using Marten.Events; using Marten.Events.Projections; using Marten.Exceptions; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Events.Projections { [Collection("event_projections")] public class EventProjectionTests : OneOffConfigurationsContext { public EventProjectionTests() : base("event_projections") { theStore.Advanced.Clean.DeleteDocumentsByType(typeof(User)); } protected void UseProjection<T>() where T : EventProjection, new() { StoreOptions(x => x.Projections.Add(new T())); } [Fact] public void documents_created_by_event_projection_should_be_registered_as_document_types() { UseProjection<SimpleTransformProjectionUsingMetadata>(); // MyAggregate is the aggregate type for AllGood above theStore.Storage.AllDocumentMappings.Select(x => x.DocumentType) .ShouldContain(typeof(User)); } [Fact] public void use_simple_synchronous_project_methods() { UseProjection<SimpleProjection>(); var stream = Guid.NewGuid(); theSession.Events.StartStream(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); using var query = theStore.QuerySession(); query.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName) .ToList() .ShouldHaveTheSameElementsAs("one", "two"); theSession.Events.Append(stream, new UserDeleted {UserName = "one"}); theSession.SaveChanges(); query.Query<User>() .OrderBy(x => x.UserName) .Select(x => x.UserName) .Single() .ShouldBe("two"); } [Fact] public void use_simple_synchronous_project_methods_with_inline_lambdas() { UseProjection<LambdaProjection>(); var stream = Guid.NewGuid(); theSession.Events.StartStream(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); using var query = theStore.QuerySession(); query.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName) .ToList() .ShouldHaveTheSameElementsAs("one", "two"); theSession.Events.Append(stream, new UserDeleted {UserName = "one"}); theSession.SaveChanges(); query.Query<User>() .OrderBy(x => x.UserName) .Select(x => x.UserName) .Single() .ShouldBe("two"); } [Fact] public void synchronous_create_method() { UseProjection<SimpleCreatorProjection>(); var stream = Guid.NewGuid(); theSession.Events.StartStream(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); using var query = theStore.QuerySession(); query.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName) .ToList() .ShouldHaveTheSameElementsAs("one", "two"); theSession.Events.Append(stream, new UserDeleted {UserName = "one"}); theSession.SaveChanges(); query.Query<User>() .OrderBy(x => x.UserName) .Select(x => x.UserName) .Single() .ShouldBe("two"); } [Fact] public void use_event_metadata() { UseProjection<SimpleTransformProjectionUsingMetadata>(); var stream = Guid.NewGuid(); theSession.Events.Append(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); } [Fact] public void use_event_metadata_with_string_stream_identity() { StoreOptions(x => { x.Events.StreamIdentity = StreamIdentity.AsString; x.Projections.Add(new SimpleTransformProjectionUsingMetadata()); }); var stream = Guid.NewGuid().ToString(); theSession.Events.StartStream(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); theSession.Events.Append(stream, new UserCreated { UserName = "three" }); theSession.SaveChanges(); } [Fact] public void synchronous_with_transform_method() { UseProjection<SimpleTransformProjection>(); var stream = Guid.NewGuid(); theSession.Events.StartStream(stream, new UserCreated {UserName = "one"}, new UserCreated {UserName = "two"}); theSession.SaveChanges(); using var query = theStore.QuerySession(); query.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName) .ToList() .ShouldHaveTheSameElementsAs("one", "two"); theSession.Events.Append(stream, new UserDeleted {UserName = "one"}); theSession.SaveChanges(); query.Query<User>() .OrderBy(x => x.UserName) .Select(x => x.UserName) .Single() .ShouldBe("two"); } [Fact] public void empty_projection_throws_validation_error() { var projection = new EmptyProjection(); Should.Throw<InvalidProjectionException>(() => { projection.AssertValidity(); }); } } public class EmptyProjection : EventProjection{} public class SimpleProjection: EventProjection { public void Project(UserCreated @event, IDocumentOperations operations) => operations.Store(new User{UserName = @event.UserName}); public void Project(UserDeleted @event, IDocumentOperations operations) => operations.DeleteWhere<User>(x => x.UserName == @event.UserName); } public class SimpleTransformProjection: EventProjection { public User Transform(UserCreated @event) => new User{UserName = @event.UserName}; public void Project(UserDeleted @event, IDocumentOperations operations) => operations.DeleteWhere<User>(x => x.UserName == @event.UserName); } public class OtherCreationEvent : UserCreated { } public class SimpleTransformProjectionUsingMetadata : EventProjection { public User Transform(IEvent<UserCreated> @event) { if (@event.StreamId == Guid.Empty && @event.StreamKey.IsEmpty()) { throw new Exception("StreamKey and StreamId are both missing"); } return new User {UserName = @event.Data.UserName}; } public User Transform(IEvent<OtherCreationEvent> @event) { if (@event.StreamId == Guid.Empty && @event.StreamKey.IsEmpty()) { throw new Exception("StreamKey and StreamId are both missing"); } return new User {UserName = @event.Data.UserName}; } public void Project(UserDeleted @event, IDocumentOperations operations) => operations.DeleteWhere<User>(x => x.UserName == @event.UserName); } public class SimpleCreatorProjection: EventProjection { public User Create(UserCreated e) => new User {UserName = e.UserName}; public void Project(UserDeleted @event, IDocumentOperations operations) => operations.DeleteWhere<User>(x => x.UserName == @event.UserName); } #region sample_lambda_definition_of_event_projection public class LambdaProjection: EventProjection { public LambdaProjection() { Project<UserCreated>((e, ops) => ops.Store(new User {UserName = e.UserName})); Project<UserDeleted>((e, ops) => ops.DeleteWhere<User>(x => x.UserName == e.UserName)); } } #endregion public class UserCreated { public string UserName { get; set; } } public class UserDeleted { public string UserName { get; set; } } }
// <copyright file="SynchronizationContextInvokerBase.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Threading; using JetBrains.Annotations; namespace IX.StandardExtensions.ComponentModel; /// <summary> /// An abstract base class for a synchronization context invoker. /// </summary> /// <seealso cref="DisposableBase" /> [PublicAPI] public abstract partial class SynchronizationContextInvokerBase : DisposableBase, INotifyThreadException { #region Internal state private SynchronizationContext? synchronizationContext; #endregion #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="SynchronizationContextInvokerBase" /> class. /// </summary> protected SynchronizationContextInvokerBase() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="SynchronizationContextInvokerBase" /> class. /// </summary> /// <param name="synchronizationContext">The specific synchronization context to use.</param> protected SynchronizationContextInvokerBase(SynchronizationContext? synchronizationContext) { this.synchronizationContext = synchronizationContext; } #endregion #region Events /// <summary> /// Triggered when an exception has occurred on a different thread. /// </summary> public event EventHandler<ExceptionOccurredEventArgs>? ExceptionOccurredOnSeparateThread; #endregion #region Properties and indexers /// <summary> /// Gets the synchronization context used by this object, if any. /// </summary> /// <value>The synchronization context.</value> public SynchronizationContext? SynchronizationContext => this.synchronizationContext; #endregion #region Methods #region Disposable /// <summary> /// Disposes in the general (managed and unmanaged) context. /// </summary> protected override void DisposeGeneralContext() { Interlocked.Exchange( ref this.synchronizationContext, null); base.DisposeGeneralContext(); } #endregion /// <summary> /// Invokes the specified action using the synchronization context, or on either this thread or a separate thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> protected void Invoke(Action action) => this.Invoke( p => p(), action); /// <summary> /// Invokes the specified action using the synchronization context, or on either this thread or a separate thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> /// <param name="state">The state object to pass on to the action.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "Appears to be unavoidable at this time.")] protected void Invoke( Action<object> action, object state) { this.ThrowIfCurrentObjectDisposed(); Requires.NotNull( action); SynchronizationContext? currentSynchronizationContext = this.synchronizationContext ?? EnvironmentSettings.GetUsableSynchronizationContext(); if (currentSynchronizationContext == null) { if (EnvironmentSettings.InvokeAsynchronously) { _ = action.OnThreadPoolAsync(state); } else { action(state); } } else { var outerState = new Tuple<Action<object>, object>( action, state); if (EnvironmentSettings.InvokeAsynchronously) { currentSynchronizationContext.Post( this.SendOrPost, outerState); } else { currentSynchronizationContext.Send( this.SendOrPost, outerState); } } } /// <summary> /// Invokes the specified action by posting on the synchronization context, or on a separate thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> protected void InvokePost(Action action) => this.InvokePost( p => p(), action); /// <summary> /// Invokes the specified action by posting on the synchronization context, or on a separate thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> /// <param name="state">The state object to pass on to the action.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "Appears to be unavoidable at this time.")] protected void InvokePost( Action<object> action, object state) { this.ThrowIfCurrentObjectDisposed(); Requires.NotNull( action); SynchronizationContext? currentSynchronizationContext = this.synchronizationContext ?? EnvironmentSettings.GetUsableSynchronizationContext(); if (currentSynchronizationContext == null) { _ = action.OnThreadPoolAsync(state); } else { var outerState = new Tuple<Action<object>, object>( action, state); currentSynchronizationContext.Post( this.SendOrPost, outerState); } } /// <summary> /// Invokes the specified action synchronously using the synchronization context, or on this thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> protected void InvokeSend(Action action) => this.InvokeSend( p => p(), action); /// <summary> /// Invokes the specified action synchronously using the synchronization context, or on this thread if /// there is no synchronization context available. /// </summary> /// <param name="action">The action to invoke.</param> /// <param name="state">The state object to pass on to the action.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "Appears to be unavoidable at this time.")] protected void InvokeSend( Action<object> action, object state) { this.ThrowIfCurrentObjectDisposed(); Requires.NotNull( action); SynchronizationContext? currentSynchronizationContext = this.synchronizationContext ?? EnvironmentSettings.GetUsableSynchronizationContext(); if (currentSynchronizationContext == null) { action(state); } else { var outerState = new Tuple<Action<object>, object>( action, state); currentSynchronizationContext.Send( this.SendOrPost, outerState); } } /// <summary> /// Invokes the <see cref="ExceptionOccurredOnSeparateThread" /> event in a safe manner, while ignoring any processing /// exceptions. /// </summary> /// <param name="ex">The ex.</param> protected void InvokeExceptionOccurredOnSeparateThread(Exception ex) => this.ExceptionOccurredOnSeparateThread?.Invoke( this, new ExceptionOccurredEventArgs(ex)); [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We specifically do not want to do that.")] private void SendOrPost(object? innerState) { (Action<object> actionL1, object stateL1) = (Tuple<Action<object>, object>)Requires.NotNull(innerState); try { actionL1(stateL1); } catch (Exception ex) { this.InvokeExceptionOccurredOnSeparateThread(ex); } } #endregion }
#region Using Directives using System; using System.IO; using System.Windows.Forms; using System.Globalization; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework; using Microsoft.Practices.RecipeFramework.Library; using Microsoft.Practices.RecipeFramework.Services; using Microsoft.Practices.RecipeFramework.VisualStudio; using Microsoft.Practices.RecipeFramework.VisualStudio.Templates; using EnvDTE; #endregion namespace SPALM.SPSF.Library.Actions { /// <summary> /// Adds an item to the solution /// </summary> [ServiceDependency(typeof(DTE))] public class AddItemToProjectByName : ConfigurableAction { private string _SourceFileName = ""; private string content = ""; [Input(Required = false)] public string SourceFileName { get { return _SourceFileName; } set { _SourceFileName = value; } } [Input(Required = false)] public string Content { get { return this.content; } set { this.content = value; } } private string destFolder = String.Empty; [Input(Required = false)] public string TargetFolder { get { return destFolder; } set { destFolder = value; } } private string _TargetFileName = String.Empty; [Input(Required = false)] public string TargetFileName { get { return _TargetFileName; } set { _TargetFileName = value; } } private bool _Overwrite = false; [Input(Required = false)] public bool Overwrite { get { return _Overwrite; } set { _Overwrite = value; } } [Input(Required = true)] public string ProjectName { get { return this.projectName; } set { this.projectName = value; } } private string projectName; protected string GetBasePath() { return base.GetService<IConfigurationService>(true).BasePath; } private string GetTemplateBasePath() { return new DirectoryInfo(this.GetBasePath() + @"\Templates").FullName; } public override void Execute() { if (string.IsNullOrEmpty(Content)) { return; } DTE dte = base.GetService<DTE>(true); string fileWithContent = ""; string testcontent = Content.Trim(new char[]{' ','\t','\n','\r'}); if ((testcontent == "") || (testcontent == "dummy")) { //no content, check for sourcefile if (SourceFileName == null) { return; } if (SourceFileName == "") { return; } fileWithContent = this.SourceFileName; string templateBasePath = GetTemplateBasePath(); if (!Path.IsPathRooted(fileWithContent)) { fileWithContent = Path.Combine(templateBasePath, fileWithContent); fileWithContent = new FileInfo(fileWithContent).FullName; } } else { fileWithContent = Path.GetTempFileName(); using (StreamWriter writer = new StreamWriter(fileWithContent, false)) { writer.Write(content); writer.Close(); } } if ((TargetFileName == null) || (TargetFileName == "")) { if (File.Exists(fileWithContent)) { TargetFileName = Path.GetFileName(fileWithContent); } } Project projectByName = Helpers.GetProjectByName(dte, projectName); if (projectByName != null) { ProjectItems whereToAdd = projectByName.ProjectItems; //check if item exists ProjectItem existingFile = null; try { existingFile = Helpers.GetProjectItemByName(whereToAdd, TargetFileName); } catch (Exception) { } if (existingFile != null && !Overwrite) { Helpers.LogMessage(dte, this, "File " + TargetFileName + " exists and will not be overwritten"); return; } //if targetfilename ends with .tt, we remove any file with the same start if (TargetFileName.EndsWith(".tt")) { //is there any file with the same name, but different extension foreach (ProjectItem pitem in whereToAdd) { if (Path.GetFileNameWithoutExtension(pitem.Name.ToUpper()) == Path.GetFileNameWithoutExtension(TargetFileName.ToUpper())) { string deletedFilepath = Helpers.GetFullPathOfProjectItem(pitem); //pHelpers.GetFullPathOfProjectItem(item); //delete the file pitem.Remove(); File.Delete(deletedFilepath); break; } } } ProjectItem _ProjectItem = Helpers.AddFromTemplate(whereToAdd, fileWithContent, this.TargetFileName); } else { //do nothing if project is not found //throw new Exception("Project with name " + projectName + " not found in solution"); } } /// <summary> /// Removes the previously added reference, if it was created /// </summary> public override void Undo() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Win32; using Internal.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System.Runtime.InteropServices { /// <summary> /// This class contains methods that are mainly used to marshal between unmanaged /// and managed types. /// </summary> public static partial class Marshal { /// <summary> /// The default character size for the system. This is always 2 because /// the framework only runs on UTF-16 systems. /// </summary> public static readonly int SystemDefaultCharSize = 2; /// <summary> /// The max DBCS character size for the system. /// </summary> public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize(); public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb); public static unsafe string PtrToStringAnsi(IntPtr ptr) { if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { return null; } return new string((sbyte*)ptr); } public static unsafe string PtrToStringAnsi(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException(nameof(ptr)); } if (len < 0) { throw new ArgumentException(null, nameof(len)); } return new string((sbyte*)ptr, 0, len); } public static unsafe string PtrToStringUni(IntPtr ptr) { if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { return null; } return new string((char*)ptr); } public static unsafe string PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException(nameof(ptr)); } if (len < 0) { throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(len)); } return new string((char*)ptr, 0, len); } public static string PtrToStringAuto(IntPtr ptr, int len) { // Ansi platforms are no longer supported return PtrToStringUni(ptr, len); } public static string PtrToStringAuto(IntPtr ptr) { // Ansi platforms are no longer supported return PtrToStringUni(ptr); } public static unsafe string PtrToStringUTF8(IntPtr ptr) { if (ptr == IntPtr.Zero) { return null; } int nbBytes = string.strlen((byte*)ptr); return string.CreateStringFromEncoding((byte*)ptr, nbBytes, Encoding.UTF8); } public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) { if (byteLen < 0) { throw new ArgumentOutOfRangeException(nameof(byteLen), SR.ArgumentOutOfRange_NeedNonNegNum); } if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { return null; } return string.CreateStringFromEncoding((byte*)ptr, byteLen, Encoding.UTF8); } public static int SizeOf(object structure) { if (structure == null) { throw new ArgumentNullException(nameof(structure)); } return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } public static int SizeOf<T>(T structure) { if (structure == null) { throw new ArgumentNullException(nameof(structure)); } return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } public static int SizeOf(Type t) { if (t == null) { throw new ArgumentNullException(nameof(t)); } if (!t.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); } if (t.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); } return SizeOfHelper(t, throwIfNotMarshalable: true); } public static int SizeOf<T>() => SizeOf(typeof(T)); /// <summary> /// IMPORTANT NOTICE: This method does not do any verification on the array. /// It must be used with EXTREME CAUTION since passing in invalid index or /// an array that is not pinned can cause unexpected results. /// </summary> public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { if (arr == null) throw new ArgumentNullException(nameof(arr)); void* pRawData = Unsafe.AsPointer(ref arr.GetRawArrayData()); return (IntPtr)((byte*)pRawData + (uint)index * (nuint)arr.GetElementSize()); } public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { if (arr == null) throw new ArgumentNullException(nameof(arr)); void* pRawData = Unsafe.AsPointer(ref arr.GetRawSzArrayData()); return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf<T>()); } public static IntPtr OffsetOf<T>(string fieldName) => OffsetOf(typeof(T), fieldName); public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } private static unsafe void CopyToNative<T>(T[] source, int startIndex, IntPtr destination, int length) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == IntPtr.Zero) throw new ArgumentNullException(nameof(destination)); // The rest of the argument validation is done by CopyTo new Span<T>(source, startIndex, length).CopyTo(new Span<T>((void*)destination, length)); } public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } private static unsafe void CopyToManaged<T>(IntPtr source, T[] destination, int startIndex, int length) { if (source == IntPtr.Zero) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); // The rest of the argument validation is done by CopyTo new Span<T>((void*)source, length).CopyTo(new Span<T>(destination, startIndex, length)); } public static unsafe byte ReadByte(IntPtr ptr, int ofs) { try { byte* addr = (byte*)ptr + ofs; return *addr; } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static byte ReadByte(IntPtr ptr) => ReadByte(ptr, 0); public static unsafe short ReadInt16(IntPtr ptr, int ofs) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned read return *((short*)addr); } else { return Unsafe.ReadUnaligned<short>(addr); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static short ReadInt16(IntPtr ptr) => ReadInt16(ptr, 0); public static unsafe int ReadInt32(IntPtr ptr, int ofs) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned read return *((int*)addr); } else { return Unsafe.ReadUnaligned<int>(addr); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static int ReadInt32(IntPtr ptr) => ReadInt32(ptr, 0); public static IntPtr ReadIntPtr(object ptr, int ofs) { #if BIT64 return (IntPtr)ReadInt64(ptr, ofs); #else // 32 return (IntPtr)ReadInt32(ptr, ofs); #endif } public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { #if BIT64 return (IntPtr)ReadInt64(ptr, ofs); #else // 32 return (IntPtr)ReadInt32(ptr, ofs); #endif } public static IntPtr ReadIntPtr(IntPtr ptr) => ReadIntPtr(ptr, 0); public static unsafe long ReadInt64(IntPtr ptr, int ofs) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned read return *((long*)addr); } else { return Unsafe.ReadUnaligned<long>(addr); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static long ReadInt64(IntPtr ptr) => ReadInt64(ptr, 0); public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val) { try { byte* addr = (byte*)ptr + ofs; *addr = val; } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static void WriteByte(IntPtr ptr, byte val) => WriteByte(ptr, 0, val); public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned write *((short*)addr) = val; } else { Unsafe.WriteUnaligned(addr, val); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static void WriteInt16(IntPtr ptr, short val) => WriteInt16(ptr, 0, val); public static void WriteInt16(IntPtr ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val); public static void WriteInt16([In, Out]object ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val); public static void WriteInt16(IntPtr ptr, char val) => WriteInt16(ptr, 0, (short)val); public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned write *((int*)addr) = val; } else { Unsafe.WriteUnaligned(addr, val); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static void WriteInt32(IntPtr ptr, int val) => WriteInt32(ptr, 0, val); public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { #if BIT64 WriteInt64(ptr, ofs, (long)val); #else // 32 WriteInt32(ptr, ofs, (int)val); #endif } public static void WriteIntPtr(object ptr, int ofs, IntPtr val) { #if BIT64 WriteInt64(ptr, ofs, (long)val); #else // 32 WriteInt32(ptr, ofs, (int)val); #endif } public static void WriteIntPtr(IntPtr ptr, IntPtr val) => WriteIntPtr(ptr, 0, val); public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) { try { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned write *((long*)addr) = val; } else { Unsafe.WriteUnaligned(addr, val); } } catch (NullReferenceException) { // this method is documented to throw AccessViolationException on any AV throw new AccessViolationException(); } } public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val); public static void Prelink(MethodInfo m) { if (m == null) { throw new ArgumentNullException(nameof(m)); } PrelinkCore(m); } public static void PrelinkAll(Type c) { if (c == null) { throw new ArgumentNullException(nameof(c)); } MethodInfo[] mi = c.GetMethods(); if (mi != null) { for (int i = 0; i < mi.Length; i++) { Prelink(mi[i]); } } } public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld) { StructureToPtr((object)structure, ptr, fDeleteOld); } /// <summary> /// Creates a new instance of "structuretype" and marshals data from a /// native memory block to it. /// </summary> public static object PtrToStructure(IntPtr ptr, Type structureType) { if (ptr == IntPtr.Zero) { return null; } if (structureType == null) { throw new ArgumentNullException(nameof(structureType)); } if (structureType.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType)); } if (!structureType.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(structureType)); } return PtrToStructureHelper(ptr, structureType); } /// <summary> /// Marshals data from a native memory block to a preallocated structure class. /// </summary> public static void PtrToStructure(IntPtr ptr, object structure) { PtrToStructureHelper(ptr, structure, allowValueClasses: false); } public static void PtrToStructure<T>(IntPtr ptr, T structure) { PtrToStructure(ptr, (object)structure); } public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T)); public static void DestroyStructure<T>(IntPtr ptr) => DestroyStructure(ptr, typeof(T)); /// <summary> /// Converts the HRESULT to a CLR exception. /// </summary> public static Exception GetExceptionForHR(int errorCode) => GetExceptionForHR(errorCode, IntPtr.Zero); public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode >= 0) { return null; } return GetExceptionForHRInternal(errorCode, errorInfo); } /// <summary> /// Throws a CLR exception based on the HRESULT. /// </summary> public static void ThrowExceptionForHR(int errorCode) { if (errorCode < 0) { throw GetExceptionForHR(errorCode, IntPtr.Zero); } } public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) { throw GetExceptionForHR(errorCode, errorInfo); } } public static IntPtr SecureStringToBSTR(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return s.MarshalToBSTR(); } public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return s.MarshalToString(globalAlloc: false, unicode: false); } public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return s.MarshalToString(globalAlloc: false, unicode: true); } public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return s.MarshalToString(globalAlloc: true, unicode: false); } public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } return s.MarshalToString(globalAlloc: true, unicode: true); ; } public static unsafe IntPtr StringToHGlobalAnsi(string s) { if (s == null) { return IntPtr.Zero; } long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize; int nb = (int)lnb; // Overflow checking if (nb != lnb) { throw new ArgumentOutOfRangeException(nameof(s)); } IntPtr hglobal = AllocHGlobal((IntPtr)nb); StringToAnsiString(s, (byte*)hglobal, nb); return hglobal; } public static unsafe IntPtr StringToHGlobalUni(string s) { if (s == null) { return IntPtr.Zero; } int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) { throw new ArgumentOutOfRangeException(nameof(s)); } IntPtr hglobal = AllocHGlobal((IntPtr)nb); fixed (char* firstChar = s) { string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); } return hglobal; } public static IntPtr StringToHGlobalAuto(string s) { // Ansi platforms are no longer supported return StringToHGlobalUni(s); } public static unsafe IntPtr StringToCoTaskMemUni(string s) { if (s == null) { return IntPtr.Zero; } int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) { throw new ArgumentOutOfRangeException(nameof(s)); } IntPtr hglobal = AllocCoTaskMem(nb); fixed (char* firstChar = s) { string.wstrcpy((char*)hglobal, firstChar, s.Length + 1); } return hglobal; } public static unsafe IntPtr StringToCoTaskMemUTF8(string s) { if (s == null) { return IntPtr.Zero; } int nb = Encoding.UTF8.GetMaxByteCount(s.Length); IntPtr pMem = AllocCoTaskMem(nb + 1); int nbWritten; byte* pbMem = (byte*)pMem; fixed (char* firstChar = s) { nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb); } pbMem[nbWritten] = 0; return pMem; } public static IntPtr StringToCoTaskMemAuto(string s) { // Ansi platforms are no longer supported return StringToCoTaskMemUni(s); } public static unsafe IntPtr StringToCoTaskMemAnsi(string s) { if (s == null) { return IntPtr.Zero; } long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize; int nb = (int)lnb; // Overflow checking if (nb != lnb) { throw new ArgumentOutOfRangeException(nameof(s)); } IntPtr hglobal = AllocCoTaskMem(nb); StringToAnsiString(s, (byte*)hglobal, nb); return hglobal; } /// <summary> /// Generates a GUID for the specified type. If the type has a GUID in the /// metadata then it is returned otherwise a stable guid is generated based /// on the fully qualified name of the type. /// </summary> public static Guid GenerateGuidForType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (!type.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); } return type.GUID; } /// <summary> /// This method generates a PROGID for the specified type. If the type has /// a PROGID in the metadata then it is returned otherwise a stable PROGID /// is generated based on the fully qualified name of the type. /// </summary> public static string GenerateProgIdForType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsImport) { throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type)); } if (type.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); } ProgIdAttribute progIdAttribute = type.GetCustomAttribute<ProgIdAttribute>(); if (progIdAttribute != null) { return progIdAttribute.Value ?? string.Empty; } // If there is no prog ID attribute then use the full name of the type as the prog id. return type.FullName; } public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException(nameof(ptr)); } if (t == null) { throw new ArgumentNullException(nameof(t)); } if (!t.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); } if (t.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); } Type c = t.BaseType; if (c != typeof(Delegate) && c != typeof(MulticastDelegate)) { throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t)); } return GetDelegateForFunctionPointerInternal(ptr, t); } public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr) { return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate)); } public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) { throw new ArgumentNullException(nameof(d)); } return GetFunctionPointerForDelegateInternal(d); } public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { return GetFunctionPointerForDelegate((Delegate)(object)d); } public static int GetHRForLastWin32Error() { int dwLastError = GetLastWin32Error(); if ((dwLastError & 0x80000000) == 0x80000000) { return dwLastError; } return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } public static IntPtr /* IDispatch */ GetIDispatchForObject(object o) => throw new PlatformNotSupportedException(); public static void ZeroFreeBSTR(IntPtr s) { if (s == IntPtr.Zero) { return; } RuntimeImports.RhZeroMemory(s, (UIntPtr)SysStringByteLen(s)); FreeBSTR(s); } public unsafe static void ZeroFreeCoTaskMemAnsi(IntPtr s) { ZeroFreeCoTaskMemUTF8(s); } public static unsafe void ZeroFreeCoTaskMemUnicode(IntPtr s) { if (s == IntPtr.Zero) { return; } RuntimeImports.RhZeroMemory(s, (UIntPtr)(string.wcslen((char*)s) * 2)); FreeCoTaskMem(s); } public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s) { if (s == IntPtr.Zero) { return; } RuntimeImports.RhZeroMemory(s, (UIntPtr)string.strlen((byte*)s)); FreeCoTaskMem(s); } public unsafe static void ZeroFreeGlobalAllocAnsi(IntPtr s) { if (s == IntPtr.Zero) { return; } RuntimeImports.RhZeroMemory(s, (UIntPtr)string.strlen((byte*)s)); FreeHGlobal(s); } public static unsafe void ZeroFreeGlobalAllocUnicode(IntPtr s) { if (s == IntPtr.Zero) { return; } RuntimeImports.RhZeroMemory(s, (UIntPtr)(string.wcslen((char*)s) * 2)); FreeHGlobal(s); } internal static unsafe uint SysStringByteLen(IntPtr s) { return *(((uint*)s) - 1); } } }
// <copyright file="IEnumerableExtensions.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using IX.StandardExtensions.Contracts; using JetBrains.Annotations; namespace IX.StandardExtensions.Extensions; /// <summary> /// Extensions for IEnumerable. /// </summary> [PublicAPI] [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "These are extensions for IEnumerable, so we must allow this.")] [SuppressMessage( "ReSharper", "InconsistentNaming", Justification = "These are extensions for IEnumerable, so we must allow this.")] public static partial class IEnumerableExtensions { #region Methods #region Static methods /// <summary> /// Executes an action in sequence with an iterator. /// </summary> /// <typeparam name="T">The enumerable type.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public static void For<T>( this IEnumerable<T> source, Action<int, T> action) { Requires.NotNull(source); Requires.NotNull(action); var i = 0; foreach (T item in source) { action( i, item); i++; } } /// <summary> /// Executes an action in sequence with an iterator. /// </summary> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public static void For( this IEnumerable source, Action<int, object> action) { Requires.NotNull(source); Requires.NotNull(action); var i = 0; foreach (var item in source) { action( i, item); i++; } } /// <summary> /// Executes an action for each one of the elements of an enumerable. /// </summary> /// <typeparam name="T">The enumerable type.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public static void ForEach<T>( this IEnumerable<T> source, Action<T> action) { Requires.NotNull(source); Requires.NotNull(action); foreach (T item in source) { action(item); } } /// <summary> /// Executes an action for each one of the elements of an enumerable. /// </summary> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public static void ForEach( this IEnumerable source, Action<object> action) { Requires.NotNull(source); Requires.NotNull(action); foreach (var item in source) { action(item); } } /// <summary> /// Executes an independent action in parallel, with an iterator that respects the original sequence. /// </summary> /// <typeparam name="T">The enumerable type.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is acceptable.")] public static void ParallelFor<T>( this IEnumerable<T> source, Action<int, T> action) { Requires.NotNull(source); Requires.NotNull(action); Parallel.ForEach( EnumerateWithIndex( source, action), PerformParallelAction); static IEnumerable<(int Index, T Item, Action<int, T> Action)> EnumerateWithIndex( IEnumerable<T> sourceEnumerable, Action<int, T> actionToPerform) { var i = 0; foreach (T item in sourceEnumerable) { yield return (i, item, actionToPerform); i++; } } static void PerformParallelAction((int Index, T Item, Action<int, T> Action) state) { state.Action( state.Index, state.Item); } } /// <summary> /// Executes an independent action for each one of the elements of an enumerable, in parallel. /// </summary> /// <typeparam name="T">The enumerable type.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public static void ParallelForEach<T>( this IEnumerable<T> source, Action<T> action) { Requires.NotNull(source); Requires.NotNull(action); Parallel.ForEach( source, action); } #endregion #endregion }
using System; using System.Globalization; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using UnitTests.GrainInterfaces; using UnitTests.Tester; using System.Collections.Generic; using TestGrainInterfaces; using Xunit; using Tester; using System.Linq; namespace UnitTests.General { /// <summary> /// Unit tests for grains implementing generic interfaces /// </summary> public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted { private static int grainId = 0; public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey { return GrainFactory.GetGrain<TGrainInterface>(i); } public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey { return GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId()); } /// Can instantiate multiple concrete grain types that implement /// different specializations of the same generic interface [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain() { var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>(); var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>(); var grainOfFloatString = GetGrain<IGenericGrain<float, string>>(); await grainOfIntFloat1.SetT(123); await grainOfIntFloat2.SetT(456); await grainOfFloatString.SetT(789.0f); var floatResult1 = await grainOfIntFloat1.MapT2U(); var floatResult2 = await grainOfIntFloat2.MapT2U(); var stringResult = await grainOfFloatString.MapT2U(); Assert.Equal(123f, floatResult1); Assert.Equal(456f, floatResult2); Assert.Equal("789", stringResult); } /// Multiple GetGrain requests with the same id return the same concrete grain [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId); await grainRef1.SetT(123); var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId); var floatResult = await grainRef2.MapT2U(); Assert.Equal(123f, floatResult); } /// Can instantiate generic grain specializations [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainGetGrain() { var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfString = GetGrain<ISimpleGenericGrain<string>>(); await grainOfFloat1.Set(1.2f); await grainOfFloat2.Set(3.4f); await grainOfString.Set("5.6"); // generic grain implementation does not change the set value: await grainOfFloat1.Transform(); await grainOfFloat2.Transform(); await grainOfString.Transform(); var floatResult1 = await grainOfFloat1.Get(); var floatResult2 = await grainOfFloat2.Get(); var stringResult = await grainOfString.Get(); Assert.Equal(1.2f, floatResult1); Assert.Equal(3.4f, floatResult2); Assert.Equal("5.6", stringResult); } /// Can instantiate grains that implement generic interfaces with generic type parameters [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain() { var grain = GetGrain<ISimpleGenericGrain<List<float>>>(); var list = new List<float>(); list.Add(0.1f); await grain.Set(list); var result = await grain.Get(); Assert.Equal(1, result.Count); Assert.Equal(0.1f, result[0]); } /// Multiple GetGrain requests with the same id return the same generic grain specialization [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId); await grainRef1.Set(1.2f); await grainRef1.Transform(); // NOP for generic grain class var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId); var floatResult = await grainRef2.Get(); Assert.Equal(1.2f, floatResult); } /// If both a concrete implementation and a generic implementation of a /// generic interface exist, prefer the concrete implementation. [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface() { var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>(); var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>(); await grainOfDouble1.Set(1.0); await grainOfDouble2.Set(2.0); // concrete implementation (SpecializedSimpleGenericGrain) doubles the set value: await grainOfDouble1.Transform(); await grainOfDouble2.Transform(); var result1 = await grainOfDouble1.Get(); var result2 = await grainOfDouble2.Get(); Assert.Equal(2.0, result1); Assert.Equal(4.0, result2); } /// Multiple GetGrain requests with the same id return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef1.Set(1.0); await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class // a second reference with the same id points to the same grain: var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(4.0f, floatResult); } /// Can instantiate concrete grains that implement multiple generic interfaces [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain() { var grain1 = GetGrain<ISimpleGenericGrain<int>>(); var grain2 = GetGrain<ISimpleGenericGrain<int>>(); await grain1.Set(1); await grain2.Set(2); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grain1.Transform(); await grain2.Transform(); var result1 = await grain1.Get(); var result2 = await grain2.Get(); Assert.Equal(10, result1); Assert.Equal(20, result2); } /// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grainRef1.Transform(); //A second reference to the interface will point to the same grain var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(100, floatResult); } /// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: // A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces // will reference the same grain: var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId); // ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10: var floatResult = await grainRef2.MapT2U(); Assert.Equal("100", floatResult); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GenericGrainTests_UseGenericFactoryInsideGrain() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId); await grainRef1.Set("JustString"); await grainRef1.CompareGrainReferences(grainRef1); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrain_GetGrain() { var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.SetA(a); await grain.SetB(b); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public void Generic_SimpleGrainControlFlow_Blocking() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); // explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases. grain.SetA(a).Wait(); grain.SetB(b).Wait(); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrainDataFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var setAPromise = grain.SetA(a); var setBPromise = grain.SetB(b); var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap(); var x = await stringPromise; Assert.Equal(expected, x); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrain2_GetGrain() { var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); await g1.GetA(); await g2.GetA(); await g3.GetA(); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain() { var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId()); await g1.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow2_GetAB() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); string r1 = await g1.GetAxB(a, b); string r2 = await g2.GetAxB(a, b); string r3 = await g3.GetAxB(a, b); Assert.Equal(expected, r1); Assert.Equal(expected, r2); Assert.Equal(expected, r3); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow3() { ISimpleGenericGrain2<int, float> g = GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_BasicGrainControlFlow() { IBasicGenericGrain<int, float> g = GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GrainWithListFields() { string a = random.Next(100).ToString(CultureInfo.InvariantCulture); string b = random.Next(100).ToString(CultureInfo.InvariantCulture); var g1 = GrainFactory.GetGrain<IGrainWithListFields>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_GrainWithListFields() { int a = random.Next(100); int b = random.Next(100); var g1 = GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; var g1 = GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; long grainId = GetRandomGrainId(); var g1 = GrainFactory.GetGrain<IGrainWithNoProperties>(grainId); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain1() { int a = random.Next(100); var g = GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++); await g.SetValue(a); var res = await g.GetValue(); Assert.Equal(a, res); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain2() { int a = random.Next(100); string b = "bbbbb"; var g = GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain3() { int a = random.Next(100); string b = "bbbbb"; double c = 3.145; var g = GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); await g.SetValue3(c); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); var r3 = await g.GetValue3(); Assert.Equal(c, r3); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Non_Primitive_Type_Argument() { IEchoHubGrain<Guid, string> g1 = GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1); IEchoHubGrain<Guid, int> g2 = GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1); IEchoHubGrain<Guid, byte[]> g3 = GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1); Assert.NotEqual((GrainReference)g1, (GrainReference)g2); Assert.NotEqual((GrainReference)g1, (GrainReference)g3); Assert.NotEqual((GrainReference)g2, (GrainReference)g3); await g1.Foo(Guid.Empty, "", 1); await g2.Foo(Guid.Empty, 0, 2); await g3.Foo(Guid.Empty, new byte[] { }, 3); Assert.Equal(1, await g1.GetX()); Assert.Equal(2, await g2.GetX()); Assert.Equal(3m, await g3.GetX()); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_1() { const string msg1 = "Hello from EchoGenericChainGrain-1"; IEchoGenericChainGrain<string> g1 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g1.Echo(msg1); Assert.Equal(msg1, received); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_2() { const string msg2 = "Hello from EchoGenericChainGrain-2"; IEchoGenericChainGrain<string> g2 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g2.Echo2(msg2); Assert.Equal(msg2, received); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_3() { const string msg3 = "Hello from EchoGenericChainGrain-3"; IEchoGenericChainGrain<string> g3 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g3.Echo3(msg3); Assert.Equal(msg3, received); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_4() { const string msg4 = "Hello from EchoGenericChainGrain-4"; var g4 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g4.Echo4(msg4); Assert.Equal(msg4, received); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_5() { const string msg5 = "Hello from EchoGenericChainGrain-5"; var g5 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g5.Echo5(msg5); Assert.Equal(msg5, received); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_Echo_Chain_6() { const string msg6 = "Hello from EchoGenericChainGrain-6"; var g6 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g6.Echo6(msg6); Assert.Equal(msg6, received); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallOnly() { var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_1Argument_NonGenericCallFirst() { var id = Guid.NewGuid(); var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallFirst() { var id = Guid.NewGuid(); var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("Functional"), TestCategory("Generics")] public async Task DifferentTypeArgsProduceIndependentActivations() { var grain1 = GrainFactory.GetGrain<IDbGrain<int>>(0); await grain1.SetValue(123); var grain2 = GrainFactory.GetGrain<IDbGrain<string>>(0); var v = await grain2.GetValue(); Assert.Null(v); } [Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelf() { var id = Guid.NewGuid(); var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelf(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelfThroughOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelfThroughOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("ActivateDeactivate")] public async Task Generic_ScheduleDelayedPingAndDeactivate() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5)); await Task.Delay(TimeSpan.FromSeconds(6)); var s2 = await grain.GetLastValue(); Assert.Equal(s1, s2); } [Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Serialization")] public async Task SerializationTests_Generic_CircularReferenceTest() { var grainId = Guid.NewGuid(); var grain = GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N")); var c1 = await grain.GetState(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")] public async Task Generic_GrainWithTypeConstraints() { var grainId = Guid.NewGuid().ToString(); var grain = GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId); var result = await grain.GetCount(); Assert.Equal(0, result); await grain.Add(42); result = await grain.GetCount(); Assert.Equal(1, result); } [Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToGenericInterfaceAfterActivation() { var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); await grain.DoSomething(); //activates original grain type here var castRef = grain.AsReference<ISomeGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal(result, "Hello!"); } [Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() { var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal(result, "Hello!"); } [Fact, TestCategory("Functional"), TestCategory("Cast")] public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() { var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGrain>(); var result = await castRef.Hello(); Assert.Equal(result, "Hello!"); } [Fact, TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() { var grain = GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid()); var castRef = grain.AsReference<INonGenericCastGrain>(); var result = await castRef.Hello(); Assert.Equal(result, "Hello!"); } } namespace Generic.EdgeCases { using UnitTests.GrainInterfaces.Generic.EdgeCases; public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted { static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) { var genArgTypeNames = await @this.ConcreteGenArgTypeNames(); return genArgTypeNames.Select(n => Type.GetType(n)) .ToArray(); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() { var grain = GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() { //resolves correctly but can't be activated: too many gen args supplied for concrete class var grain = GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() { var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() { var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedRearrangedGenArgsResolved() { //again resolves to the correct generic type definition, but fails on activation as too many args //gen args aren't being properly inferred from matched concrete type var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() { var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>()) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() { var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() { //Only errors on invocation: wrong arity again var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() { var grain = GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() { var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() { var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal(response, "Hello!"); } //************************************************************************************************************** //************************************************************************************************************** //Below must be commented out, as supplying multiple fully-specified generic interfaces //to a class causes the codegen to fall over, stopping all other tests from working. //See new test here of the bit causing the issue - type info conflation: //UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly() //public interface IFullySpecifiedGenericInterface<T> : IBasicGrain //{ } //public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long> //{ } //public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface //{ } //[Fact, TestCategory("Generics")] //public async Task CastingBetweenFullySpecifiedGenericInterfaces() //{ // //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy // //codegen falling over: duplicate key when both specializations are matched to same concrete type // var grain = GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid()); // await grain.Hello(); // var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>(); // await castRef.Hello(); // var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>(); // await castRef2.Hello(); //} //******************************************************************************************************* [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() { var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() { var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecialized() { var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() { var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() { var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal(response, "Hello!"); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() { var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal(response, "Hello!"); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for OAuth authorizations. /// </summary> internal partial class OAuthOperations : IServiceOperations<DataFactoryManagementClient>, IOAuthOperations { /// <summary> /// Initializes a new instance of the OAuthOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal OAuthOperations(DataFactoryManagementClient client) { this._client = client; } private DataFactoryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient. /// </summary> public DataFactoryManagementClient Client { get { return this._client; } } /// <summary> /// Gets an OAuth authorization session. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='linkedServiceType'> /// Required. The type of OAuth linked service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get authorization session operation response. /// </returns> public async Task<AuthorizationSessionGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string linkedServiceType, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (linkedServiceType == null) { throw new ArgumentNullException("linkedServiceType"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceType", linkedServiceType); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/oauth/authorizationsession/"; url = url + Uri.EscapeDataString(linkedServiceType); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AuthorizationSessionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AuthorizationSessionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AuthorizationSession authorizationSessionInstance = new AuthorizationSession(); result.AuthorizationSession = authorizationSessionInstance; JToken endpointValue = responseDoc["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { Uri endpointInstance = TypeConversion.TryParseUri(((string)endpointValue)); authorizationSessionInstance.Endpoint = endpointInstance; } JToken sessionIdValue = responseDoc["sessionId"]; if (sessionIdValue != null && sessionIdValue.Type != JTokenType.Null) { string sessionIdInstance = ((string)sessionIdValue); authorizationSessionInstance.SessionId = sessionIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// -- FILE ------------------------------------------------------------------ // name : TimePeriodChainTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class TimePeriodChainTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void DefaultConstructorTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.Equal(0, timePeriods.Count); Assert.False( timePeriods.HasStart ); Assert.False( timePeriods.HasEnd ); Assert.False( timePeriods.IsReadOnly ); } // DefaultConstructorTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void CopyConstructorTest() { SchoolDay schoolDay = new SchoolDay(); TimePeriodChain timePeriods = new TimePeriodChain( schoolDay ); Assert.Equal( timePeriods.Count, schoolDay.Count ); Assert.True( timePeriods.HasStart ); Assert.True( timePeriods.HasEnd ); Assert.False( timePeriods.IsReadOnly ); Assert.Equal( timePeriods.Start, schoolDay.Start ); } // CopyConstructorTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void FirstTest() { SchoolDay schoolDay = new SchoolDay(); Assert.Equal( schoolDay.First, schoolDay.Lesson1 ); } // FirstTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void LastTest() { SchoolDay schoolDay = new SchoolDay(); Assert.Equal( schoolDay.Last, schoolDay.Lesson4 ); } // LastTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void CountTest() { Assert.Equal(0, new TimePeriodChain().Count); Assert.Equal(7, new SchoolDay().Count); } // CountTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void ItemIndexTest() { SchoolDay schoolDay = new SchoolDay(); Assert.Equal( schoolDay[ 0 ], schoolDay.Lesson1 ); Assert.Equal( schoolDay[ 1 ], schoolDay.Break1 ); Assert.Equal( schoolDay[ 2 ], schoolDay.Lesson2 ); Assert.Equal( schoolDay[ 3 ], schoolDay.Break2 ); Assert.Equal( schoolDay[ 4 ], schoolDay.Lesson3 ); Assert.Equal( schoolDay[ 5 ], schoolDay.Break3 ); Assert.Equal( schoolDay[ 6 ], schoolDay.Lesson4 ); } // ItemIndexTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void IsAnytimeTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodChain timePeriods = new TimePeriodChain(); Assert.True( timePeriods.IsAnytime ); timePeriods.Add( new TimeBlock( TimeSpec.MinPeriodDate, now ) ); Assert.False( timePeriods.IsAnytime ); timePeriods.Add( new TimeBlock( now, TimeSpec.MaxPeriodDate ) ); Assert.True( timePeriods.IsAnytime ); } // IsAnytimeTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void IsMomentTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodChain timePeriods = new TimePeriodChain(); Assert.False( timePeriods.IsMoment ); timePeriods.Add( new TimeBlock( now ) ); Assert.Equal(1, timePeriods.Count); Assert.True( timePeriods.HasStart ); Assert.True( timePeriods.HasEnd ); Assert.True( timePeriods.IsMoment ); timePeriods.Add( new TimeBlock( now ) ); Assert.Equal(2, timePeriods.Count); Assert.True( timePeriods.HasStart ); Assert.True( timePeriods.HasEnd ); Assert.True( timePeriods.IsMoment ); } // IsMomentTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void HasStartTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.False( timePeriods.HasStart ); timePeriods.Add( new TimeBlock( TimeSpec.MinPeriodDate, Duration.Hour ) ); Assert.False( timePeriods.HasStart ); timePeriods.Clear(); timePeriods.Add( new TimeBlock( ClockProxy.Clock.Now, Duration.Hour ) ); Assert.True( timePeriods.HasStart ); } // HasStartTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void StartTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodChain timePeriods = new TimePeriodChain(); Assert.Equal( timePeriods.Start, TimeSpec.MinPeriodDate ); timePeriods.Add( new TimeBlock( now, Duration.Hour ) ); Assert.Equal( timePeriods.Start, now ); timePeriods.Clear(); Assert.Equal( timePeriods.Start, TimeSpec.MinPeriodDate ); } // StartTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void StartMoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); Assert.Equal( schoolDay.Start, now ); schoolDay.Start = now.AddHours( 0 ); Assert.Equal( schoolDay.Start, now ); schoolDay.Start = now.AddHours( 1 ); Assert.Equal( schoolDay.Start, now.AddHours( 1 ) ); schoolDay.Start = now.AddHours( -1 ); Assert.Equal( schoolDay.Start, now.AddHours( -1 ) ); } // StartMoveTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void HasEndTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodChain timePeriods = new TimePeriodChain(); Assert.False( timePeriods.HasEnd ); timePeriods.Add( new TimeBlock( Duration.Hour, TimeSpec.MaxPeriodDate ) ); Assert.False( timePeriods.HasEnd ); timePeriods.Clear(); timePeriods.Add( new TimeBlock( now, Duration.Hour ) ); Assert.True( timePeriods.HasEnd ); } // HasEndTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void EndTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodChain timePeriods = new TimePeriodChain(); Assert.Equal( timePeriods.End, TimeSpec.MaxPeriodDate ); timePeriods.Add( new TimeBlock( Duration.Hour, now ) ); Assert.Equal( timePeriods.End, now ); timePeriods.Clear(); Assert.Equal( timePeriods.End, TimeSpec.MaxPeriodDate ); } // EndTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void EndMoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); DateTime end = schoolDay.End; schoolDay.End = end.AddHours( 0 ); Assert.Equal( schoolDay.End, end ); schoolDay.End = end.AddHours( 1 ); Assert.Equal( schoolDay.End, end.AddHours( 1 ) ); schoolDay.End = end.AddHours( -1 ); Assert.Equal( schoolDay.End, end.AddHours( -1 ) ); } // EndMoveTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void DurationTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.Equal( timePeriods.Duration, TimeSpec.MaxPeriodDuration ); TimeSpan duration = Duration.Hour; timePeriods.Add( new TimeBlock( ClockProxy.Clock.Now, duration ) ); Assert.Equal( timePeriods.Duration, duration ); } // DurationTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void MoveTest() { SchoolDay schoolDay = new SchoolDay(); DateTime startDate = schoolDay.Start; DateTime endDate = schoolDay.End; TimeSpan startDuration = schoolDay.Duration; TimeSpan duration = Duration.Hour; schoolDay.Move( duration ); Assert.Equal( schoolDay.Start, startDate.Add( duration ) ); Assert.Equal( schoolDay.End, endDate.Add( duration ) ); Assert.Equal( schoolDay.Duration, startDuration ); } // MoveTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void AddTest() { SchoolDay schoolDay = new SchoolDay(); int count = schoolDay.Count; DateTime end = schoolDay.End; ShortBreak shortBreak = new ShortBreak( schoolDay.Start ); schoolDay.Add( shortBreak ); Assert.Equal( schoolDay.Count, count + 1 ); Assert.Equal( schoolDay.Last, shortBreak ); Assert.Equal( schoolDay.End, end.Add( shortBreak.Duration ) ); Assert.Equal( shortBreak.Start, end ); Assert.Equal( shortBreak.End, schoolDay.End ); Assert.Equal( shortBreak.Duration, ShortBreak.ShortBreakDuration ); } // AddTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void AddTimeRangeTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodChain timePeriods = new TimePeriodChain( schoolDay ); TimeRange timeRange = new TimeRange( schoolDay.Lesson1.Start, schoolDay.Lesson1.End ); timePeriods.Add( timeRange ); Assert.Equal( timePeriods.Last, timeRange ); } // AddTimeRangeTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void ContainsPeriodTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodChain timePeriods = new TimePeriodChain( schoolDay ); TimeRange timeRange = new TimeRange( schoolDay.Lesson1.Start, schoolDay.Lesson1.End ); Assert.False( timePeriods.Contains( timeRange ) ); Assert.True( timePeriods.ContainsPeriod( timeRange ) ); } // ContainsPeriodTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void AddAllTest() { SchoolDay schoolDay = new SchoolDay(); int count = schoolDay.Count; TimeSpan duration = schoolDay.Duration; DateTime start = schoolDay.Start; schoolDay.AddAll( new SchoolDay() ); Assert.Equal( schoolDay.Count, count + count ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( schoolDay.Duration, duration + duration ); } // AddAllTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void AddReadOnlyTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.NotNull(Assert.Throws<NotSupportedException>( () => timePeriods.Add( new TimeRange( TimeSpec.MinPeriodDate, TimeSpec.MaxPeriodDate, true ) ) ) ); } // AddReadOnlyTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void InsertReadOnlyTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.NotNull(Assert.Throws<NotSupportedException>(() => timePeriods.Insert( 0, new TimeRange( TimeSpec.MinPeriodDate, TimeSpec.MaxPeriodDate, true ) ) ) ); } // InsertReadOnlyTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void InsertTest() { SchoolDay schoolDay = new SchoolDay(); // first int count = schoolDay.Count; DateTime start = schoolDay.Start; Lesson lesson1 = new Lesson( schoolDay.Start ); schoolDay.Insert( 0, lesson1 ); Assert.Equal( schoolDay.Count, count + 1 ); Assert.Equal( schoolDay[ 0 ], lesson1 ); Assert.Equal( schoolDay.First, lesson1 ); Assert.Equal( schoolDay.Start, start.Subtract( lesson1.Duration ) ); Assert.Equal( lesson1.Start, schoolDay.Start ); Assert.Equal( lesson1.End, start ); Assert.Equal( lesson1.Duration, Lesson.LessonDuration ); // inside count = schoolDay.Count; start = schoolDay.Start; ShortBreak shortBreak1 = new ShortBreak( schoolDay.Start ); schoolDay.Insert( 1, shortBreak1 ); Assert.Equal( schoolDay.Count, count + 1 ); Assert.Equal( schoolDay[ 1 ], shortBreak1 ); Assert.Equal( schoolDay.First, lesson1 ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( shortBreak1.Start, schoolDay.Start.Add( lesson1.Duration ) ); Assert.Equal( shortBreak1.Duration, ShortBreak.ShortBreakDuration ); // last count = schoolDay.Count; DateTime end = schoolDay.End; ShortBreak shortBreak2 = new ShortBreak( schoolDay.Start ); schoolDay.Insert( schoolDay.Count, shortBreak2 ); Assert.Equal( schoolDay.Count, count + 1 ); Assert.Equal( schoolDay[ count ], shortBreak2 ); Assert.Equal( schoolDay.Last, shortBreak2 ); Assert.Equal( schoolDay.End, shortBreak2.End ); Assert.Equal( shortBreak2.Start, end ); Assert.Equal( shortBreak2.Duration, ShortBreak.ShortBreakDuration ); } // InsertTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void InsertTimeRangeTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodChain timePeriods = new TimePeriodChain( schoolDay ); TimeRange timeRange = new TimeRange( schoolDay.Lesson1.Start, schoolDay.Lesson1.End ); timePeriods.Add( timeRange ); Assert.Equal( timePeriods.Last, timeRange ); } // InsertTimeRangeTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void ContainsTest() { SchoolDay schoolDay = new SchoolDay(); Assert.False( schoolDay.Contains( new TimeRange() ) ); Assert.False( schoolDay.Contains( new TimeBlock() ) ); Assert.True( schoolDay.Contains( schoolDay.Lesson1 ) ); Assert.True( schoolDay.Contains( schoolDay.Break1 ) ); Assert.True( schoolDay.Contains( schoolDay.Lesson2 ) ); Assert.True( schoolDay.Contains( schoolDay.Break2 ) ); Assert.True( schoolDay.Contains( schoolDay.Lesson3 ) ); Assert.True( schoolDay.Contains( schoolDay.Break3 ) ); Assert.True( schoolDay.Contains( schoolDay.Lesson4 ) ); schoolDay.Remove( schoolDay.Lesson1 ); Assert.False( schoolDay.Contains( schoolDay.Lesson1 ) ); } // ContainsTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void IndexOfTest() { SchoolDay schoolDay = new SchoolDay(); Assert.Equal( schoolDay.IndexOf( new TimeRange() ), -1 ); Assert.Equal( schoolDay.IndexOf( new TimeBlock() ), -1 ); Assert.Equal(0, schoolDay.IndexOf( schoolDay.Lesson1 )); Assert.Equal(1, schoolDay.IndexOf( schoolDay.Break1 )); Assert.Equal(2, schoolDay.IndexOf( schoolDay.Lesson2 )); Assert.Equal(3, schoolDay.IndexOf( schoolDay.Break2 )); Assert.Equal(4, schoolDay.IndexOf( schoolDay.Lesson3 )); Assert.Equal(5, schoolDay.IndexOf( schoolDay.Break3 )); Assert.Equal(6, schoolDay.IndexOf( schoolDay.Lesson4 )); schoolDay.Remove( schoolDay.Lesson1 ); Assert.Equal( schoolDay.IndexOf( schoolDay.Lesson1 ), -1 ); } // IndexOfTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void CopyToTest() { TimePeriodChain timePeriods = new TimePeriodChain(); ITimePeriod[] array1 = new ITimePeriod[ 0 ]; timePeriods.CopyTo( array1, 0 ); SchoolDay schoolDay = new SchoolDay(); ITimePeriod[] array2 = new ITimePeriod[ schoolDay.Count ]; schoolDay.CopyTo( array2, 0 ); Assert.Equal( array2[ 0 ], schoolDay.Lesson1 ); Assert.Equal( array2[ 1 ], schoolDay.Break1 ); Assert.Equal( array2[ 2 ], schoolDay.Lesson2 ); Assert.Equal( array2[ 3 ], schoolDay.Break2 ); Assert.Equal( array2[ 4 ], schoolDay.Lesson3 ); Assert.Equal( array2[ 5 ], schoolDay.Break3 ); Assert.Equal( array2[ 6 ], schoolDay.Lesson4 ); ITimePeriod[] array3 = new ITimePeriod[ schoolDay.Count + 3 ]; schoolDay.CopyTo( array3, 3 ); Assert.Equal( array3[ 3 ], schoolDay.Lesson1 ); Assert.Equal( array3[ 4 ], schoolDay.Break1 ); Assert.Equal( array3[ 5 ], schoolDay.Lesson2 ); Assert.Equal( array3[ 6 ], schoolDay.Break2 ); Assert.Equal( array3[ 7 ], schoolDay.Lesson3 ); Assert.Equal( array3[ 8 ], schoolDay.Break3 ); Assert.Equal( array3[ 9 ], schoolDay.Lesson4 ); } // CopyToTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void ClearTest() { TimePeriodChain timePeriods = new TimePeriodChain(); Assert.Equal(0, timePeriods.Count); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); SchoolDay schoolDay = new SchoolDay(); Assert.Equal(7, schoolDay.Count); schoolDay.Clear(); Assert.Equal(0, schoolDay.Count); } // ClearTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void RemoveTest() { SchoolDay schoolDay = new SchoolDay(); // first int count = schoolDay.Count; DateTime end = schoolDay.End; ITimePeriod removeItem = schoolDay.First; TimeSpan duration = schoolDay.Duration; schoolDay.Remove( removeItem ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay.First, removeItem ); Assert.Equal( schoolDay.End, end ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); // inside count = schoolDay.Count; duration = schoolDay.Duration; DateTime start = schoolDay.Start; ITimePeriod first = schoolDay.First; ITimePeriod last = schoolDay.Last; removeItem = schoolDay[ 1 ]; schoolDay.Remove( removeItem ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay[ 1 ], removeItem ); Assert.Equal( schoolDay.First, first ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( schoolDay.Last, last ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); // last count = schoolDay.Count; start = schoolDay.Start; duration = schoolDay.Duration; removeItem = schoolDay.Last; schoolDay.Remove( removeItem ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay.Last, removeItem ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); } // RemoveTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void RemoveAtTest() { SchoolDay schoolDay = new SchoolDay(); // first int count = schoolDay.Count; DateTime end = schoolDay.End; ITimePeriod removeItem = schoolDay[ 0 ]; TimeSpan duration = schoolDay.Duration; schoolDay.RemoveAt( 0 ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay[ 0 ], removeItem ); Assert.Equal( schoolDay.End, end ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); // inside count = schoolDay.Count; duration = schoolDay.Duration; DateTime start = schoolDay.Start; ITimePeriod first = schoolDay.First; ITimePeriod last = schoolDay.Last; removeItem = schoolDay[ 1 ]; schoolDay.RemoveAt( 1 ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay[ 1 ], removeItem ); Assert.Equal( schoolDay.First, first ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( schoolDay.Last, last ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); // last count = schoolDay.Count; start = schoolDay.Start; duration = schoolDay.Duration; removeItem = schoolDay[ schoolDay.Count - 1 ]; schoolDay.RemoveAt( schoolDay.Count - 1 ); Assert.Equal( schoolDay.Count, count - 1 ); Assert.NotEqual( schoolDay[ schoolDay.Count - 1 ], removeItem ); Assert.Equal( schoolDay.Start, start ); Assert.Equal( schoolDay.Duration, duration.Subtract( removeItem.Duration ) ); } // RemoveAtTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void IsSamePeriodTest() { SchoolDay schoolDay = new SchoolDay(); TimeRange manualRange = new TimeRange( schoolDay.Start, schoolDay.End ); Assert.True( schoolDay.IsSamePeriod( schoolDay ) ); Assert.True( schoolDay.IsSamePeriod( manualRange ) ); Assert.True( manualRange.IsSamePeriod( schoolDay ) ); Assert.False( schoolDay.IsSamePeriod( TimeBlock.Anytime ) ); Assert.False( manualRange.IsSamePeriod( TimeBlock.Anytime ) ); schoolDay.RemoveAt( 0 ); Assert.False( schoolDay.IsSamePeriod( manualRange ) ); Assert.False( manualRange.IsSamePeriod( schoolDay ) ); } // IsSamePeriodTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void HasInsideTest() { SchoolDay schoolDay = new SchoolDay(); TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( schoolDay.Start, schoolDay.End, offset ); Assert.False( schoolDay.HasInside( testData.Before ) ); Assert.False( schoolDay.HasInside( testData.StartTouching ) ); Assert.False( schoolDay.HasInside( testData.StartInside ) ); Assert.False( schoolDay.HasInside( testData.InsideStartTouching ) ); Assert.True( schoolDay.HasInside( testData.EnclosingStartTouching ) ); Assert.True( schoolDay.HasInside( testData.Enclosing ) ); Assert.True( schoolDay.HasInside( testData.ExactMatch ) ); Assert.True( schoolDay.HasInside( testData.EnclosingEndTouching ) ); Assert.False( schoolDay.HasInside( testData.Inside ) ); Assert.False( schoolDay.HasInside( testData.InsideEndTouching ) ); Assert.False( schoolDay.HasInside( testData.EndInside ) ); Assert.False( schoolDay.HasInside( testData.EndTouching ) ); Assert.False( schoolDay.HasInside( testData.After ) ); } // HasInsideTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void IntersectsWithTest() { SchoolDay schoolDay = new SchoolDay(); TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( schoolDay.Start, schoolDay.End, offset ); Assert.False( schoolDay.IntersectsWith( testData.Before ) ); Assert.True( schoolDay.IntersectsWith( testData.StartTouching ) ); Assert.True( schoolDay.IntersectsWith( testData.StartInside ) ); Assert.True( schoolDay.IntersectsWith( testData.InsideStartTouching ) ); Assert.True( schoolDay.IntersectsWith( testData.EnclosingStartTouching ) ); Assert.True( schoolDay.IntersectsWith( testData.Enclosing ) ); Assert.True( schoolDay.IntersectsWith( testData.EnclosingEndTouching ) ); Assert.True( schoolDay.IntersectsWith( testData.ExactMatch ) ); Assert.True( schoolDay.IntersectsWith( testData.Inside ) ); Assert.True( schoolDay.IntersectsWith( testData.InsideEndTouching ) ); Assert.True( schoolDay.IntersectsWith( testData.EndInside ) ); Assert.True( schoolDay.IntersectsWith( testData.EndTouching ) ); Assert.False( schoolDay.IntersectsWith( testData.After ) ); } // IntersectsWithTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void OverlapsWithTest() { SchoolDay schoolDay = new SchoolDay(); TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( schoolDay.Start, schoolDay.End, offset ); Assert.False( schoolDay.OverlapsWith( testData.Before ) ); Assert.False( schoolDay.OverlapsWith( testData.StartTouching ) ); Assert.True( schoolDay.OverlapsWith( testData.StartInside ) ); Assert.True( schoolDay.OverlapsWith( testData.InsideStartTouching ) ); Assert.True( schoolDay.OverlapsWith( testData.EnclosingStartTouching ) ); Assert.True( schoolDay.OverlapsWith( testData.Enclosing ) ); Assert.True( schoolDay.OverlapsWith( testData.EnclosingEndTouching ) ); Assert.True( schoolDay.OverlapsWith( testData.ExactMatch ) ); Assert.True( schoolDay.OverlapsWith( testData.Inside ) ); Assert.True( schoolDay.OverlapsWith( testData.InsideEndTouching ) ); Assert.True( schoolDay.OverlapsWith( testData.EndInside ) ); Assert.False( schoolDay.OverlapsWith( testData.EndTouching ) ); Assert.False( schoolDay.OverlapsWith( testData.After ) ); } // OverlapsWithTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodChain")] [Fact] public void GetRelationTest() { SchoolDay schoolDay = new SchoolDay(); TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( schoolDay.Start, schoolDay.End, offset ); Assert.Equal(PeriodRelation.Before, schoolDay.GetRelation( testData.Before )); Assert.Equal(PeriodRelation.StartTouching, schoolDay.GetRelation( testData.StartTouching )); Assert.Equal(PeriodRelation.StartInside, schoolDay.GetRelation( testData.StartInside )); Assert.Equal(PeriodRelation.InsideStartTouching, schoolDay.GetRelation( testData.InsideStartTouching )); Assert.Equal(PeriodRelation.EnclosingStartTouching, schoolDay.GetRelation( testData.EnclosingStartTouching )); Assert.Equal(PeriodRelation.Enclosing, schoolDay.GetRelation( testData.Enclosing )); Assert.Equal(PeriodRelation.EnclosingEndTouching, schoolDay.GetRelation( testData.EnclosingEndTouching )); Assert.Equal(PeriodRelation.ExactMatch, schoolDay.GetRelation( testData.ExactMatch )); Assert.Equal(PeriodRelation.Inside, schoolDay.GetRelation( testData.Inside )); Assert.Equal(PeriodRelation.InsideEndTouching, schoolDay.GetRelation( testData.InsideEndTouching )); Assert.Equal(PeriodRelation.EndInside, schoolDay.GetRelation( testData.EndInside )); Assert.Equal(PeriodRelation.EndTouching, schoolDay.GetRelation( testData.EndTouching )); Assert.Equal(PeriodRelation.After, schoolDay.GetRelation( testData.After )); } // GetRelationTest } // class TimePeriodChainTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
// // getline.cs: A command line editor // // Authors: // Miguel de Icaza (miguel@novell.com) // // Copyright 2008 Novell, Inc. // // Dual-licensed under the terms of the MIT X11 license or the // Apache License 2.0 // // USE -define:DEMO to build this as a standalone file and test it // // TODO: // Enter an error (a = 1); Notice how the prompt is in the wrong line // This is caused by Stderr not being tracked by System.Console. // Completion support // Why is Thread.Interrupt not working? Currently I resort to Abort which is too much. // // Limitations in System.Console: // Console needs SIGWINCH support of some sort // Console needs a way of updating its position after things have been written // behind its back (P/Invoke puts for example). // System.Console needs to get the DELETE character, and report accordingly. // #if NET_2_0 || NET_1_1 #define IN_MCS_BUILD #endif // Only compile this code in the 2.0 profile, but not in the Moonlight one #if (IN_MCS_BUILD && NET_2_0 && !SMCS_SOURCE) || !IN_MCS_BUILD using System; using System.Text; using System.IO; using System.Threading; using System.Reflection; namespace Mono.Terminal { public class LineEditor { public class Completion { public String[] _Result; public String _Prefix; public Completion (String myPrefix, String[] myResult) { _Prefix = myPrefix; _Result = myResult; } } public delegate Completion AutoCompleteHandler(String myText, Int32 myPosition); //static StreamWriter log; // The text being edited. StringBuilder text; // The text as it is rendered (replaces (char)1 with ^A on display for example). StringBuilder rendered_text; // The prompt specified, and the prompt shown to the user. String prompt; String shown_prompt; // The current cursor position, indexes into "text", for an index // into rendered_text, use TextToRenderPos Int32 cursor; // The row where we started displaying data. Int32 home_row; // The maximum length that has been displayed on the screen Int32 max_rendered; // If we are done editing, this breaks the interactive loop Boolean done = false; // The thread where the Editing started taking place Thread edit_thread; // Our object that tracks history History history; // The contents of the kill buffer (cut/paste in Emacs parlance) String kill_buffer = ""; // The string being searched for String search; String last_search; // whether we are searching (-1= reverse; 0 = no; 1 = forward) Int32 searching; // The position where we found the match. Int32 match_at; // Used to implement the Kill semantics (multiple Alt-Ds accumulate) KeyHandler last_handler; delegate void KeyHandler(); struct Handler { public ConsoleKeyInfo CKI; public KeyHandler KeyHandler; public Handler(ConsoleKey myKey, KeyHandler myKeyHandler) { CKI = new ConsoleKeyInfo ((char) 0, myKey, false, false, false); KeyHandler = myKeyHandler; } public Handler(Char myChar, KeyHandler myKeyHandler) { KeyHandler = myKeyHandler; // Use the "Zoom" as a flag that we only have a character. CKI = new ConsoleKeyInfo(myChar, ConsoleKey.Zoom, false, false, false); } public Handler(ConsoleKeyInfo myConsoleKeyInfo, KeyHandler myKeyHandler) { CKI = myConsoleKeyInfo; KeyHandler = myKeyHandler; } public static Handler Control(Char myChar, KeyHandler myKeyHandler) { return new Handler((char) (myChar - 'A' + 1), myKeyHandler); } public static Handler Alt(Char myChar, ConsoleKey myConsoleKey, KeyHandler myKeyHandler) { var cki = new ConsoleKeyInfo((char) myChar, myConsoleKey, false, true, false); return new Handler (cki, myKeyHandler); } } /// <summary> /// Invoked when the user requests auto-completion using the tab character /// </summary> /// <remarks> /// The result is null for no values found, an array with a single /// string, in that case the string should be the text to be inserted /// for example if the word at pos is "T", the result for a completion /// of "ToString" should be "oString", not "ToString". /// /// When there are multiple results, the result should be the full /// text /// </remarks> public AutoCompleteHandler AutoCompleteEvent; static Handler [] _Handlers; public LineEditor(String name) : this (name, 42) { } public LineEditor(String name, Int32 myHistsize) { _Handlers = new Handler [] { new Handler (ConsoleKey.Home, CmdHome), new Handler (ConsoleKey.End, CmdEnd), new Handler (ConsoleKey.LeftArrow, CmdLeft), new Handler (ConsoleKey.RightArrow, CmdRight), new Handler (ConsoleKey.UpArrow, CmdHistoryPrev), new Handler (ConsoleKey.DownArrow, CmdHistoryNext), new Handler (ConsoleKey.Enter, CmdDone), new Handler (ConsoleKey.Backspace, CmdBackspace), new Handler (ConsoleKey.Delete, CmdDeleteChar), new Handler (ConsoleKey.Tab, CmdTabOrComplete), // Emacs keys Handler.Control ('A', CmdHome), Handler.Control ('E', CmdEnd), Handler.Control ('B', CmdLeft), Handler.Control ('F', CmdRight), Handler.Control ('P', CmdHistoryPrev), Handler.Control ('N', CmdHistoryNext), Handler.Control ('K', CmdKillToEOF), Handler.Control ('Y', CmdYank), Handler.Control ('D', CmdDeleteChar), Handler.Control ('L', CmdRefresh), Handler.Control ('R', CmdReverseSearch), Handler.Control ('G', delegate {} ), Handler.Alt ('B', ConsoleKey.B, CmdBackwardWord), Handler.Alt ('F', ConsoleKey.F, CmdForwardWord), Handler.Alt ('D', ConsoleKey.D, CmdDeleteWord), Handler.Alt ((char) 8, ConsoleKey.Backspace, CmdDeleteBackword), // DEBUG //Handler.Control ('T', CmdDebug), // quote Handler.Control ('Q', delegate { HandleChar (Console.ReadKey (true).KeyChar); }) }; rendered_text = new StringBuilder(); text = new StringBuilder(); history = new History(name, myHistsize); //if (File.Exists ("log"))File.Delete ("log"); //log = File.CreateText ("log"); } void CmdDebug() { history.Dump (); Console.WriteLine (); Render (); } void Render() { Console.Write(shown_prompt); Console.Write(rendered_text); int max = System.Math.Max(rendered_text.Length + shown_prompt.Length, max_rendered); for (int i = rendered_text.Length + shown_prompt.Length; i < max_rendered; i++) Console.Write (' '); max_rendered = shown_prompt.Length + rendered_text.Length; // Write one more to ensure that we always wrap around properly if we are at the // end of a line. Console.Write (' '); UpdateHomeRow (max); } void UpdateHomeRow(int screenpos) { int lines = 1 + (screenpos / Console.WindowWidth); home_row = Console.CursorTop - (lines - 1); if (home_row < 0) home_row = 0; } void RenderFrom(int pos) { int rpos = TextToRenderPos (pos); int i; for (i = rpos; i < rendered_text.Length; i++) Console.Write (rendered_text [i]); if ((shown_prompt.Length + rendered_text.Length) > max_rendered) max_rendered = shown_prompt.Length + rendered_text.Length; else { int max_extra = max_rendered - shown_prompt.Length; for (; i < max_extra; i++) Console.Write (' '); } } void ComputeRendered() { rendered_text.Length = 0; for (int i = 0; i < text.Length; i++) { int c = (int) text [i]; if (c < 26){ if (c == '\t') rendered_text.Append (" "); else { rendered_text.Append ('^'); rendered_text.Append ((char) (c + (int) 'A' - 1)); } } else rendered_text.Append ((char)c); } } int TextToRenderPos(Int32 pos) { int p = 0; for (int i = 0; i < pos; i++){ int c; c = (int) text [i]; if (c < 26){ if (c == 9) p += 4; else p += 2; } else p++; } return p; } int TextToScreenPos(Int32 pos) { return shown_prompt.Length + TextToRenderPos (pos); } string Prompt { get { return prompt; } set { prompt = value; } } int LineCount { get { return (shown_prompt.Length + rendered_text.Length)/Console.WindowWidth; } } void ForceCursor(Int32 newpos) { cursor = newpos; int actual_pos = shown_prompt.Length + TextToRenderPos (cursor); int row = home_row + (actual_pos/Console.WindowWidth); int col = actual_pos % Console.WindowWidth; if (row >= Console.BufferHeight) row = Console.BufferHeight-1; Console.SetCursorPosition (col, row); //log.WriteLine ("Going to cursor={0} row={1} col={2} actual={3} prompt={4} ttr={5} old={6}", newpos, row, col, actual_pos, prompt.Length, TextToRenderPos (cursor), cursor); //log.Flush (); } void UpdateCursor(Int32 newpos) { if (cursor == newpos) return; ForceCursor (newpos); } void InsertChar(Char c) { int prev_lines = LineCount; text = text.Insert(cursor, c); ComputeRendered(); if (prev_lines != LineCount) { Console.SetCursorPosition(0, home_row); Render (); ForceCursor (++cursor); } else { RenderFrom(cursor); ForceCursor(++cursor); UpdateHomeRow (TextToScreenPos(cursor)); } } // // Commands // void CmdDone() { done = true; } void CmdTabOrComplete() { bool complete = false; if (AutoCompleteEvent != null) { if (TabAtStartCompletes) complete = true; else { for (int i = 0; i < cursor; i++) { if (!Char.IsWhiteSpace (text [i])) { complete = true; break; } } } if (complete) { Completion completion = AutoCompleteEvent (text.ToString(), cursor); string [] completions = completion._Result; if (completions == null) return; int ncompletions = completions.Length; if (ncompletions == 0) return; if (completions.Length == 1){ InsertTextAtCursor (completions [0]); } else { int last = -1; for (int p = 0; p < completions [0].Length; p++) { char c = completions [0][p]; for (int i = 1; i < ncompletions; i++) { if (completions [i].Length < p) goto mismatch; if (completions [i][p] != c) goto mismatch; } last = p; } mismatch: if (last != -1) { InsertTextAtCursor(completions [0].Substring (0, last+1)); } Console.WriteLine(); foreach (string s in completions) { Console.Write(completion._Prefix); Console.Write(s); Console.Write(' '); } Console.WriteLine (); Render(); ForceCursor(cursor); } } else HandleChar ('\t'); } else HandleChar ('t'); } void CmdHome () { UpdateCursor (0); } void CmdEnd () { UpdateCursor (text.Length); } void CmdLeft () { if (cursor == 0) return; UpdateCursor (cursor-1); } void CmdBackwardWord () { int p = WordBackward (cursor); if (p == -1) return; UpdateCursor (p); } void CmdForwardWord () { int p = WordForward (cursor); if (p == -1) return; UpdateCursor (p); } void CmdRight () { if (cursor == text.Length) return; UpdateCursor (cursor+1); } void RenderAfter (int p) { ForceCursor (p); RenderFrom (p); ForceCursor (cursor); } void CmdBackspace () { if (cursor == 0) return; text.Remove (--cursor, 1); ComputeRendered (); RenderAfter (cursor); } void CmdDeleteChar () { // If there is no input, this behaves like EOF if (text.Length == 0){ done = true; text = null; Console.WriteLine (); return; } if (cursor == text.Length) return; text.Remove (cursor, 1); ComputeRendered (); RenderAfter (cursor); } int WordForward (int p) { if (p >= text.Length) return -1; int i = p; if (Char.IsPunctuation (text [p]) || Char.IsWhiteSpace (text[p])){ for (; i < text.Length; i++){ if (Char.IsLetterOrDigit (text [i])) break; } for (; i < text.Length; i++){ if (!Char.IsLetterOrDigit (text [i])) break; } } else { for (; i < text.Length; i++){ if (!Char.IsLetterOrDigit (text [i])) break; } } if (i != p) return i; return -1; } int WordBackward (int p) { if (p == 0) return -1; int i = p-1; if (i == 0) return 0; if (Char.IsPunctuation (text [i]) || Char.IsSymbol (text [i]) || Char.IsWhiteSpace (text[i])){ for (; i >= 0; i--){ if (Char.IsLetterOrDigit (text [i])) break; } for (; i >= 0; i--){ if (!Char.IsLetterOrDigit (text[i])) break; } } else { for (; i >= 0; i--){ if (!Char.IsLetterOrDigit (text [i])) break; } } i++; if (i != p) return i; return -1; } void CmdDeleteWord () { int pos = WordForward (cursor); if (pos == -1) return; string k = text.ToString (cursor, pos-cursor); if (last_handler == CmdDeleteWord) kill_buffer = kill_buffer + k; else kill_buffer = k; text.Remove (cursor, pos-cursor); ComputeRendered (); RenderAfter (cursor); } void CmdDeleteBackword () { int pos = WordBackward (cursor); if (pos == -1) return; string k = text.ToString (pos, cursor-pos); if (last_handler == CmdDeleteBackword) kill_buffer = k + kill_buffer; else kill_buffer = k; text.Remove (pos, cursor-pos); ComputeRendered (); RenderAfter (pos); } // // Adds the current line to the history if needed // void HistoryUpdateLine () { history.Update (text.ToString ()); } void CmdHistoryPrev () { if (!history.PreviousAvailable ()) return; HistoryUpdateLine (); SetText (history.Previous ()); } void CmdHistoryNext () { if (!history.NextAvailable()) return; history.Update (text.ToString ()); SetText (history.Next ()); } void CmdKillToEOF () { kill_buffer = text.ToString (cursor, text.Length-cursor); text.Length = cursor; ComputeRendered (); RenderAfter (cursor); } void CmdYank () { InsertTextAtCursor (kill_buffer); } void InsertTextAtCursor (string str) { int prev_lines = LineCount; text.Insert (cursor, str); ComputeRendered (); if (prev_lines != LineCount){ Console.SetCursorPosition (0, home_row); Render (); cursor += str.Length; ForceCursor (cursor); } else { RenderFrom (cursor); cursor += str.Length; ForceCursor (cursor); UpdateHomeRow (TextToScreenPos (cursor)); } } void SetSearchPrompt (string s) { SetPrompt ("(reverse-i-search)`" + s + "': "); } void ReverseSearch () { int p; if (cursor == text.Length){ // The cursor is at the end of the string p = text.ToString ().LastIndexOf (search); if (p != -1){ match_at = p; cursor = p; ForceCursor (cursor); return; } } else { // The cursor is somewhere in the middle of the string int start = (cursor == match_at) ? cursor - 1 : cursor; if (start != -1){ p = text.ToString ().LastIndexOf (search, start); if (p != -1){ match_at = p; cursor = p; ForceCursor (cursor); return; } } } // Need to search backwards in history HistoryUpdateLine (); string s = history.SearchBackward (search); if (s != null){ match_at = -1; SetText (s); ReverseSearch (); } } void CmdReverseSearch () { if (searching == 0){ match_at = -1; last_search = search; searching = -1; search = ""; SetSearchPrompt (""); } else { if (search == ""){ if (last_search != "" && last_search != null){ search = last_search; SetSearchPrompt (search); ReverseSearch (); } return; } ReverseSearch (); } } void SearchAppend (char c) { search = search + c; SetSearchPrompt (search); // // If the new typed data still matches the current text, stay here // if (cursor < text.Length){ string r = text.ToString (cursor, text.Length - cursor); if (r.StartsWith (search)) return; } ReverseSearch (); } void CmdRefresh () { Console.Clear (); max_rendered = 0; Render (); ForceCursor (cursor); } void InterruptEdit (object sender, ConsoleCancelEventArgs a) { // Do not abort our program: a.Cancel = true; // Interrupt the editor edit_thread.Abort(); } void HandleChar (char c) { if (searching != 0) SearchAppend (c); else InsertChar (c); } void EditLoop () { ConsoleKeyInfo cki; while (!done){ ConsoleModifiers mod; cki = Console.ReadKey (true); if (cki.Key == ConsoleKey.Escape){ cki = Console.ReadKey (true); mod = ConsoleModifiers.Alt; } else mod = cki.Modifiers; bool handled = false; foreach (Handler handler in _Handlers){ ConsoleKeyInfo t = handler.CKI; if (t.Key == cki.Key && t.Modifiers == mod){ handled = true; handler.KeyHandler (); last_handler = handler.KeyHandler; break; } else if (t.KeyChar == cki.KeyChar && t.Key == ConsoleKey.Zoom){ handled = true; handler.KeyHandler (); last_handler = handler.KeyHandler; break; } } if (handled){ if (searching != 0){ if (last_handler != CmdReverseSearch){ searching = 0; SetPrompt (prompt); } } continue; } if (cki.KeyChar != (char) 0) HandleChar (cki.KeyChar); } } void InitText (string initial) { text = new StringBuilder (initial); ComputeRendered (); cursor = text.Length; Render (); ForceCursor (cursor); } void SetText (string newtext) { Console.SetCursorPosition (0, home_row); InitText (newtext); } void SetPrompt (string newprompt) { shown_prompt = newprompt; Console.SetCursorPosition (0, home_row); Render (); ForceCursor (cursor); } public String Edit(String myPrompt, String myInitial) { edit_thread = Thread.CurrentThread; searching = 0; Console.CancelKeyPress += InterruptEdit; done = false; history.CursorToEnd(); max_rendered = 0; Prompt = myPrompt; shown_prompt = myPrompt; InitText(myInitial); history.Append(myInitial); do { try { EditLoop (); } catch (ThreadAbortException) { searching = 0; Thread.ResetAbort(); Console.WriteLine(); SetPrompt (myPrompt); SetText (""); } } while (!done); Console.WriteLine(); Console.CancelKeyPress -= InterruptEdit; if (text == null) { history.Close(); return null; } var result = text.ToString(); if (result != "") history.Accept (result); else history.RemoveLast (); return result; } public bool TabAtStartCompletes { get; set; } // // Emulates the bash-like behavior, where edits done to the // history are recorded // class History { String[] history; Int32 head, tail; Int32 cursor, count; String histfile; public History (string app, int size) { if (size < 1) throw new ArgumentException ("size"); if (app != null) { string dir = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); //Console.WriteLine (dir); if (!Directory.Exists (dir)){ try { Directory.CreateDirectory (dir); } catch { app = null; } } if (app != null) histfile = Path.Combine (dir, app) + ".history"; } history = new string [size]; head = tail = cursor = 0; if (File.Exists (histfile)) { using (StreamReader sr = File.OpenText (histfile)) { string line; while ((line = sr.ReadLine ()) != null){ if (line != "") Append (line); } } } } public void Close() { if (histfile == null) return; try { using (StreamWriter sw = File.CreateText (histfile)){ int start = (count == history.Length) ? head : tail; for (int i = start; i < start+count; i++){ int p = i % history.Length; sw.WriteLine (history [p]); } } } catch { // ignore } } // // Appends a value to the history // public void Append (string s) { //Console.WriteLine ("APPENDING {0} {1}", s, Environment.StackTrace); history [head] = s; head = (head+1) % history.Length; if (head == tail) tail = (tail+1 % history.Length); if (count != history.Length) count++; } // // Updates the current cursor location with the string, // to support editing of history items. For the current // line to participate, an Append must be done before. // public void Update (string s) { history [cursor] = s; } public void RemoveLast () { head = head-1; if (head < 0) head = history.Length-1; } public void Accept (string s) { int t = head-1; if (t < 0) t = history.Length-1; history [t] = s; } public bool PreviousAvailable () { //Console.WriteLine ("h={0} t={1} cursor={2}", head, tail, cursor); if (count == 0 || cursor == tail) return false; return true; } public bool NextAvailable () { int next = (cursor + 1) % history.Length; if (count == 0 || next >= head) return false; return true; } // // Returns: a string with the previous line contents, or // nul if there is no data in the history to move to. // public string Previous () { if (!PreviousAvailable ()) return null; cursor--; if (cursor < 0) cursor = history.Length - 1; return history [cursor]; } public string Next () { if (!NextAvailable ()) return null; cursor = (cursor + 1) % history.Length; return history [cursor]; } public void CursorToEnd () { if (head == tail) return; cursor = head; } public void Dump () { Console.WriteLine ("Head={0} Tail={1} Cursor={2} count={3}", head, tail, cursor, count); for (int i = 0; i < history.Length;i++){ Console.WriteLine (" {0} {1}: {2}", i == cursor ? "==>" : " ", i, history[i]); } //log.Flush (); } public string SearchBackward (string term) { for (int i = 0; i < count; i++){ int slot = cursor-i-1; if (slot < 0) slot = history.Length+slot; if (slot >= history.Length) slot = 0; if (history [slot] != null && history [slot].IndexOf (term) != -1){ cursor = slot; return history [slot]; } } return null; } } } #if DEMO class Demo { static void Main () { LineEditor le = new LineEditor ("foo"); string s; while ((s = le.Edit ("shell> ", "")) != null){ Console.WriteLine ("----> [{0}]", s); } } } #endif } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { [ConditionalClass(typeof(ParallelQueryCombinationTests), nameof(RunSlowTests))] public static partial class ParallelQueryCombinationTests { // on ARM platforms many available cores makes this unbearably slow: #36494 public static bool RunSlowTests => PlatformDetection.IsNotArmNorArm64Process || Environment.ProcessorCount <= 8; [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Aggregate(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Aggregate((x, y) => x + y)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Aggregate_Seed(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Aggregate(0, (x, y) => x + y)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Aggregate_Result(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Aggregate(0, (x, y) => x + y, r => r)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Aggregate_Accumulator(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Aggregate_SeedFactory(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void All_False(Labeled<Operation> operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, DefaultSource).All(x => false)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void All_True(Labeled<Operation> operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.True(operation.Item(DefaultStart, DefaultSize, DefaultSource).All(x => seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Any_False(Labeled<Operation> operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.False(operation.Item(DefaultStart, DefaultSize, DefaultSource).Any(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Any_True(Labeled<Operation> operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, DefaultSource).Any(x => true)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Average(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double)DefaultSize, operation.Item(DefaultStart, DefaultSize, DefaultSource).Average()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Average_Nullable(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double?)DefaultSize, operation.Item(DefaultStart, DefaultSize, DefaultSource).Average(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Cast(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>()) { Assert.True(i.HasValue); Assert.Equal(seen++, i.Value); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Cast_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Concat(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> concat = (left, right) => { int seen = DefaultStart; foreach (int i in left(DefaultStart, DefaultSize / 2, source.Item) .Concat(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item))) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); }; concat(operation.Item, LabeledDefaultSource.AsOrdered().Item); concat(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Concat_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> concat = (left, right) => { int seen = DefaultStart; Assert.All( left(DefaultStart, DefaultSize / 2, source.Item) .Concat(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item)).ToList(), x => Assert.Equal(seen++, x) ); Assert.Equal(DefaultStart + DefaultSize, seen); }; concat(operation.Item, LabeledDefaultSource.AsOrdered().Item); concat(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Contains_True(Labeled<Operation> operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, DefaultSource).Contains(DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Contains_False(Labeled<Operation> operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, DefaultSource).Contains(DefaultStart + DefaultSize)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Count_Elements(Labeled<Operation> operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, DefaultSource).Count()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Count_Predicate_Some(Labeled<Operation> operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, DefaultSource).Count(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Count_Predicate_None(Labeled<Operation> operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, DefaultSource).Count(x => x < DefaultStart)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void DefaultIfEmpty(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void DefaultIfEmpty_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Distinct(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Distinct_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ElementAt(Labeled<Operation> source, Labeled<Operation> operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAt(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ElementAtOrDefault(Labeled<Operation> source, Labeled<Operation> operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAtOrDefault(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); Assert.Equal(default(int), query.ElementAtOrDefault(-1)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Except(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> except = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(right(DefaultStart + DefaultSize, DefaultSize, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); }; except(operation.Item, DefaultSource); except(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Except_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> except = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(right(DefaultStart + DefaultSize, DefaultSize, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); }; except(operation.Item, DefaultSource); except(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void First(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).First()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void First_Predicate(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).First(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault_Predicate(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault_Predicate_None(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ForAll(Labeled<Operation> source, Labeled<Operation> operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GetEnumerator(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator(); while (enumerator.MoveNext()) { int current = enumerator.Current; Assert.Equal(seen++, current); Assert.Equal(current, enumerator.Current); } Assert.Equal(DefaultStart + DefaultSize, seen); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy(Labeled<Operation> source, Labeled<Operation> operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor)) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_ElementSelector(Labeled<Operation> source, Labeled<Operation> operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y)) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_ElementSelector_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupJoin(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> groupJoin = (left, right) => { int seenKey = DefaultStart / GroupFactor; foreach (KeyValuePair<int, IEnumerable<int>> group in left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .GroupJoin(right(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g))) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group.Value, x => Assert.Equal(seenElement++, x)); Assert.Equal((group.Key + 1) * GroupFactor, seenElement); } Assert.Equal((DefaultStart + DefaultSize) / GroupFactor, seenKey); }; groupJoin(operation.Item, LabeledDefaultSource.AsOrdered().Item); groupJoin(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupJoin_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> groupJoin = (left, right) => { int seenKey = DefaultStart / GroupFactor; foreach (KeyValuePair<int, IEnumerable<int>> group in left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .GroupJoin(right(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group.Value, x => Assert.Equal(seenElement++, x)); Assert.Equal((group.Key + 1) * GroupFactor, seenElement); } Assert.Equal((DefaultStart + DefaultSize) / GroupFactor, seenKey); }; groupJoin(operation.Item, LabeledDefaultSource.AsOrdered().Item); groupJoin(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Intersect(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> intersect = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(right(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); }; intersect(operation.Item, DefaultSource); intersect(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Intersect_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> intersect = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(right(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); }; intersect(operation.Item, DefaultSource); intersect(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Join(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> join = (left, right) => { int seen = DefaultStart; ParallelQuery<KeyValuePair<int, int>> query = left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .Join(right(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y)); foreach (KeyValuePair<int, int> p in query) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / GroupFactor); } Assert.Equal(DefaultStart + DefaultSize, seen); }; join(operation.Item, LabeledDefaultSource.AsOrdered().Item); join(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Join_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> join = (left, right) => { int seen = DefaultStart; ParallelQuery<KeyValuePair<int, int>> query = left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .Join(right(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y)); foreach (KeyValuePair<int, int> p in query.ToList()) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / GroupFactor); } Assert.Equal(DefaultStart + DefaultSize, seen); }; join(operation.Item, LabeledDefaultSource.AsOrdered().Item); join(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Last(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Last_Predicate(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault_Predicate(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault_Predicate_None(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => false)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void LongCount_Elements(Labeled<Operation> operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, DefaultSource).LongCount()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void LongCount_Predicate_Some(Labeled<Operation> operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, DefaultSource).LongCount(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void LongCount_Predicate_None(Labeled<Operation> operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, DefaultSource).LongCount(x => x < DefaultStart)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Max(Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, DefaultSource).Max()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Max_Nullable(Labeled<Operation> operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, DefaultSource).Max(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Min(Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, DefaultSource).Min()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Min_Nullable(Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, DefaultSource).Min(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_Other(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_Other_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>().ToList()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_Initial(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_Initial_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_OtherDirection(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_OtherDirection_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_Initial(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_Initial_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_OtherDirection(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_OtherDirection_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Reverse(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Reverse_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse().ToList()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_Indexed(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_Indexed_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x))) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_ResultSelector(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_ResultSelector_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_ResultSelector(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_ResultSelector_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SequenceEqual(Labeled<Operation> source, Labeled<Operation> operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered())); Assert.True(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Single(Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, DefaultSource).Single()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, DefaultSource).Single(x => x == DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void SingleOrDefault(Labeled<Operation> operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, DefaultSource).SingleOrDefault()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, DefaultSource).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); if (!operation.ToString().StartsWith("DefaultIfEmpty")) { Assert.Equal(default(int), operation.Item(DefaultStart, 0, DefaultSource).SingleOrDefault()); Assert.Equal(default(int), operation.Item(DefaultStart, 0, DefaultSource).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); } } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Skip(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Skip_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_Indexed(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_Indexed_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Sum(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Sum()); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void Sum_Nullable(Labeled<Operation> operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, DefaultSource).Sum(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Take(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Take_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_Indexed(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_Indexed_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_Initial(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_Initial_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_OtherDirection(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_OtherDirection_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_Initial(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_Initial_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_OtherDirection(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_OtherDirection_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ToArray(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void ToDictionary(Labeled<Operation> operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).ToDictionary(x => x * 2), p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); }); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperations))] [MemberData(nameof(BinaryOperations))] public static void ToDictionary_ElementSelector(Labeled<Operation> operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).ToDictionary(x => x, y => y * 2), p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); }); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ToList(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToLookup(Labeled<Operation> source, Labeled<Operation> operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToLookup_ElementSelector(Labeled<Operation> source, Labeled<Operation> operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2, y => -y); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Union(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> union = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart, DefaultSize * 3 / 4, source.Item) .Union(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); }; union(operation.Item, LabeledDefaultSource.AsOrdered().Item); union(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Union_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> union = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart, DefaultSize * 3 / 4, source.Item) .Union(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); }; union(operation.Item, LabeledDefaultSource.AsOrdered().Item); union(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_Indexed(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_Indexed_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Zip(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> zip = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart * 2, DefaultSize, source.Item) .Zip(right(0, DefaultSize, source.Item), (x, y) => (x + y) / 2); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); }; zip(operation.Item, LabeledDefaultSource.AsOrdered().Item); zip(LabeledDefaultSource.AsOrdered().Item, operation.Item); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Zip_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation) { Action<Operation, Operation> zip = (left, right) => { int seen = DefaultStart; ParallelQuery<int> query = left(DefaultStart * 2, DefaultSize, source.Item) .Zip(right(0, DefaultSize, source.Item), (x, y) => (x + y) / 2); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); }; zip(operation.Item, LabeledDefaultSource.AsOrdered().Item); zip(LabeledDefaultSource.AsOrdered().Item, operation.Item); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Resources; using System.Reflection; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.SystemUI; namespace VertexCommands_CS { /// <summary> /// Contains 2 tools to insert or delete vertices. /// Both make use the out-of-the-box ControlsCommands to do this /// </summary> [Guid("6583D8C5-7A4A-4efc-9FAA-2FCD4EAD5BC3")] [ClassInterface(ClassInterfaceType.None)] [ProgId("VertexCommands_CS.UsingOutOfBoxVertexCommands")] public sealed class UsingOutOfBoxVertexCommands : BaseTool, ICommandSubType { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Unregister(regKey); } #endregion #endregion #region Private Members private long m_lSubType; private IHookHelper m_hookHelper = null; private IEngineEditor m_engineEditor; private IEngineEditLayers m_editLayer; private System.Windows.Forms.Cursor m_InsertVertexCursor; private System.Windows.Forms.Cursor m_DeleteVertexCursor; #endregion #region Class constructor public UsingOutOfBoxVertexCommands() { #region load the cursors try { m_InsertVertexCursor = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("VertexCommands_CS.InsertVertexCursor.cur")); m_DeleteVertexCursor = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("VertexCommands_CS.DeleteVertexCursor.cur")); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Cursor"); } #endregion } #endregion #region Overriden Class Methods /// <summary> /// Return the cursor to be used by the tool /// </summary> public override int Cursor { get { int iHandle = 0; switch (m_lSubType) { case 1: iHandle = m_InsertVertexCursor.Handle.ToInt32(); break; case 2: iHandle = m_DeleteVertexCursor.Handle.ToInt32(); break; } return (iHandle); } } public override void OnClick() { //Find the Modify Feature task and set it as the current task IEngineEditTask editTask = m_engineEditor.GetTaskByUniqueName("ControlToolsEditing_ModifyFeatureTask"); m_engineEditor.CurrentTask = editTask; } /// <summary> /// Occurs when this tool is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { try { m_hookHelper = new HookHelperClass(); m_hookHelper.Hook = hook; m_engineEditor = new EngineEditorClass(); //this class is a singleton m_editLayer = m_engineEditor as IEngineEditLayers; } catch { m_hookHelper = null; } } /// <summary> /// Perform checks so that the tool is enabled appropriately /// </summary> public override bool Enabled { get { //check whether Editing if (m_engineEditor.EditState == esriEngineEditState.esriEngineStateNotEditing) { return false; } //check for appropriate geometry types esriGeometryType geomType = m_editLayer.TargetLayer.FeatureClass.ShapeType; if ((geomType != esriGeometryType.esriGeometryPolygon) & (geomType != esriGeometryType.esriGeometryPolyline)) { return false; } //check that only one feature is currently selected IFeatureSelection featureSelection = m_editLayer.TargetLayer as IFeatureSelection; ISelectionSet selectionSet = featureSelection.SelectionSet; if (selectionSet.Count != 1) { return false; } return true; } } /// <summary> /// The mouse up performs the action appropriate for each sub-typed command: /// insert vertex or delete vertex /// </summary> /// <param name="Button"></param> /// <param name="Shift"></param> /// <param name="X">The X screen coordinate of the clicked location</param> /// <param name="Y">The Y screen coordinate of the clicked location</param> public override void OnMouseUp(int Button, int Shift, int X, int Y) { try { //get layer being edited IFeatureLayer featureLayer = m_editLayer.TargetLayer as IFeatureLayer; //set the x,y location which will be used by the out-of-the-box commands IEngineEditSketch editsketch = m_engineEditor as IEngineEditSketch; editsketch.SetEditLocation(X, Y); Type t = null; object o = null; switch (m_lSubType) { case 1: //Insert Vertex using out-of-the-box command t = Type.GetTypeFromProgID("esriControls.ControlsEditingVertexInsertCommand.1"); o = Activator.CreateInstance(t); ICommand insertVertexCommand = o as ICommand; if (insertVertexCommand != null) { insertVertexCommand.OnCreate(m_hookHelper.Hook); insertVertexCommand.OnClick(); } break; case 2: //Delete Vertex using out-of-the-box command t = Type.GetTypeFromProgID("esriControls.ControlsEditingVertexDeleteCommand.1"); o = Activator.CreateInstance(t); ICommand deleteVertexCommand = o as ICommand; if (deleteVertexCommand != null) { deleteVertexCommand.OnCreate(m_hookHelper.Hook); deleteVertexCommand.OnClick(); } break; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Unexpected Error"); } } #endregion #region ICommandSubType Interface /// <summary> /// Returns the number of subtyped commands /// </summary> /// <returns></returns> public int GetCount() { return 2; } /// <summary> /// Sets the sub-type /// </summary> /// <param name="SubType"></param> public void SetSubType(int SubType) { m_lSubType = SubType; ResourceManager rm = new ResourceManager("VertexCommands_CS.Resources", Assembly.GetExecutingAssembly()); //set a common Command category for all subtypes base.m_category = "Vertex Cmds (C#)"; switch (m_lSubType) { case 1: //Insert Vertex using the out-of-the-box ControlsEditingSketchInsertPointCommand command base.m_caption = (string)rm.GetString("OOBInsertVertex_CommandCaption"); base.m_message = (string)rm.GetString("OOBInsertVertex_CommandMessage"); base.m_toolTip = (string)rm.GetString("OOBInsertVertex_CommandToolTip"); base.m_name = "VertexCommands_UsingOutOfBoxInsertVertex"; base.m_cursor = m_InsertVertexCursor; #region bitmap try { base.m_bitmap = (System.Drawing.Bitmap)rm.GetObject("OOBInsertVertex"); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } #endregion break; case 2: //Delete vertex at clicked location using the out-of-the-box ControlsEditingSketchDeletePointCommand base.m_caption = (string)rm.GetString("OOBDeleteVertex_CommandCaption"); base.m_message = (string)rm.GetString("OOBDeleteVertex_CommandMessage"); base.m_toolTip = (string)rm.GetString("OOBDeleteVertex_CommandToolTip"); base.m_name = "VertexCommands_UsingOutOfBoxDeleteVertex"; base.m_cursor = m_DeleteVertexCursor; #region bitmap try { base.m_bitmap = (System.Drawing.Bitmap)rm.GetObject("OOBDeleteVertex"); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } #endregion break; } } #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.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.DirectoryServices; using System.Text; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { internal class SAMUtils { // To stop the compiler from autogenerating a constructor for this class private SAMUtils() { } static internal bool IsOfObjectClass(DirectoryEntry de, string classToCompare) { return string.Equals(de.SchemaClassName, classToCompare, StringComparison.OrdinalIgnoreCase); } internal static bool GetOSVersion(DirectoryEntry computerDE, out int versionMajor, out int versionMinor) { Debug.Assert(SAMUtils.IsOfObjectClass(computerDE, "Computer")); versionMajor = 0; versionMinor = 0; string version = null; try { if (computerDE.Properties["OperatingSystemVersion"].Count > 0) { Debug.Assert(computerDE.Properties["OperatingSystemVersion"].Count == 1); version = (string)computerDE.Properties["OperatingSystemVersion"].Value; } } catch (COMException e) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "SAMUtils", "GetOSVersion: caught COMException with message " + e.Message); // Couldn't retrieve the value if (e.ErrorCode == unchecked((int)0x80070035)) // ERROR_BAD_NETPATH return false; throw; } // Couldn't retrieve the value if (version == null || version.Length == 0) return false; // This string should be in the form "M.N", where M and N are integers. // We'll also accept "M", which we'll treat as "M.0". // // We'll split the string into its period-separated components, and parse // each component into an int. string[] versionComponents = version.Split(new char[] { '.' }); Debug.Assert(versionComponents.Length >= 1); // since version was a non-empty string try { versionMajor = int.Parse(versionComponents[0], CultureInfo.InvariantCulture); if (versionComponents.Length > 1) versionMinor = int.Parse(versionComponents[1], CultureInfo.InvariantCulture); // Sanity check: there are no negetive OS versions, nor is there a version "0". if (versionMajor <= 0 || versionMinor < 0) { Debug.Fail(string.Format( CultureInfo.CurrentCulture, "SAMUtils.GetOSVersion: {0} claims to have negetive OS version, {1}", computerDE.Path, version)); return false; } } catch (FormatException) { Debug.Fail(string.Format( CultureInfo.CurrentCulture, "SAMUtils.GetOSVersion: FormatException on {0} for {1}", version, computerDE.Path)); return false; } catch (OverflowException) { Debug.Fail(string.Format( CultureInfo.CurrentCulture, "SAMUtils.GetOSVersion: OverflowException on {0} for {1}", version, computerDE.Path)); return false; } return true; } static internal Principal DirectoryEntryAsPrincipal(DirectoryEntry de, StoreCtx storeCtx) { string className = de.SchemaClassName; // Unlike AD, we don't have to worry about cross-store refs here. In AD, if there's // a cross-store ref, we'll get back a DirectoryEntry of the FPO object. In the WinNT ADSI // provider, we'll get back the DirectoryEntry of the remote object itself --- ADSI does // the domain vs. local resolution for us. if (SAMUtils.IsOfObjectClass(de, "Computer") || SAMUtils.IsOfObjectClass(de, "User") || SAMUtils.IsOfObjectClass(de, "Group")) { return storeCtx.GetAsPrincipal(de, null); } else { Debug.Fail(string.Format( CultureInfo.CurrentCulture, "SAMUtils.DirectoryEntryAsPrincipal: fell off end, Path={0}, SchemaClassName={1}", de.Path, de.SchemaClassName)); return null; } } // These are verbatim C# string ( @ ) where \ is actually \\ // Input Matches RegEx // ----- ------- ----- // * any ( 1 or more ) .* // // \* * \* // \ \ \\ // ( ( \( // \( ( \( // ) ) \) // \) ) \) // \\ \ \\ // x x x (where x is anything else) // Add \G to beginning and \z to the end so that the regex will be anchored at the either end of the property // \G = Regex must match at the beginning // \z = Regex must match at the end // ( ) * are special characters to Regex so they must be escaped with \\. We support these from teh user either raw or already escaped. // Any other \ in the input string are translated to an actual \ in the match because we cannot determine usage except for ( ) * // The user cannot enter any regex escape sequence they would like in their match string. Only * is supported. // // @"c:\Home" -> "c:\\\\Home" OR @"c:\\Home" // // static internal string PAPIQueryToRegexString(string papiString) { StringBuilder sb = new StringBuilder(papiString.Length); sb.Append(@"\G"); bool escapeMode = false; foreach (char c in papiString) { if (escapeMode == false) { switch (c) { case '(': sb.Append(@"\("); // ( --> \( break; case ')': sb.Append(@"\)"); // ) --> \) break; case '\\': escapeMode = true; break; case '*': sb.Append(@".*"); // * --> .* break; default: sb.Append(c.ToString()); // x --> x break; } } else { escapeMode = false; switch (c) { case '(': sb.Append(@"\("); // \( --> \( break; case ')': sb.Append(@"\)"); // \) --> \) break; case '*': sb.Append(@"\*"); // \* --> \* break; case '\\': sb.Append(@"\\\\"); // \\ --> \\ break; default: sb.Append(@"\\"); sb.Append(c.ToString()); // \x --> \x break; } } } // There was a '\\' but no character after it because we were at the // end of the string. // Append '\\\\' to match the '\\'. if (escapeMode) { sb.Append(@"\\"); } GlobalDebug.WriteLineIf( GlobalDebug.Info, "SAMUtils", "PAPIQueryToRegexString: mapped '{0}' to '{1}'", papiString, sb.ToString()); sb.Append(@"\z"); return sb.ToString(); } } }
namespace Nancy.Authentication.Forms.Tests { using System; using System.Linq; using System.Threading; using Bootstrapper; using Cryptography; using FakeItEasy; using Fakes; using Helpers; using Nancy.Security; using Nancy.Tests; using Nancy.Tests.Fakes; using Xunit; public class FormsAuthenticationFixture { private FormsAuthenticationConfiguration config; private FormsAuthenticationConfiguration secureConfig; private FormsAuthenticationConfiguration domainPathConfig; private NancyContext context; private Guid userGuid; private string validCookieValue = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithNoHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithEmptyHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithInvalidHmac = HttpUtility.UrlEncode("C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithBrokenEncryptedData = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9"); private CryptographyConfiguration cryptographyConfiguration; private string domain = ".nancyfx.org"; private string path = "/"; public FormsAuthenticationFixture() { this.cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); this.config = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false }; this.secureConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = true }; this.domainPathConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false, Domain = domain, Path = path }; this.context = new NancyContext { Request = new Request( "GET", new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" }) }; this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010"); } [Fact] public void Should_throw_with_null_application_pipelines_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_invalid_config_passed_to_enable() { var fakeConfig = A.Fake<FormsAuthenticationConfiguration>(); A.CallTo(() => fakeConfig.IsValid).Returns(false); var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig)); result.ShouldBeOfType(typeof(ArgumentException)); } [Fact] public void Should_add_a_pre_and_post_hook_when_enabled() { var pipelines = A.Fake<IPipelines>(); FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true() { var pipelines = A.Fake<IPipelines>(); this.config.DisableRedirect = true; FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustNotHaveHappened(); } [Fact] public void Should_return_redirect_response_when_user_logs_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_encrypt_cookie_when_logging_in_with_redirect() { var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_encrypt_cookie_when_logging_in_without_redirect() { // Given var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect() { var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect() { // Given var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_return_redirect_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_get_username_from_mapping_service_with_valid_cookie() { var fakePipelines = new Pipelines(); var mockMapper = A.Fake<IUserMapper>(); this.config.UserMapper = mockMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_user_in_context_with_valid_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity {UserName = "Bob"}; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeSameAs(fakeUser); } [Fact] public void Should_not_set_user_in_context_with_empty_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity {UserName = "Bob"}; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_invalid_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_empty_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_no_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_username_in_context_with_broken_encryption_data() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_retain_querystring_when_redirecting_to_login_page() { // Given var fakePipelines = new Pipelines(); FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = "next"; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = null; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = string.Empty; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_retain_querystring_when_redirecting_after_successfull_login() { // Given var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar") }; FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1)); // Then result.Headers["Location"].ShouldEqual("/secure?foo=bar"); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing"); } [Fact] public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/moo"); } [Fact] public void Should_redirect_to_given_url_if_local() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "~/login"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing/login"); } [Fact] public void Should_set_Domain_when_config_provides_domain_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Domain.ShouldEqual(domain); } [Fact] public void Should_set_Path_when_config_provides_path_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Path.ShouldEqual(path); } [Fact] public void Should_throw_with_null_module_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable_with_module() { var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } class FakeModule : NancyModule { public FakeModule() { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); } } } }
using System; using System.Diagnostics; using System.Threading; using NSec.Cryptography; using static Interop.Libsodium; namespace NSec.Experimental { // Stream cipher encryption/decryption algorithm without any authentication. // This is not usually recommended for any communication protocol and should // be used only as a building block for a more high level protocol. public abstract class StreamCipherAlgorithm : Algorithm { private static ChaCha20? s_ChaCha20; private readonly int _keySize; private readonly int _nonceSize; private protected StreamCipherAlgorithm( int keySize, int nonceSize) { Debug.Assert(keySize > 0); Debug.Assert(nonceSize >= 0 && nonceSize <= 24); _keySize = keySize; _nonceSize = nonceSize; } public static ChaCha20 ChaCha20 { get { ChaCha20? instance = s_ChaCha20; if (instance == null) { Interlocked.CompareExchange(ref s_ChaCha20, new ChaCha20(), null); instance = s_ChaCha20; } return instance; } } public int KeySize => _keySize; public int NonceSize => _nonceSize; public byte[] GeneratePseudoRandomStream( Key key, ReadOnlySpan<byte> nonce, int count) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } if (count < 0) { throw Error.ArgumentOutOfRange_GenerateNegativeCount(nameof(count)); } byte[] bytes = new byte[count]; GeneratePseudoRandomStreamCore(key.Handle, nonce, bytes); return bytes; } public void GeneratePseudoRandomStream( Key key, ReadOnlySpan<byte> nonce, Span<byte> bytes) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } GeneratePseudoRandomStreamCore(key.Handle, nonce, bytes); } public byte[] XOr( Key key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } byte[] output = new byte[input.Length]; XOrCore(key.Handle, nonce, input, output); return output; } public void XOr( Key key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input, Span<byte> output) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } if (output.Length != input.Length) { throw Error.Argument_CiphertextLength(nameof(output)); // TODO } if (output.Overlaps(input, out int offset) && offset != 0) { throw Error.Argument_OverlapCiphertext(nameof(output)); // TODO } XOrCore(key.Handle, nonce, input, output); } public byte[] XOrIC( Key key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input, uint ic) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } byte[] output = new byte[input.Length]; XOrICCore(key.Handle, nonce, input, ic, output); return output; } public void XOrIC( Key key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input, Span<byte> output, uint ic) { if (key == null) { throw Error.ArgumentNull_Key(nameof(key)); } if (key.Algorithm != this) { throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key)); } if (nonce.Length != _nonceSize) { throw Error.Argument_NonceLength(nameof(nonce), _nonceSize); } if (output.Length != input.Length) { throw Error.Argument_CiphertextLength(nameof(output)); // TODO } if (output.Overlaps(input, out int offset) && offset != 0) { throw Error.Argument_OverlapCiphertext(nameof(output)); // TODO } XOrICCore(key.Handle, nonce, input, ic, output); } internal sealed override int GetKeySize() { return _keySize; } internal sealed override int GetPublicKeySize() { throw Error.InvalidOperation_InternalError(); } internal abstract override int GetSeedSize(); private protected abstract void GeneratePseudoRandomStreamCore( SecureMemoryHandle keyHandle, ReadOnlySpan<byte> nonce, Span<byte> bytes); private protected abstract void XOrCore( SecureMemoryHandle keyHandle, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input, Span<byte> output); private protected abstract void XOrICCore( SecureMemoryHandle keyHandle, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> input, uint ic, Span<byte> output); } }
// // Authors: // Alan McGovern alan.mcgovern@gmail.com // Ben Motmans <ben.motmans@gmail.com> // Lucas Ontivero lucasontivero@gmail.com // // Copyright (C) 2006 Alan McGovern // Copyright (C) 2007 Ben Motmans // Copyright (C) 2014 Lucas Ontivero // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Net; namespace Open.Nat { enum MappingLifetime { Permanent, Session, Manual, ForcedSession } /// <summary> /// Represents a port forwarding entry in the NAT translation table. /// </summary> public class Mapping { private DateTime _expiration; private int _lifetime; internal MappingLifetime LifetimeType { get; set; } /// <summary> /// Gets the mapping's description. It is the value stored in the NewPortMappingDescription parameter. /// The NewPortMappingDescription parameter is a human readable string that describes the connection. /// It is used in sorme web interfaces of routers so the user can see which program is using what port. /// </summary> public string Description { get; internal set; } /// <summary> /// Gets the private ip. /// </summary> public IPAddress PrivateIP { get; internal set; } /// <summary> /// Gets the protocol. /// </summary> public Protocol Protocol { get; internal set; } /// <summary> /// The PrivatePort parameter specifies the port on a client machine to which all traffic /// coming in on <see cref="#PublicPort">PublicPort</see> for the protocol specified by /// <see cref="#Protocol">Protocol</see> should be forwarded to. /// </summary> /// <see cref="Protocol">Protocol enum</see> public int PrivatePort { get; internal set; } /// <summary> /// Gets the public ip. /// </summary> public IPAddress PublicIP { get; internal set; } /// <summary> /// Gets the external (visible) port number. /// It is the value stored in the NewExternalPort parameter . /// The NewExternalPort parameter is used to specify the TCP or UDP port on the WAN side of the router which should be forwarded. /// </summary> public int PublicPort { get; internal set; } /// <summary> /// Gets the lifetime. The Lifetime parameter tells the router how long the portmapping should be active. /// Since most programs don't know this in advance, it is often set to 0, which means 'unlimited' or 'permanent'. /// </summary> /// <remarks> /// All portmappings are release automatically as part of the shutdown process when <see cref="NatDiscoverer">NatUtility</see>.<see cref="NatUtility#releaseonshutdown">ReleaseOnShutdown</see> is true. /// Permanent portmappings will not be released if the process ends anormally. /// Since most programs don't know the lifetime in advance, Open.NAT renew all the portmappings (except the permanents) before they expires. So, developers have to close explicitly those portmappings /// they don't want to remain open for the session. /// </remarks> public int Lifetime { get { return _lifetime; } internal set { switch (value) { case int.MaxValue: LifetimeType = MappingLifetime.Session; _lifetime = 10 * 60; // ten minutes _expiration = DateTime.UtcNow.AddSeconds(_lifetime);; break; case 0: LifetimeType = MappingLifetime.Permanent; _lifetime = 0; _expiration = DateTime.UtcNow; break; default: LifetimeType = MappingLifetime.Manual; _lifetime = value; _expiration = DateTime.UtcNow.AddSeconds(_lifetime); break; } } } /// <summary> /// Gets the expiration. The property value is calculated using <see cref="#Lifetime">Lifetime</see> property. /// </summary> public DateTime Expiration { get { return _expiration; } internal set { _expiration = value; _lifetime = (int)(_expiration - DateTime.UtcNow).TotalSeconds; } } internal Mapping(Protocol protocol, IPAddress privateIP, int privatePort, int publicPort) : this(protocol, privateIP, privatePort, publicPort, 0, "Open.Nat") { } /// <summary> /// Initializes a new instance of the <see cref="Mapping"/> class. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="privateIP">The private ip.</param> /// <param name="privatePort">The private port.</param> /// <param name="publicPort">The public port.</param> /// <param name="lifetime">The lifetime.</param> /// <param name="description">The description.</param> public Mapping(Protocol protocol, IPAddress privateIP, int privatePort, int publicPort, int lifetime, string description) { Guard.IsInRange(privatePort, 0, ushort.MaxValue, "privatePort"); Guard.IsInRange(publicPort, 0, ushort.MaxValue, "publicPort"); Guard.IsInRange(lifetime, 0, int.MaxValue, "lifetime"); Guard.IsTrue(protocol == Protocol.Tcp || protocol == Protocol.Udp, "protocol"); Guard.IsNotNull(privateIP, "privateIP"); Protocol = protocol; PrivateIP = privateIP; PrivatePort = privatePort; PublicIP = IPAddress.None; PublicPort = publicPort; Lifetime = lifetime; Description = description; } /// <summary> /// Initializes a new instance of the <see cref="Mapping"/> class. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="privatePort">The private port.</param> /// <param name="publicPort">The public port.</param> /// <remarks> /// This constructor initializes a Permanent mapping. The description by deafult is "Open.NAT" /// </remarks> public Mapping(Protocol protocol, int privatePort, int publicPort) : this(protocol, IPAddress.None, privatePort, publicPort, 0, "Open.NAT") { } /// <summary> /// Initializes a new instance of the <see cref="Mapping"/> class. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="privatePort">The private port.</param> /// <param name="publicPort">The public port.</param> /// <param name="description">The description.</param> /// <remarks> /// This constructor initializes a Permanent mapping. /// </remarks> public Mapping(Protocol protocol, int privatePort, int publicPort, string description) : this(protocol, IPAddress.None, privatePort, publicPort, int.MaxValue, description) { } /// <summary> /// Initializes a new instance of the <see cref="Mapping"/> class. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="privatePort">The private port.</param> /// <param name="publicPort">The public port.</param> /// <param name="lifetime">The lifetime.</param> /// <param name="description">The description.</param> public Mapping(Protocol protocol, int privatePort, int publicPort, int lifetime, string description) : this(protocol, IPAddress.None, privatePort, publicPort, lifetime, description) { } internal Mapping(Mapping mapping) { PrivateIP = mapping.PrivateIP; PrivatePort = mapping.PrivatePort; Protocol = mapping.Protocol; PublicIP = mapping.PublicIP; PublicPort = mapping.PublicPort; LifetimeType = mapping.LifetimeType; Description = mapping.Description; _lifetime = mapping._lifetime; _expiration = mapping._expiration; } /// <summary> /// Determines whether this instance is expired. /// </summary> /// <remarks> /// Permanent mappings never expires. /// </remarks> public bool IsExpired () { return LifetimeType != MappingLifetime.Permanent && LifetimeType != MappingLifetime.ForcedSession && Expiration < DateTime.UtcNow; } internal bool ShoundRenew() { return LifetimeType == MappingLifetime.Session && IsExpired(); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var m = obj as Mapping; if (ReferenceEquals(null, m)) return false; return PublicPort == m.PublicPort && PrivatePort == m.PrivatePort; } public override int GetHashCode() { unchecked { var hashCode = PublicPort; hashCode = (hashCode * 397) ^ (PrivateIP != null ? PrivateIP.GetHashCode() : 0); hashCode = (hashCode * 397) ^ PrivatePort; return hashCode; } } /// <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 string.Format("{0} {1} --> {2}:{3} ({4})", Protocol == Protocol.Tcp ? "Tcp" : "Udp", PublicPort, PrivateIP, PrivatePort, Description); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Params { /// <summary> /// <para>This class maintains a map of HTTP routes to maximum number of connections allowed for those routes. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>652947 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRouteBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRouteBean", AccessFlags = 49)] public sealed partial class ConnPerRouteBean : global::Org.Apache.Http.Conn.Params.IConnPerRoute /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed per host </para> /// </summary> /// <java-name> /// DEFAULT_MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("DEFAULT_MAX_CONNECTIONS_PER_ROUTE", "I", AccessFlags = 25)] public const int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public ConnPerRouteBean(int defaultMax) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnPerRouteBean() /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] public int GetDefaultMax() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setDefaultMaxPerRoute /// </java-name> [Dot42.DexImport("setDefaultMaxPerRoute", "(I)V", AccessFlags = 1)] public void SetDefaultMaxPerRoute(int max) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxForRoute /// </java-name> [Dot42.DexImport("setMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;I)V", AccessFlags = 1)] public void SetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route, int max) /* MethodBuilder.Create */ { } /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1)] public int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setMaxForRoutes /// </java-name> [Dot42.DexImport("setMaxForRoutes", "(Ljava/util/Map;)V", AccessFlags = 1, Signature = "(Ljava/util/Map<Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Integer;>;)V")] public void SetMaxForRoutes(global::Java.Util.IMap<global::Org.Apache.Http.Conn.Routing.HttpRoute, int?> map) /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> public int DefaultMax { [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] get{ return GetDefaultMax(); } } } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the maximum number of ignorable lines before we expect a HTTP response's status line. </para><para>With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. </para><para>This parameter expects a value of type Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited (default in lenient mode). </para> /// </summary> /// <java-name> /// MAX_STATUS_LINE_GARBAGE /// </java-name> [Dot42.DexImport("MAX_STATUS_LINE_GARBAGE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537)] public partial interface IConnConnectionPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnRoutePNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Parameter for the default proxy. The default value will be used by some HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_PROXY /// </java-name> [Dot42.DexImport("DEFAULT_PROXY", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_PROXY = "http.route.default-proxy"; /// <summary> /// <para>Parameter for the local address. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. It will be interpreted by the standard HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type java.net.InetAddress. </para> /// </summary> /// <java-name> /// LOCAL_ADDRESS /// </java-name> [Dot42.DexImport("LOCAL_ADDRESS", "Ljava/lang/String;", AccessFlags = 25)] public const string LOCAL_ADDRESS = "http.route.local-address"; /// <summary> /// <para>Parameter for an forced route. The forced route will be interpreted by the standard HttpRoutePlanner implementations. Instead of computing a route, the given forced route will be returned, even if it points to the wrong target host. </para><para>This parameter expects a value of type HttpRoute. </para> /// </summary> /// <java-name> /// FORCED_ROUTE /// </java-name> [Dot42.DexImport("FORCED_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string FORCED_ROUTE = "http.route.forced-route"; } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537)] public partial interface IConnRoutePNames /* scope: __dot42__ */ { } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters applicable to client-side connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke</para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0</para><para>ConnManagerPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParams", AccessFlags = 49)] public sealed partial class ConnManagerParams : global::Org.Apache.Http.Conn.Params.IConnManagerPNames /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed overall </para> /// </summary> /// <java-name> /// DEFAULT_MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("DEFAULT_MAX_TOTAL_CONNECTIONS", "I", AccessFlags = 25)] public const int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnManagerParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getTimeout /// </java-name> [Dot42.DexImport("getTimeout", "(Lorg/apache/http/params/HttpParams;)J", AccessFlags = 9)] public static long GetTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(long); } /// <summary> /// <para>Sets the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(Lorg/apache/http/params/HttpParams;J)V", AccessFlags = 9)] public static void SetTimeout(global::Org.Apache.Http.Params.IHttpParams @params, long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("setMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/params/ConnPerRoute;)V", AccessFlags = 9)] public static void SetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Params.IConnPerRoute connPerRoute) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <returns> /// <para>lookup interface for maximum number of connections allowed per route.</para> /// </returns> /// <java-name> /// getMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("getMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/params/ConnPerRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Params.IConnPerRoute GetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Params.IConnPerRoute); } /// <summary> /// <para>Sets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params, int maxTotalConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <returns> /// <para>The maximum number of connections allowed.</para> /// </returns> /// <java-name> /// getMaxTotalConnections /// </java-name> [Dot42.DexImport("getMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } } /// <summary> /// <para>This interface is intended for looking up maximum number of connections allowed for for a given route. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>651813 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRoute /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRoute", AccessFlags = 1537)] public partial interface IConnPerRoute /* scope: __dot42__ */ { /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1025)] int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Allows for setting parameters relating to connection managers on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParamBean", AccessFlags = 33)] public partial class ConnManagerParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnManagerParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(J)V", AccessFlags = 1)] public virtual void SetTimeout(long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(I)V", AccessFlags = 1)] public virtual void SetMaxTotalConnections(int maxConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setConnectionsPerRoute /// </java-name> [Dot42.DexImport("setConnectionsPerRoute", "(Lorg/apache/http/conn/params/ConnPerRouteBean;)V", AccessFlags = 1)] public virtual void SetConnectionsPerRoute(global::Org.Apache.Http.Conn.Params.ConnPerRouteBean connPerRoute) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnManagerParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Allows for setting parameters relating to connections on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionParamBean", AccessFlags = 33)] public partial class ConnConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnConnectionPNames::MAX_STATUS_LINE_GARBAGE </para></para> /// </summary> /// <java-name> /// setMaxStatusLineGarbage /// </java-name> [Dot42.DexImport("setMaxStatusLineGarbage", "(I)V", AccessFlags = 1)] public virtual void SetMaxStatusLineGarbage(int maxStatusLineGarbage) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>An adaptor for accessing route related parameters in HttpParams. See ConnRoutePNames for parameter name definitions.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParams", AccessFlags = 33)] public partial class ConnRouteParams : global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { /// <summary> /// <para>A special value indicating "no host". This relies on a nonsense scheme name to avoid conflicts with actual hosts. Note that this is a <b>valid</b> host. </para> /// </summary> /// <java-name> /// NO_HOST /// </java-name> [Dot42.DexImport("NO_HOST", "Lorg/apache/http/HttpHost;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.HttpHost NO_HOST; /// <summary> /// <para>A special value indicating "no route". This is a route with NO_HOST as the target. </para> /// </summary> /// <java-name> /// NO_ROUTE /// </java-name> [Dot42.DexImport("NO_ROUTE", "Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.Conn.Routing.HttpRoute NO_ROUTE; /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal ConnRouteParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the DEFAULT_PROXY parameter value. NO_HOST will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the default proxy set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getDefaultProxy /// </java-name> [Dot42.DexImport("getDefaultProxy", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/HttpHost;", AccessFlags = 9)] public static global::Org.Apache.Http.HttpHost GetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.HttpHost); } /// <summary> /// <para>Sets the DEFAULT_PROXY parameter value.</para><para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/HttpHost;)V", AccessFlags = 9)] public static void SetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.HttpHost proxy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the FORCED_ROUTE parameter value. NO_ROUTE will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the forced route set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getForcedRoute /// </java-name> [Dot42.DexImport("getForcedRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Routing.HttpRoute GetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Routing.HttpRoute); } /// <summary> /// <para>Sets the FORCED_ROUTE parameter value.</para><para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 9)] public static void SetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the LOCAL_ADDRESS parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the local address set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getLocalAddress /// </java-name> [Dot42.DexImport("getLocalAddress", "(Lorg/apache/http/params/HttpParams;)Ljava/net/InetAddress;", AccessFlags = 9)] public static global::Java.Net.InetAddress GetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.InetAddress); } /// <summary> /// <para>Sets the LOCAL_ADDRESS parameter value.</para><para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Lorg/apache/http/params/HttpParams;Ljava/net/InetAddress;)V", AccessFlags = 9)] public static void SetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params, global::Java.Net.InetAddress local) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnManagerPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the timeout in milliseconds used when retrieving an instance of org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager. </para><para>This parameter expects a value of type Long. </para> /// </summary> /// <java-name> /// TIMEOUT /// </java-name> [Dot42.DexImport("TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string TIMEOUT = "http.conn-manager.timeout"; /// <summary> /// <para>Defines the maximum number of connections per route. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type ConnPerRoute. </para> /// </summary> /// <java-name> /// MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("MAX_CONNECTIONS_PER_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; /// <summary> /// <para>Defines the maximum number of connections in total. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("MAX_TOTAL_CONNECTIONS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537)] public partial interface IConnManagerPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Allows for setting parameters relating to connection routes on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParamBean", AccessFlags = 33)] public partial class ConnRouteParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnRouteParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::DEFAULT_PROXY </para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultProxy(global::Org.Apache.Http.HttpHost defaultProxy) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::LOCAL_ADDRESS </para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Ljava/net/InetAddress;)V", AccessFlags = 1)] public virtual void SetLocalAddress(global::Java.Net.InetAddress address) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::FORCED_ROUTE </para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)] public virtual void SetForcedRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnRouteParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } }
// 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; using Xunit; using System.Reflection; namespace System.Diagnostics.TraceSourceTests { public sealed class TraceListenerCollectionClassTests : ListBaseTests<TraceListenerCollection> { public override TraceListenerCollection Create(int count = 0) { // TraceListenerCollection has an internal constructor // so we use a TraceSource to create one for us. var list = new TraceSource("Test").Listeners; list.Clear(); for (int i = 0; i < count; i++) { list.Add(CreateListener()); } return list; } public TraceListener CreateListener() { return new TestTraceListener(); } public override object CreateItem() { return CreateListener(); } public override bool IsReadOnly { get { return false; } } public override bool IsFixedSize { get { return false; } } public override bool IsSynchronized { get { return true; } } [Fact] public void TraceListenerIndexerTest() { var list = Create(); var item = CreateListener(); list.Add(item); Assert.Equal(item, list[0]); item = CreateListener(); list[0] = item; Assert.Equal(item, list[0]); } [Fact] public void TraceListenerNameIndexerTest() { var list = Create(); var item = CreateListener(); item.Name = "TestListener"; list.Add(item); Assert.Equal(item, list["TestListener"]); Assert.Equal(null, list["NO_EXIST"]); } [Fact] public void AddListenerTest() { var list = Create(); var item = CreateListener(); list.Add(item); Assert.Equal(item, list[0]); Assert.Throws<ArgumentNullException>(() => list.Add(null)); Assert.Equal(1, list.Count); } [Fact] public void AddRangeArrayTest() { var list = Create(); Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListener[])null)); var items = new TraceListener[] { CreateListener(), CreateListener(), }; list.AddRange(items); Assert.Equal(items[0], list[0]); Assert.Equal(items[1], list[1]); } [Fact] public void AddRangeCollectionTest() { var list = Create(); Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListenerCollection)null)); var items = Create(); var item0 = CreateListener(); var item1 = CreateListener(); items.Add(item0); items.Add(item1); list.AddRange(items); Assert.Equal(item0, list[0]); Assert.Equal(item1, list[1]); } [Fact] public void ContainsTest() { var list = Create(); var item = CreateListener(); list.Add(item); Assert.True(list.Contains(item)); item = CreateListener(); Assert.False(list.Contains(item)); Assert.False(list.Contains(null)); } [Fact] public void CopyToListenerTest() { var list = Create(2); var arr = new TraceListener[4]; list.CopyTo(arr, 1); Assert.Null(arr[0]); Assert.Equal(arr[1], list[0]); Assert.Equal(arr[2], list[1]); Assert.Null(arr[3]); } [Fact] public void IndexOfListenerTest() { var list = Create(2); var item = CreateListener(); list.Insert(1, item); var idx = list.IndexOf(item); Assert.Equal(1, idx); idx = list.IndexOf(null); Assert.Equal(-1, idx); item = CreateListener(); idx = list.IndexOf(item); Assert.Equal(-1, idx); } [Fact] public void InsertListenerTest() { var list = Create(2); var item = CreateListener(); list.Insert(1, item); Assert.Equal(3, list.Count); Assert.Equal(item, list[1]); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(5, item)); } [Fact] public void RemoveListenerTest() { var list = Create(); var item = new TestTraceListener("Test1"); list.Add(item); Assert.Equal(1, list.Count); list.Remove(item); Assert.Equal(0, list.Count); } [Fact] public void RemoveAtTest() { var list = Create(); var item = new TestTraceListener("Test1"); list.Add(item); list.RemoveAt(0); Assert.False(list.Contains(item)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); } [Fact] public void RemoveByNameTest() { var list = Create(); var item = new TestTraceListener("Test1"); list.Add(item); Assert.Equal(1, list.Count); list.Remove("NO_EXIST"); Assert.Equal(1, list.Count); list.Remove("Test1"); Assert.Equal(0, list.Count); } } public abstract class ListBaseTests<T> : CollectionBaseTests<T> where T : IList { public abstract bool IsReadOnly { get; } public abstract bool IsFixedSize { get; } public virtual object CreateNonItem() { return new object(); } [Fact] public virtual void AddTest() { var list = Create(); var item = CreateItem(); if (IsReadOnly || IsFixedSize) { Assert.Throws<NotSupportedException>(() => list.Add(item)); } else { list.Add(item); Assert.Equal(item, list[0]); } } [Fact] public virtual void AddExceptionTest() { var list = Create(); var item = CreateNonItem(); if (IsReadOnly || IsFixedSize) { Assert.Throws<NotSupportedException>(() => list.Add(item)); } else { AssertExtensions.Throws<ArgumentException>("value", () => list.Add(item)); } } [Fact] public virtual void IndexerGetTest() { var list = Create(); var item = CreateItem(); list.Add(item); Assert.Equal(item, list[0]); var item2 = CreateItem(); list[0] = item2; Assert.Equal(item2, list[0]); } [Fact] public virtual void IndexerSetTest() { var list = Create(3); var item = CreateItem(); if (IsReadOnly) { Assert.Throws<NotSupportedException>(() => list[1] = item); } else { list[1] = item; Assert.Equal(item, list[1]); var nonItem = CreateNonItem(); AssertExtensions.Throws<ArgumentException>("value", () => list[1] = nonItem); } } [Fact] public virtual void IndexOfTest() { var list = Create(); var item0 = CreateItem(); list.Add(item0); var item1 = CreateItem(); list.Add(item1); Assert.Equal(0, list.IndexOf(item0)); Assert.Equal(1, list.IndexOf(item1)); var itemN = CreateItem(); Assert.Equal(-1, list.IndexOf(itemN)); } [Fact] public virtual void InsertTest() { var list = Create(2); var item = CreateItem(); list.Insert(1, item); Assert.Equal(3, list.Count); Assert.Equal(item, list[1]); } [Fact] public virtual void InsertExceptionTest() { var list = Create(2); AssertExtensions.Throws<ArgumentException>("value", () => list.Insert(1, null)); } [Fact] public virtual void InsertExceptionTest2() { var list = Create(2); var item = CreateItem(); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, item)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(4, item)); } [Fact] public virtual void RemoveTest() { var list = Create(); var item = CreateItem(); list.Add(item); Assert.True(list.Contains(item)); list.Remove(item); Assert.False(list.Contains(item)); } [Fact] public virtual void IsReadOnlyTest() { var list = Create(); Assert.Equal(IsReadOnly, list.IsReadOnly); } [Fact] public virtual void IsFixedSizeTest() { var list = Create(); Assert.Equal(IsFixedSize, list.IsFixedSize); } } public abstract class CollectionBaseTests<T> : EnumerableBaseTests<T> where T : ICollection { public abstract bool IsSynchronized { get; } [Fact] public virtual void CountTest() { var list = Create(); Assert.Equal(0, list.Count); } [Fact] public virtual void SyncRootTest() { var list = Create(); var sync1 = list.SyncRoot; Assert.NotNull(sync1); var sync2 = list.SyncRoot; Assert.NotNull(sync2); Assert.Equal(sync1, sync2); } [Fact] public virtual void IsSynchronizedTest() { var list = Create(); var value = list.IsSynchronized; var expected = IsSynchronized; Assert.Equal(expected, value); } [Fact] public virtual void CopyToTest() { var list = Create(4); var arr = new object[4]; list.CopyTo(arr, 0); } [Fact] public virtual void CopyToTest2() { var list = Create(4); var arr = new object[6]; list.CopyTo(arr, 2); Assert.Null(arr[0]); Assert.Null(arr[1]); } [Fact] public virtual void CopyToExceptionTest() { var list = Create(4); var arr = new object[2]; AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => list.CopyTo(arr, 0)); } } public abstract class EnumerableBaseTests<T> where T : IEnumerable { public abstract T Create(int count = 0); public abstract object CreateItem(); [Fact] public virtual void GetEnumeratorEmptyTest() { var list = Create(); var enumerator = list.GetEnumerator(); Assert.NotNull(enumerator); Assert.Throws<InvalidOperationException>(() => enumerator.Current); var more = enumerator.MoveNext(); Assert.False(more); more = enumerator.MoveNext(); Assert.False(more); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public virtual void GetEnumeratorTest() { var list = Create(2); var enumerator = list.GetEnumerator(); Assert.NotNull(enumerator); Assert.Throws<InvalidOperationException>(() => enumerator.Current); var more = enumerator.MoveNext(); Assert.True(more); var item = enumerator.Current; more = enumerator.MoveNext(); Assert.True(more); more = enumerator.MoveNext(); Assert.False(more); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } }
// 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 !SILVERLIGHT using System; using System.Diagnostics.Contracts; namespace System.Net.Sockets { [Flags] public enum SocketFlags { None = 0, OutOfBand = 1, Peek = 2, DontRoute = 4, MaxIOVectorLength = 16, Truncated = 256, ControlDataTruncated = 512, Broadcast = 1024, Multicast = 2048, Partial = 32768, } public enum SocketType { Unknown = -1, Stream = 1, Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, } public enum SelectMode { SelectRead = 0, SelectWrite = 1, SelectError = 2, } public enum SocketOptionLevel { IP = 0, Tcp = 6, Udp = 17, IPv6 = 41, Socket = 65535, } public enum ProtocolType { Unknown = -1, IPv6HopByHopOptions = 0, Unspecified = 0, IP = 0, Icmp = 1, Igmp = 2, Ggp = 3, IPv4 = 4, Tcp = 6, Pup = 12, Udp = 17, Idp = 22, IPv6 = 41, IPv6RoutingHeader = 43, IPv6FragmentHeader = 44, IPSecEncapsulatingSecurityPayload = 50, IPSecAuthenticationHeader = 51, IcmpV6 = 58, IPv6NoNextHeader = 59, IPv6DestinationOptions = 60, ND = 77, Raw = 255, Ipx = 1000, Spx = 1256, SpxII = 1257, } public enum SocketOptionName { DontLinger = -129, ExclusiveAddressUse = -5, IPOptions = 1, NoDelay = 1, NoChecksum = 1, Debug = 1, BsdUrgent = 2, Expedited = 2, HeaderIncluded = 2, AcceptConnection = 2, TypeOfService = 3, ReuseAddress = 4, IpTimeToLive = 4, KeepAlive = 8, MulticastInterface = 9, MulticastTimeToLive = 10, MulticastLoopback = 11, AddMembership = 12, DropMembership = 13, DontFragment = 14, AddSourceMembership = 15, DropSourceMembership = 16, DontRoute = 16, BlockSource = 17, UnblockSource = 18, PacketInformation = 19, ChecksumCoverage = 20, HopLimit = 21, #if NETFRAMEWORK_4_0 IPProtectionLevel = 23, IPv6Only = 27, #endif Broadcast = 32, UseLoopback = 64, Linger = 128, OutOfBandInline = 256, SendBuffer = 4097, ReceiveBuffer = 4098, SendLowWater = 4099, ReceiveLowWater = 4100, SendTimeout = 4101, ReceiveTimeout = 4102, Error = 4103, Type = 4104, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, MaxConnections = 2147483647, } public class Socket { extern public int Available { get; } extern public ProtocolType ProtocolType { get; } extern public System.Net.EndPoint RemoteEndPoint { get; } extern public System.Net.EndPoint LocalEndPoint { get; } extern public static bool SupportsIPv4 { get; } extern public static bool SupportsIPv6 { get; } extern public bool Blocking { get; set; } extern public bool Connected { get; } extern public SocketType SocketType { get; } extern public AddressFamily AddressFamily { get; } public Socket EndAccept(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); return default(Socket); } public IAsyncResult BeginAccept(AsyncCallback callback, object state) { return default(IAsyncResult); } public int EndReceiveFrom(IAsyncResult asyncResult, ref System.Net.EndPoint endPoint) { Contract.Requires(asyncResult != null); return default(int); } public IAsyncResult BeginReceiveFrom(Byte[] buffer, int offset, int size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, AsyncCallback callback, object state) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(IAsyncResult); } public int EndReceive(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); return default(int); } public IAsyncResult BeginReceive(Byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(IAsyncResult); } public int EndSendTo(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); return default(int); } public IAsyncResult BeginSendTo(Byte[] buffer, int offset, int size, SocketFlags socketFlags, System.Net.EndPoint remoteEP, AsyncCallback callback, object state) { Contract.Requires(buffer != null); Contract.Requires(remoteEP != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(IAsyncResult); } public int EndSend(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); return default(int); } public IAsyncResult BeginSend(Byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(IAsyncResult); } public void EndConnect(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); } public IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, AsyncCallback callback, object state) { Contract.Requires(remoteEP != null); return default(IAsyncResult); } public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { Contract.Requires(checkError != null); } public bool Poll(int microSeconds, SelectMode mode) { return default(bool); } public Byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength) { return default(Byte[]); } public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Byte[] optionValue) { } public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { return default(object); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue) { Contract.Requires(optionValue != null); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Byte[] optionValue) { } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) { } public int IOControl(int ioControlCode, Byte[] optionInValue, Byte[] optionOutValue) { Contract.Requires(ioControlCode != -2147195266); return default(int); } public int ReceiveFrom(Byte[] buffer, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(Byte[] buffer, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(Byte[] buffer, int size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(Byte[] buffer, int offset, int size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(int); } public int Receive(Byte[] buffer, int offset, int size, SocketFlags socketFlags) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(int); } public int Receive(Byte[] buffer) { return default(int); } public int Receive(Byte[] buffer, SocketFlags socketFlags) { return default(int); } public int Receive(Byte[] buffer, int size, SocketFlags socketFlags) { return default(int); } public int SendTo(Byte[] buffer, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(Byte[] buffer, SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(Byte[] buffer, int size, SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(Byte[] buffer, int offset, int size, SocketFlags socketFlags, System.Net.EndPoint remoteEP) { Contract.Requires(buffer != null); Contract.Requires(remoteEP != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(int); } public int Send(Byte[] buffer, int offset, int size, SocketFlags socketFlags) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(offset <= buffer.Length); Contract.Requires(size >= 0); Contract.Requires(size <= (buffer.Length - offset)); return default(int); } public int Send(Byte[] buffer) { return default(int); } public int Send(Byte[] buffer, SocketFlags socketFlags) { return default(int); } public int Send(Byte[] buffer, int size, SocketFlags socketFlags) { return default(int); } public Socket Accept() { return default(Socket); } public void Listen(int backlog) { } //public void Shutdown(SocketShutdown how) //{ //} public void Close() { } public void Connect(System.Net.EndPoint remoteEP) { Contract.Requires(remoteEP != null); } public void Bind(System.Net.EndPoint localEP) { Contract.Requires(localEP != null); } public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { } } } #endif
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Linq; using Twilio.Converters; using Twilio.TwiML.Voice; namespace Twilio.TwiML { /// <summary> /// Response TwiML for Voice /// </summary> public class VoiceResponse : TwiML { /// <summary> /// Create a new VoiceResponse /// </summary> public VoiceResponse() : base("Response") { } /// <summary> /// Create a new <Connect/> element and append it as a child of this element. /// </summary> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> public VoiceResponse Connect(Uri action = null, Twilio.Http.HttpMethod method = null) { var newChild = new Connect(action, method); this.Append(newChild); return this; } /// <summary> /// Append a <Connect/> element as a child of this element /// </summary> /// <param name="connect"> A Connect instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Connect(Connect connect) { this.Append(connect); return this; } /// <summary> /// Create a new <Dial/> element and append it as a child of this element. /// </summary> /// <param name="number"> Phone number to dial, the body of the TwiML Element. </param> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="timeout"> Time to wait for answer </param> /// <param name="hangupOnStar"> Hangup call on star press </param> /// <param name="timeLimit"> Max time length </param> /// <param name="callerId"> Caller ID to display </param> /// <param name="record"> Record the call </param> /// <param name="trim"> Trim the recording </param> /// <param name="recordingStatusCallback"> Recording status callback URL </param> /// <param name="recordingStatusCallbackMethod"> Recording status callback URL method </param> /// <param name="recordingStatusCallbackEvent"> Recording status callback events </param> /// <param name="answerOnBridge"> Preserve the ringing behavior of the inbound call until the Dialed call picks up /// </param> /// <param name="ringTone"> Ringtone allows you to override the ringback tone that Twilio will play back to the caller /// while executing the Dial </param> /// <param name="recordingTrack"> To indicate which audio track should be recorded </param> /// <param name="sequential"> Used to determine if child TwiML nouns should be dialed in order, one after the other /// (sequential) or dial all at once (parallel). Default is false, parallel </param> /// <param name="referUrl"> Webhook that will receive future SIP REFER requests </param> /// <param name="referMethod"> The HTTP method to use for the refer Webhook </param> public VoiceResponse Dial(string number = null, Uri action = null, Twilio.Http.HttpMethod method = null, int? timeout = null, bool? hangupOnStar = null, int? timeLimit = null, string callerId = null, Dial.RecordEnum record = null, Dial.TrimEnum trim = null, Uri recordingStatusCallback = null, Twilio.Http.HttpMethod recordingStatusCallbackMethod = null, List<Dial.RecordingEventEnum> recordingStatusCallbackEvent = null, bool? answerOnBridge = null, Dial.RingToneEnum ringTone = null, Dial.RecordingTrackEnum recordingTrack = null, bool? sequential = null, Uri referUrl = null, Twilio.Http.HttpMethod referMethod = null) { var newChild = new Dial( number, action, method, timeout, hangupOnStar, timeLimit, callerId, record, trim, recordingStatusCallback, recordingStatusCallbackMethod, recordingStatusCallbackEvent, answerOnBridge, ringTone, recordingTrack, sequential, referUrl, referMethod ); this.Append(newChild); return this; } /// <summary> /// Append a <Dial/> element as a child of this element /// </summary> /// <param name="dial"> A Dial instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Dial(Dial dial) { this.Append(dial); return this; } /// <summary> /// Create a new <Echo/> element and append it as a child of this element. /// </summary> public VoiceResponse Echo() { var newChild = new Echo(); this.Append(newChild); return this; } /// <summary> /// Append a <Echo/> element as a child of this element /// </summary> /// <param name="echo"> A Echo instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Echo(Echo echo) { this.Append(echo); return this; } /// <summary> /// Create a new <Enqueue/> element and append it as a child of this element. /// </summary> /// <param name="name"> Friendly name, the body of the TwiML Element. </param> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="waitUrl"> Wait URL </param> /// <param name="waitUrlMethod"> Wait URL method </param> /// <param name="workflowSid"> TaskRouter Workflow SID </param> public VoiceResponse Enqueue(string name = null, Uri action = null, Twilio.Http.HttpMethod method = null, Uri waitUrl = null, Twilio.Http.HttpMethod waitUrlMethod = null, string workflowSid = null) { var newChild = new Enqueue(name, action, method, waitUrl, waitUrlMethod, workflowSid); this.Append(newChild); return this; } /// <summary> /// Append a <Enqueue/> element as a child of this element /// </summary> /// <param name="enqueue"> A Enqueue instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Enqueue(Enqueue enqueue) { this.Append(enqueue); return this; } /// <summary> /// Create a new <Gather/> element and append it as a child of this element. /// </summary> /// <param name="input"> Input type Twilio should accept </param> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="timeout"> Time to wait to gather input </param> /// <param name="speechTimeout"> Time to wait to gather speech input and it should be either auto or a positive /// integer. </param> /// <param name="maxSpeechTime"> Max allowed time for speech input </param> /// <param name="profanityFilter"> Profanity Filter on speech </param> /// <param name="finishOnKey"> Finish gather on key </param> /// <param name="numDigits"> Number of digits to collect </param> /// <param name="partialResultCallback"> Partial result callback URL </param> /// <param name="partialResultCallbackMethod"> Partial result callback URL method </param> /// <param name="language"> Language to use </param> /// <param name="hints"> Speech recognition hints </param> /// <param name="bargeIn"> Stop playing media upon speech </param> /// <param name="debug"> Allow debug for gather </param> /// <param name="actionOnEmptyResult"> Force webhook to the action URL event if there is no input </param> /// <param name="speechModel"> Specify the model that is best suited for your use case </param> /// <param name="enhanced"> Use enhanced speech model </param> public VoiceResponse Gather(List<Gather.InputEnum> input = null, Uri action = null, Twilio.Http.HttpMethod method = null, int? timeout = null, string speechTimeout = null, int? maxSpeechTime = null, bool? profanityFilter = null, string finishOnKey = null, int? numDigits = null, Uri partialResultCallback = null, Twilio.Http.HttpMethod partialResultCallbackMethod = null, Gather.LanguageEnum language = null, string hints = null, bool? bargeIn = null, bool? debug = null, bool? actionOnEmptyResult = null, Gather.SpeechModelEnum speechModel = null, bool? enhanced = null) { var newChild = new Gather( input, action, method, timeout, speechTimeout, maxSpeechTime, profanityFilter, finishOnKey, numDigits, partialResultCallback, partialResultCallbackMethod, language, hints, bargeIn, debug, actionOnEmptyResult, speechModel, enhanced ); this.Append(newChild); return this; } /// <summary> /// Append a <Gather/> element as a child of this element /// </summary> /// <param name="gather"> A Gather instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Gather(Gather gather) { this.Append(gather); return this; } /// <summary> /// Create a new <Hangup/> element and append it as a child of this element. /// </summary> public VoiceResponse Hangup() { var newChild = new Hangup(); this.Append(newChild); return this; } /// <summary> /// Append a <Hangup/> element as a child of this element /// </summary> /// <param name="hangup"> A Hangup instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Hangup(Hangup hangup) { this.Append(hangup); return this; } /// <summary> /// Create a new <Leave/> element and append it as a child of this element. /// </summary> public VoiceResponse Leave() { var newChild = new Leave(); this.Append(newChild); return this; } /// <summary> /// Append a <Leave/> element as a child of this element /// </summary> /// <param name="leave"> A Leave instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Leave(Leave leave) { this.Append(leave); return this; } /// <summary> /// Create a new <Pause/> element and append it as a child of this element. /// </summary> /// <param name="length"> Length in seconds to pause </param> public VoiceResponse Pause(int? length = null) { var newChild = new Pause(length); this.Append(newChild); return this; } /// <summary> /// Append a <Pause/> element as a child of this element /// </summary> /// <param name="pause"> A Pause instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Pause(Pause pause) { this.Append(pause); return this; } /// <summary> /// Create a new <Play/> element and append it as a child of this element. /// </summary> /// <param name="url"> Media URL, the body of the TwiML Element. </param> /// <param name="loop"> Times to loop media </param> /// <param name="digits"> Play DTMF tones for digits </param> public VoiceResponse Play(Uri url = null, int? loop = null, string digits = null) { var newChild = new Play(url, loop, digits); this.Append(newChild); return this; } /// <summary> /// Append a <Play/> element as a child of this element /// </summary> /// <param name="play"> A Play instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Play(Play play) { this.Append(play); return this; } /// <summary> /// Create a new <Queue/> element and append it as a child of this element. /// </summary> /// <param name="name"> Queue name, the body of the TwiML Element. </param> /// <param name="url"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="reservationSid"> TaskRouter Reservation SID </param> /// <param name="postWorkActivitySid"> TaskRouter Activity SID </param> public VoiceResponse Queue(string name = null, Uri url = null, Twilio.Http.HttpMethod method = null, string reservationSid = null, string postWorkActivitySid = null) { var newChild = new Queue(name, url, method, reservationSid, postWorkActivitySid); this.Append(newChild); return this; } /// <summary> /// Append a <Queue/> element as a child of this element /// </summary> /// <param name="queue"> A Queue instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Queue(Queue queue) { this.Append(queue); return this; } /// <summary> /// Create a new <Record/> element and append it as a child of this element. /// </summary> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="timeout"> Timeout to begin recording </param> /// <param name="finishOnKey"> Finish recording on key </param> /// <param name="maxLength"> Max time to record in seconds </param> /// <param name="playBeep"> Play beep </param> /// <param name="trim"> Trim the recording </param> /// <param name="recordingStatusCallback"> Status callback URL </param> /// <param name="recordingStatusCallbackMethod"> Status callback URL method </param> /// <param name="recordingStatusCallbackEvent"> Recording status callback events </param> /// <param name="transcribe"> Transcribe the recording </param> /// <param name="transcribeCallback"> Transcribe callback URL </param> public VoiceResponse Record(Uri action = null, Twilio.Http.HttpMethod method = null, int? timeout = null, string finishOnKey = null, int? maxLength = null, bool? playBeep = null, Record.TrimEnum trim = null, Uri recordingStatusCallback = null, Twilio.Http.HttpMethod recordingStatusCallbackMethod = null, List<Record.RecordingEventEnum> recordingStatusCallbackEvent = null, bool? transcribe = null, Uri transcribeCallback = null) { var newChild = new Record( action, method, timeout, finishOnKey, maxLength, playBeep, trim, recordingStatusCallback, recordingStatusCallbackMethod, recordingStatusCallbackEvent, transcribe, transcribeCallback ); this.Append(newChild); return this; } /// <summary> /// Append a <Record/> element as a child of this element /// </summary> /// <param name="record"> A Record instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Record(Record record) { this.Append(record); return this; } /// <summary> /// Create a new <Redirect/> element and append it as a child of this element. /// </summary> /// <param name="url"> Redirect URL, the body of the TwiML Element. </param> /// <param name="method"> Redirect URL method </param> public VoiceResponse Redirect(Uri url = null, Twilio.Http.HttpMethod method = null) { var newChild = new Redirect(url, method); this.Append(newChild); return this; } /// <summary> /// Append a <Redirect/> element as a child of this element /// </summary> /// <param name="redirect"> A Redirect instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Redirect(Redirect redirect) { this.Append(redirect); return this; } /// <summary> /// Create a new <Reject/> element and append it as a child of this element. /// </summary> /// <param name="reason"> Rejection reason </param> public VoiceResponse Reject(Reject.ReasonEnum reason = null) { var newChild = new Reject(reason); this.Append(newChild); return this; } /// <summary> /// Append a <Reject/> element as a child of this element /// </summary> /// <param name="reject"> A Reject instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Reject(Reject reject) { this.Append(reject); return this; } /// <summary> /// Create a new <Say/> element and append it as a child of this element. /// </summary> /// <param name="message"> Message to say, the body of the TwiML Element. </param> /// <param name="voice"> Voice to use </param> /// <param name="loop"> Times to loop message </param> /// <param name="language"> Message langauge </param> public VoiceResponse Say(string message = null, Say.VoiceEnum voice = null, int? loop = null, Say.LanguageEnum language = null) { var newChild = new Say(message, voice, loop, language); this.Append(newChild); return this; } /// <summary> /// Append a <Say/> element as a child of this element /// </summary> /// <param name="say"> A Say instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Say(Say say) { this.Append(say); return this; } /// <summary> /// Create a new <Sms/> element and append it as a child of this element. /// </summary> /// <param name="message"> Message body, the body of the TwiML Element. </param> /// <param name="to"> Number to send message to </param> /// <param name="from"> Number to send message from </param> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> /// <param name="statusCallback"> Status callback URL </param> public VoiceResponse Sms(string message = null, Types.PhoneNumber to = null, Types.PhoneNumber from = null, Uri action = null, Twilio.Http.HttpMethod method = null, Uri statusCallback = null) { var newChild = new Sms(message, to, from, action, method, statusCallback); this.Append(newChild); return this; } /// <summary> /// Append a <Sms/> element as a child of this element /// </summary> /// <param name="sms"> A Sms instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Sms(Sms sms) { this.Append(sms); return this; } /// <summary> /// Create a new <Pay/> element and append it as a child of this element. /// </summary> /// <param name="input"> Input type Twilio should accept </param> /// <param name="action"> Action URL </param> /// <param name="bankAccountType"> Bank account type for ach transactions. If set, payment method attribute must be /// provided and value should be set to ach-debit. defaults to consumer-checking </param> /// <param name="statusCallback"> Status callback URL </param> /// <param name="statusCallbackMethod"> Status callback method </param> /// <param name="timeout"> Time to wait to gather input </param> /// <param name="maxAttempts"> Maximum number of allowed retries when gathering input </param> /// <param name="securityCode"> Prompt for security code </param> /// <param name="postalCode"> Prompt for postal code and it should be true/false or default postal code </param> /// <param name="minPostalCodeLength"> Prompt for minimum postal code length </param> /// <param name="paymentConnector"> Unique name for payment connector </param> /// <param name="paymentMethod"> Payment method to be used. defaults to credit-card </param> /// <param name="tokenType"> Type of token </param> /// <param name="chargeAmount"> Amount to process. If value is greater than 0 then make the payment else create a /// payment token </param> /// <param name="currency"> Currency of the amount attribute </param> /// <param name="description"> Details regarding the payment </param> /// <param name="validCardTypes"> Comma separated accepted card types </param> /// <param name="language"> Language to use </param> public VoiceResponse Pay(Pay.InputEnum input = null, Uri action = null, Pay.BankAccountTypeEnum bankAccountType = null, Uri statusCallback = null, Pay.StatusCallbackMethodEnum statusCallbackMethod = null, int? timeout = null, int? maxAttempts = null, bool? securityCode = null, string postalCode = null, int? minPostalCodeLength = null, string paymentConnector = null, Pay.PaymentMethodEnum paymentMethod = null, Pay.TokenTypeEnum tokenType = null, string chargeAmount = null, string currency = null, string description = null, List<Pay.ValidCardTypesEnum> validCardTypes = null, Pay.LanguageEnum language = null) { var newChild = new Pay( input, action, bankAccountType, statusCallback, statusCallbackMethod, timeout, maxAttempts, securityCode, postalCode, minPostalCodeLength, paymentConnector, paymentMethod, tokenType, chargeAmount, currency, description, validCardTypes, language ); this.Append(newChild); return this; } /// <summary> /// Append a <Pay/> element as a child of this element /// </summary> /// <param name="pay"> A Pay instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Pay(Pay pay) { this.Append(pay); return this; } /// <summary> /// Create a new <Prompt/> element and append it as a child of this element. /// </summary> /// <param name="for_"> Name of the payment source data element </param> /// <param name="errorType"> Type of error </param> /// <param name="cardType"> Type of the credit card </param> /// <param name="attempt"> Current attempt count </param> public VoiceResponse Prompt(Prompt.ForEnum for_ = null, List<Prompt.ErrorTypeEnum> errorType = null, List<Prompt.CardTypeEnum> cardType = null, List<int> attempt = null) { var newChild = new Prompt(for_, errorType, cardType, attempt); this.Append(newChild); return this; } /// <summary> /// Append a <Prompt/> element as a child of this element /// </summary> /// <param name="prompt"> A Prompt instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Prompt(Prompt prompt) { this.Append(prompt); return this; } /// <summary> /// Create a new <Start/> element and append it as a child of this element. /// </summary> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> public VoiceResponse Start(Uri action = null, Twilio.Http.HttpMethod method = null) { var newChild = new Start(action, method); this.Append(newChild); return this; } /// <summary> /// Append a <Start/> element as a child of this element /// </summary> /// <param name="start"> A Start instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Start(Start start) { this.Append(start); return this; } /// <summary> /// Create a new <Stop/> element and append it as a child of this element. /// </summary> public VoiceResponse Stop() { var newChild = new Stop(); this.Append(newChild); return this; } /// <summary> /// Append a <Stop/> element as a child of this element /// </summary> /// <param name="stop"> A Stop instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Stop(Stop stop) { this.Append(stop); return this; } /// <summary> /// Create a new <Refer/> element and append it as a child of this element. /// </summary> /// <param name="action"> Action URL </param> /// <param name="method"> Action URL method </param> public VoiceResponse Refer(Uri action = null, Twilio.Http.HttpMethod method = null) { var newChild = new Refer(action, method); this.Append(newChild); return this; } /// <summary> /// Append a <Refer/> element as a child of this element /// </summary> /// <param name="refer"> A Refer instance. </param> [System.Obsolete("This method is deprecated, use .Append() instead.")] public VoiceResponse Refer(Refer refer) { this.Append(refer); return this; } /// <summary> /// Append a child TwiML element to this element returning this element to allow chaining. /// </summary> /// <param name="childElem"> Child TwiML element to add </param> public new VoiceResponse Append(TwiML childElem) { return (VoiceResponse) base.Append(childElem); } /// <summary> /// Add freeform key-value attributes to the generated xml /// </summary> /// <param name="key"> Option key </param> /// <param name="value"> Option value </param> public new VoiceResponse SetOption(string key, object value) { return (VoiceResponse) base.SetOption(key, value); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TinTorch.Dns.Areas.HelpPage.ModelDescriptions; using TinTorch.Dns.Areas.HelpPage.Models; namespace TinTorch.Dns.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.IsovistUtility; using SpatialAnalysis.Geometry; using SpatialAnalysis.Data; using MathNet.Numerics.Distributions; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.OptionalScenario { /// <summary> /// This class includes the mechanism for updating of the agent's state in optional scenarios and is designed for use in training process. /// </summary> /// <seealso cref="SpatialAnalysis.Agents.IAgent" /> internal class OptionalScenarioTrainer: IAgent { /// <summary> /// Gets or sets the body elasticity. /// </summary> /// <value>The body elasticity.</value> public double BodyElasticity { get; set; } /// <summary> /// Gets or sets the barrier friction. /// </summary> /// <value>The barrier friction.</value> public double BarrierFriction { get; set; } /// <summary> /// Gets or sets the barrier repulsion range. /// </summary> /// <value>The barrier repulsion range.</value> public double BarrierRepulsionRange { get; set; } /// <summary> /// Gets or sets the repulsion change rate. /// </summary> /// <value>The repulsion change rate.</value> public double RepulsionChangeRate { get; set; } /// <summary> /// Gets or sets the acceleration magnitude. /// </summary> /// <value>The acceleration magnitude.</value> public double AccelerationMagnitude { get; set; } /// <summary> /// Gets or sets the time-step. /// </summary> /// <value>The time step.</value> public double TimeStep { get; set; } /// <summary> /// Gets or sets the state of the edge collision. /// </summary> /// <value>The state of the edge collision.</value> public CollisionAnalyzer EdgeCollisionState { get; set; } /// <summary> /// Gets or sets the decision making period distribution. /// </summary> /// <value>The decision making period distribution.</value> public Exponential DecisionMakingPeriodDistribution { get; set; } /// <summary> /// Gets or sets the angle distribution lambda factor. /// </summary> /// <value>The angle distribution lambda factor.</value> public double AngleDistributionLambdaFactor { get; set; } /// <summary> /// Gets or sets the desirability distribution lambda factor. /// </summary> /// <value>The desirability distribution lambda factor.</value> public double DesirabilityDistributionLambdaFactor { get; set; } /// <summary> /// The trail points /// </summary> public static List<UV> TrailPoints = new List<UV>(); /// <summary> /// Gets or sets the report progress. /// </summary> /// <value>The report progress.</value> public ProgressReport ReportProgress { get; set; } /// <summary> /// The debuger /// </summary> public static StringBuilder Debuger = new StringBuilder(); /// <summary> /// Gets or sets the total walk time. /// </summary> /// <value>The total walk time.</value> public double TotalWalkTime { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> /// <value>The duration.</value> public double Duration { get; set; } /// <summary> /// Gets or sets the fixed time step. /// </summary> /// <value>The fixed time step.</value> public double FixedTimeStep { get; set; } /// <summary> /// Gets or sets the visibility cosine factor. /// </summary> /// <value>The visibility cosine factor.</value> public double VisibilityCosineFactor { get; set; } /// <summary> /// Gets or sets the decision making period. /// </summary> /// <value>The decision making period.</value> public double DecisionMakingPeriod { get; set; } /// <summary> /// Gets or sets the walk time. /// </summary> /// <value>The walk time.</value> public double WalkTime { get; set; } /// <summary> /// Gets or sets the angular velocity. /// </summary> /// <value>The angular velocity.</value> public double AngularVelocity { get; set; } /// <summary> /// Gets or sets the size of the body. /// </summary> /// <value>The size of the body.</value> public double BodySize { get; set; } /// <summary> /// Gets or sets the velocity magnitude. /// </summary> /// <value>The velocity magnitude.</value> public double VelocityMagnitude { get; set; } public StateBase _currentState; /// <summary> /// Gets or sets the current state of the agent. /// </summary> /// <value>The state of the current.</value> public StateBase CurrentState { get { return this._currentState; } set { this._currentState= value; } } /// <summary> /// Gets or sets the destination. /// </summary> /// <value>The destination.</value> public UV Destination { get; set; } /// <summary> /// Gets or sets the visibility angle. /// </summary> /// <value>The visibility angle.</value> public double VisibilityAngle { get; set; } private CellularFloor _cellularFloor { get; set; } private Dictionary<Cell, AgentEscapeRoutes> _escapeRouts { get; set; } private Random _random { get; set; } private Dictionary<Cell, double> _staticCost { get; set; } private double _isovistExternalRadius { get; set; } private int _destinationCount { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OptionalScenarioTrainer"/> class. /// </summary> /// <param name="host">The main document to which the agent belongs.</param> /// <param name="fixedTimeStep">The fixed time-step per milliseconds.</param> /// <param name="duration">The duration per hours.</param> public OptionalScenarioTrainer(OSMDocument host, double fixedTimeStep, double duration) { this._isovistExternalRadius = host.Parameters[AgentParameters.OPT_IsovistExternalDepth.ToString()].Value; this._destinationCount = (int)(host.Parameters[AgentParameters.OPT_NumberOfDestinations.ToString()].Value); this.Duration = duration; this.FixedTimeStep = fixedTimeStep / 1000.0d; this._random = new Random(DateTime.Now.Millisecond); this._cellularFloor = host.cellularFloor; this._staticCost = this._cellularFloor.GetStaticCost(); this._escapeRouts = new Dictionary<Cell, AgentEscapeRoutes>(); this.BarrierRepulsionRange = host.Parameters[AgentParameters.GEN_BarrierRepulsionRange.ToString()].Value; this.RepulsionChangeRate = host.Parameters[AgentParameters.GEN_MaximumRepulsion.ToString()].Value; this.BarrierFriction = host.Parameters[AgentParameters.GEN_BarrierFriction.ToString()].Value; this.BodyElasticity = host.Parameters[AgentParameters.GEN_AgentBodyElasticity.ToString()].Value; this.AccelerationMagnitude = host.Parameters[AgentParameters.GEN_AccelerationMagnitude.ToString()].Value; this.AngularVelocity = host.Parameters[AgentParameters.GEN_AngularVelocity.ToString()].Value; this.DesirabilityDistributionLambdaFactor = host.Parameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor.ToString()].Value; this.BodySize = host.Parameters[AgentParameters.GEN_BodySize.ToString()].Value; this.VelocityMagnitude = host.Parameters[AgentParameters.GEN_VelocityMagnitude.ToString()].Value; this.VisibilityAngle = host.Parameters[AgentParameters.GEN_VisibilityAngle.ToString()].Value; this.VisibilityCosineFactor = Math.Cos(this.VisibilityAngle / 2); this.AngleDistributionLambdaFactor = host.Parameters[AgentParameters.OPT_AngleDistributionLambdaFactor.ToString()].Value; this.DecisionMakingPeriodDistribution = new Exponential(1.0d / this.DecisionMakingPeriod); } /// <summary> /// Updates the agent. /// </summary> /// <param name="newState">The new state.</param> public void UpdateAgent(StateBase newState) { this.CurrentState = newState; this.TotalWalkTime = 0; this.WalkTime = 0.0d; this.EdgeCollisionState = null; this.Destination = null; while (this.TotalWalkTime < this.Duration) { this.TimeStep = this.FixedTimeStep; this.TotalWalkTime += this.FixedTimeStep; this.WalkTime += this.FixedTimeStep; while (this.TimeStep != 0.0d) { this.TimeStepUpdate(); } } } private void updateDestination() { try { //update the destination AgentEscapeRoutes escapeRoute = null; var vantageCell = this._cellularFloor.FindCell(this.CurrentState.Location); if (!this._escapeRouts.ContainsKey(vantageCell)) { try { escapeRoute = CellularIsovistCalculator.GetAgentEscapeRoutes( vantageCell, this._isovistExternalRadius, this._destinationCount, this._cellularFloor, this._staticCost, 0.0000001d); } catch (Exception) { //throw new ArgumentException("Escape Routes cannot be calculated for the agent training!"); //MessageBox.Show(e.Report()); //try //{ // escapeRoute = CellularIsovistCalculator.GetAgentEscapeRoutes( // vantageCell, // this._isovistRadius, // this._destinationCount, // this._cellularFloor, // this._staticCost, // 0.0000001d); //} //catch (Exception) { } } if (escapeRoute == null) { return; } this._escapeRouts.Add(vantageCell, escapeRoute); } else { escapeRoute = this._escapeRouts[vantageCell]; } this.DecisionMakingPeriod = this.DecisionMakingPeriodDistribution.Sample(); this.WalkTime = 0.0d; //updating desired state //filtering the destinations to those in the cone of vision var visibleDestinationList = new List<AgentCellDestination>(); foreach (var item in escapeRoute.Destinations) { UV direction = item.Destination - this.CurrentState.Location; direction.Unitize(); if (direction.DotProduct(this.CurrentState.Direction) >= this.VisibilityCosineFactor) { visibleDestinationList.Add(item); } } AgentCellDestination[] destinations; if (visibleDestinationList.Count > 0) { destinations = visibleDestinationList.ToArray(); visibleDestinationList.Clear(); visibleDestinationList = null; } else { destinations = escapeRoute.Destinations; } double[] normalizedAngleCost = new double[destinations.Length]; //between zero and 1 for (int i = 0; i < destinations.Length; i++) { UV direction = destinations[i].Destination - this.CurrentState.Location; direction.Unitize(); normalizedAngleCost[i] = (direction.DotProduct(this.CurrentState.Direction) + 1) / 2; } double[] weighted = new double[destinations.Length]; double sum = 0; for (int i = 0; i < destinations.Length; i++) { weighted[i] = this.AngleDistributionLambdaFactor * Math.Exp(-this.AngleDistributionLambdaFactor * normalizedAngleCost[i]) + this.DesirabilityDistributionLambdaFactor * Math.Exp(-this.DesirabilityDistributionLambdaFactor * destinations[i].DesirabilityCost); sum += weighted[i]; } double selected = this._random.NextDouble() * sum; sum = 0; int selectedIndex = 0; for (int i = 0; i < destinations.Length; i++) { sum += weighted[i]; if (sum > selected) { selectedIndex = i; break; } } this.Destination = destinations[selectedIndex].Destination; } catch (Exception) { //MessageBox.Show(e.Report()); } } /// <summary> /// Updates the time-step. /// </summary> /// <exception cref="System.ArgumentNullException"> /// Collision Analyzer failed! /// or /// Collision Analyzer failed! /// </exception> /// <exception cref="System.ArgumentException"> /// Collision not found /// or /// </exception> public void TimeStepUpdate() { try { #region update destination bool decisionPeriodUpdate = this.WalkTime > this.DecisionMakingPeriod; bool desiredStateIsNull = this.Destination == null; bool distanceToDestination = true; if (this.Destination != null) { distanceToDestination = UV.GetLengthSquared(this.CurrentState.Location, this.Destination) < .01d; } if (decisionPeriodUpdate || desiredStateIsNull || distanceToDestination || this.EdgeCollisionState.DistanceToBarrier < this.BodySize) { this.updateDestination(); } #endregion // make a copy of current state var newState = this.CurrentState.Copy(); var previousState = this.CurrentState.Copy(); // direction update var direction = this.Destination - newState.Location; direction.Unitize(); #region update barrier relation factors UV repulsionForce = new UV(0.0, 0.0); // this condition is for the first time only when walking begins if (this.EdgeCollisionState == null) { this.EdgeCollisionState = CollisionAnalyzer.GetCollidingEdge(newState.Location, this._cellularFloor, BarrierType.Field); } if (this.EdgeCollisionState != null) { //only if the barrier is visible to the agent the repulstion force will be applied if (this.EdgeCollisionState.NormalizedRepulsion.DotProduct(newState.Direction) >= 0.0d)//this.VisibilityCosineFactor) { } else { //calculate repulsion force repulsionForce = this.EdgeCollisionState.NormalizedRepulsion * this.LoadRepulsionMagnetude(); } } else { throw new ArgumentNullException("Collision Analyzer failed!"); } #endregion // find Acceleration force UV acceleration = this.AccelerationMagnitude * direction + repulsionForce; //update velocity newState.Velocity += acceleration * this.TimeStep; //check velocity magnetude against the cap if (newState.Velocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { newState.Velocity.Unitize(); newState.Velocity *= this.VelocityMagnitude; } //update location var location = newState.Location + this.TimeStep * newState.Velocity; newState.Location = location; //update the direction of the agent in the transformation matrix double deltaAngle = this.AngularVelocity * this.TimeStep; Axis axis = new Axis(this.CurrentState.Direction, direction, deltaAngle); newState.Direction = axis.V_Axis; this.CurrentState = newState; //checking for collisions var newEdgeCollisionState = CollisionAnalyzer.GetCollidingEdge(newState.Location, this._cellularFloor, BarrierType.Field); if (newEdgeCollisionState == null) { throw new ArgumentNullException("Collision Analyzer failed!"); } else { if (newEdgeCollisionState.DistanceToBarrier <= this.BodySize / 2) { var collision = CollisionAnalyzer.GetCollision(this.EdgeCollisionState, newEdgeCollisionState, this.BodySize / 2, OSMDocument.AbsoluteTolerance); if (collision == null) { throw new ArgumentException("Collision not found"); } else { double newTimeStep = 0.0; if (collision.TimeStepRemainderProportion <= 0) { newTimeStep = this.TimeStep; this.TimeStep = 0.0; } else { if (collision.TimeStepRemainderProportion > 1.0) { newTimeStep = 0; this.TimeStep = TimeStep; } else { newTimeStep = this.TimeStep * (1.0 - collision.TimeStepRemainderProportion); this.TimeStep = this.TimeStep - newTimeStep; } } // update velocity var velocity = this.CurrentState.Velocity + newTimeStep * acceleration; if (velocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { velocity.Unitize(); velocity *= this.VelocityMagnitude; } //decompose velocity UV normal = collision.GetCollisionNormal(); UV velocityVerticalComponent = normal * (normal.DotProduct(velocity)); double velocityVerticalComponentLength = velocityVerticalComponent.GetLength(); UV velocityHorizontalComponent = velocity - velocityVerticalComponent; double velocityHorizontalComponentLength = velocityHorizontalComponent.GetLength(); //decompose acceleration UV accelerationVerticalComponent = normal * (normal.DotProduct(acceleration)); // elasticity UV ve = this.BodyElasticity * velocityVerticalComponent; //friction double f1 = this.BarrierFriction * velocityVerticalComponentLength; double f2 = velocityHorizontalComponentLength; UV vf = velocityHorizontalComponent - Math.Min(f1, f2) * velocityHorizontalComponent / velocityHorizontalComponentLength; //update velocity var adjustedVelocity = vf - ve - newTimeStep * accelerationVerticalComponent; if (adjustedVelocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { adjustedVelocity.Unitize(); adjustedVelocity *= this.VelocityMagnitude; } newState.Velocity = adjustedVelocity; // update location if (newTimeStep == 0) { newState.Location = CurrentState.Location; } else { newState.Location = collision.CollisionPoint; } newState.Location += OSMDocument.PenaltyCollisionReaction * normal; //update direction deltaAngle = this.AngularVelocity * newTimeStep; axis = new Axis(this.CurrentState.Direction, direction, deltaAngle); newState.Direction = axis.V_Axis; //update state newEdgeCollisionState.DistanceToBarrier = this.BodySize / 2; newEdgeCollisionState.Location = newState.Location; this.EdgeCollisionState = newEdgeCollisionState; this.CurrentState = newState; } } else { //update state for the full timestep length this.EdgeCollisionState = newEdgeCollisionState; this.CurrentState = newState; this.TimeStep = 0.0d; } } } catch (Exception error) { throw new ArgumentException(error.Report()); } } /// <summary> /// Loads the repulsion magnitude. /// </summary> /// <returns>System.Double.</returns> public double LoadRepulsionMagnetude() { return Function.BezierRepulsionMethod(this.EdgeCollisionState.DistanceToBarrier); } /// <summary> /// Gets or sets the walked total length. /// </summary> /// <value>The total length of the walked.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double TotalWalkedLength { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Loads the repulsion vector's magnitude. /// </summary> /// <returns>System.Double.</returns> /// <exception cref="System.NotImplementedException"></exception> public double LoadRepulsionMagnitude() { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System; using System.Diagnostics; using System.Globalization; using System.Text; using System.Threading; namespace System.Text { internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal BaseCodePageEncoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) { // Need to load our replacement characters table. encoding = _encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) { return (encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char _cBestFit = '\0'; private InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (_oFallback.arrayBestFit == null) _oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); _iCount = _iSize = 1; _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') _cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit _cBestFit = '?'; _iCount = _iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. _iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (_iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } // Return the best fit character return _cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (_iCount >= 0) _iCount++; // Return true if we could do it. return (_iCount >= 0 && _iCount <= _iSize); } // How many characters left to output? public override int Remaining { get { return (_iCount > 0) ? _iCount : 0; } } // Clear the buffer public override unsafe void Reset() { _iCount = -1; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = _oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = _oFallback.arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback.arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (_oFallback.arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Util; namespace Sep.Git.Tfs.Core { public class GitTfsRemote : IGitTfsRemote { private static readonly Regex isInDotGit = new Regex("(?:^|/)\\.git(?:/|$)", RegexOptions.Compiled); private readonly Globals globals; private readonly TextWriter stdout; private readonly RemoteOptions remoteOptions; private readonly ConfigProperties properties; private int? maxChangesetId; private string maxCommitHash; private bool isTfsAuthenticated; public RemoteInfo RemoteInfo { get; private set; } public GitTfsRemote(RemoteInfo info, IGitRepository repository, RemoteOptions remoteOptions, Globals globals, ITfsHelper tfsHelper, TextWriter stdout, ConfigProperties properties) { this.remoteOptions = remoteOptions; this.globals = globals; this.stdout = stdout; this.properties = properties; Tfs = tfsHelper; Repository = repository; RemoteInfo = info; Id = info.Id; TfsUrl = info.Url; TfsRepositoryPath = info.Repository; TfsUsername = info.Username; TfsPassword = info.Password; Aliases = (info.Aliases ?? Enumerable.Empty<string>()).ToArray(); IgnoreRegexExpression = info.IgnoreRegex; IgnoreExceptRegexExpression = info.IgnoreExceptRegex; Autotag = info.Autotag; this.IsSubtree = CheckSubtree(); } private bool CheckSubtree() { var m = GitTfsConstants.RemoteSubtreeRegex.Match(this.Id); if (m.Success) { this.OwningRemoteId = m.Groups["owner"].Value; this.Prefix = m.Groups["prefix"].Value; return true; } return false; } public void EnsureTfsAuthenticated() { if (isTfsAuthenticated) return; Tfs.EnsureAuthenticated(); isTfsAuthenticated = true; } public int? InitialChangeset { get { return properties.InitialChangeset; } set { properties.InitialChangeset = value; } } public bool IsDerived { get { return false; } } public bool IsSubtree { get; private set; } public bool IsSubtreeOwner { get { return TfsRepositoryPath == null; } } public string Id { get; set; } public string TfsUrl { get { return Tfs.Url; } set { Tfs.Url = value; } } private string[] Aliases { get; set; } public bool Autotag { get; set; } public string TfsUsername { get { return Tfs.Username; } set { Tfs.Username = value; } } public string TfsPassword { get { return Tfs.Password; } set { Tfs.Password = value; } } public string TfsRepositoryPath { get; set; } /// <summary> /// Gets the TFS server-side paths of all subtrees of this remote. /// Valid if the remote has subtrees, which occurs when <see cref="TfsRepositoryPath"/> is null. /// </summary> public string[] TfsSubtreePaths { get { if (tfsSubtreePaths == null) tfsSubtreePaths = Repository.GetSubtrees(this).Select(x => x.TfsRepositoryPath).ToArray(); return tfsSubtreePaths; } } private string[] tfsSubtreePaths = null; public string IgnoreRegexExpression { get; set; } public string IgnoreExceptRegexExpression { get; set; } public IGitRepository Repository { get; set; } public ITfsHelper Tfs { get; set; } public string OwningRemoteId { get; private set; } public string Prefix { get; private set; } public bool ExportMetadatas { get; set; } public Dictionary<string, string> ExportWorkitemsMapping { get; set; } public int MaxChangesetId { get { InitHistory(); return maxChangesetId.Value; } set { maxChangesetId = value; } } public string MaxCommitHash { get { InitHistory(); return maxCommitHash; } set { maxCommitHash = value; } } private TfsChangesetInfo GetTfsChangesetById(int id) { return Repository.GetTfsChangesetById(RemoteRef, id); } private void InitHistory() { if (maxChangesetId == null) { var mostRecentUpdate = Repository.GetLastParentTfsCommits(RemoteRef).FirstOrDefault(); if (mostRecentUpdate != null) { MaxCommitHash = mostRecentUpdate.GitCommit; MaxChangesetId = mostRecentUpdate.ChangesetId; } else { MaxChangesetId = 0; } } } private const string WorkspaceDirectory = "~w"; private string WorkingDirectory { get { var dir = Repository.GetConfig(GitTfsConstants.WorkspaceConfigKey); if (this.IsSubtree) { if(dir != null) { return Path.Combine(dir, this.Prefix); } //find the relative path to the owning remote return Ext.CombinePaths(globals.GitDir, WorkspaceDirectory, OwningRemoteId, Prefix); } return dir ?? DefaultWorkingDirectory; } } private string DefaultWorkingDirectory { get { return Path.Combine(globals.GitDir, WorkspaceDirectory); } } public void CleanupWorkspace() { Tfs.CleanupWorkspaces(WorkingDirectory); } public void CleanupWorkspaceDirectory() { try { if (Directory.Exists(WorkingDirectory)) { var allFiles = Directory.EnumerateFiles(WorkingDirectory, "*", SearchOption.AllDirectories); foreach (var file in allFiles) File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); Directory.Delete(WorkingDirectory, true); } } catch (Exception ex) { Trace.WriteLine("CleanupWorkspaceDirectory: " + ex.Message); } } public bool ShouldSkip(string path) { return IsInDotGit(path) || IsIgnored(path); } private bool IsIgnored(string path) { return Ignorance.IsIncluded(path); } private Bouncer _ignorance; private Bouncer Ignorance { get { if (_ignorance == null) { _ignorance = new Bouncer(); _ignorance.Include(IgnoreRegexExpression); _ignorance.Include(remoteOptions.IgnoreRegex); _ignorance.Exclude(IgnoreExceptRegexExpression); _ignorance.Exclude(remoteOptions.ExceptRegex); } return _ignorance; } } private bool IsInDotGit(string path) { return isInDotGit.IsMatch(path); } public string GetPathInGitRepo(string tfsPath) { if (tfsPath == null) return null; if (!IsSubtreeOwner) { if (!tfsPath.StartsWith(TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)) return null; if (TfsRepositoryPath == GitTfsConstants.TfsRoot) { tfsPath = tfsPath.Substring(TfsRepositoryPath.Length); } else { if (tfsPath.Length > TfsRepositoryPath.Length && tfsPath[TfsRepositoryPath.Length] != '/') return null; tfsPath = tfsPath.Substring(TfsRepositoryPath.Length); } } else { //look through the subtrees var p = this.globals.Repository.GetSubtrees(this) .Where(x => x.IsSubtree) .FirstOrDefault(x => tfsPath.StartsWith(x.TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) && (tfsPath.Length == x.TfsRepositoryPath.Length || tfsPath[x.TfsRepositoryPath.Length] == '/')); if (p == null) return null; tfsPath = p.GetPathInGitRepo(tfsPath); //we must prepend the prefix in order to get the correct directory if (tfsPath.StartsWith("/")) tfsPath = p.Prefix + tfsPath; else tfsPath = p.Prefix + "/" + tfsPath; } while (tfsPath.StartsWith("/")) tfsPath = tfsPath.Substring(1); return tfsPath; } public class FetchResult : IFetchResult { public bool IsSuccess { get; set; } public int LastFetchedChangesetId { get; set; } public int NewChangesetCount { get; set; } public string ParentBranchTfsPath { get; set; } public bool IsProcessingRenameChangeset { get; set; } public string LastParentCommitBeforeRename { get; set; } } public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null) { return FetchWithMerge(-1, stopOnFailMergeCommit,lastChangesetIdToFetch, renameResult); } public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes) { return FetchWithMerge(mergeChangesetId, stopOnFailMergeCommit, -1, renameResult, parentCommitsHashes); } public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes) { var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 }; var latestChangesetId = GetLatestChangesetId(); if (lastChangesetIdToFetch != -1) latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch); // TFS 2010 doesn't like when we ask for history past its last changeset. if (MaxChangesetId >= latestChangesetId) return fetchResult; bool fetchRetrievedChangesets; do { var fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch); var objects = BuildEntryDictionary(); fetchRetrievedChangesets = false; foreach (var changeset in fetchedChangesets) { fetchRetrievedChangesets = true; fetchResult.NewChangesetCount++; if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch) return fetchResult; string parentCommitSha = null; if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha)) { fetchResult.IsSuccess = false; return fetchResult; } var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash; var isFirstCommitInRepository = (parentSha == null); var log = Apply(parentSha, changeset, objects); if (changeset.IsRenameChangeset && !isFirstCommitInRepository) { if (renameResult == null || !renameResult.IsProcessingRenameChangeset) { fetchResult.IsProcessingRenameChangeset = true; fetchResult.LastParentCommitBeforeRename = MaxCommitHash; return fetchResult; } renameResult.IsProcessingRenameChangeset = false; renameResult.LastParentCommitBeforeRename = null; } if (parentCommitSha != null) log.CommitParents.Add(parentCommitSha); if (changeset.Summary.ChangesetId == mergeChangesetId) { foreach (var parent in parentCommitsHashes) log.CommitParents.Add(parent); } var commitSha = ProcessChangeset(changeset, log); fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId; // set commit sha for added git objects foreach (var commit in objects) { if (commit.Value.Commit == null) commit.Value.Commit = commitSha; } DoGcIfNeeded(); } } while (fetchRetrievedChangesets && latestChangesetId > fetchResult.LastFetchedChangesetId); return fetchResult; } private Dictionary<string, GitObject> BuildEntryDictionary() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } private bool ProcessMergeChangeset(ITfsChangeset changeset, bool stopOnFailMergeCommit, ref string parentCommit) { if (!Tfs.CanGetBranchInformation) { stdout.WriteLine("info: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But was not treated as is because this version of TFS can't manage branches..."); } else if (!IsIgnoringBranches()) { var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this); if (parentChangesetId < 1) // Handle missing merge parent info { if (stopOnFailMergeCommit) return false; stdout.WriteLine("warning: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But git-tfs is unable to determine the parent changeset."); return true; } var shaParent = Repository.FindCommitHashByChangesetId(parentChangesetId); if (shaParent == null) { string omittedParentBranch; shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit, out omittedParentBranch); changeset.OmittedParentBranch = omittedParentBranch; } if (shaParent != null) { parentCommit = shaParent; } else { if (stopOnFailMergeCommit) return false; stdout.WriteLine("warning: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But git-tfs failed to find and fetch the parent changeset " + parentChangesetId + ". Parent changeset will be ignored..."); } } else { stdout.WriteLine("info: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But was not treated as is because of your git setting..."); changeset.OmittedParentBranch = ";C" + changeset.Summary.ChangesetId; } return true; } public bool IsIgnoringBranches() { var value = Repository.GetConfig<string>(GitTfsConstants.IgnoreBranches, null); bool isIgnoringBranches; if (value != null && bool.TryParse(value, out isIgnoringBranches)) return isIgnoringBranches; stdout.WriteLine("warning: no value found for branch management setting '" + GitTfsConstants.IgnoreBranches + "'..."); var isIgnoringBranchesDetected = Repository.ReadAllTfsRemotes().Count() < 2; stdout.WriteLine("=> Branch support " + (isIgnoringBranchesDetected ? "disabled!" : "enabled!")); if(isIgnoringBranchesDetected) stdout.WriteLine(" if you want to enable branch support, use the command:" + Environment.NewLine + " git config --local " + GitTfsConstants.IgnoreBranches + " false"); globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, isIgnoringBranchesDetected.ToString()); return isIgnoringBranchesDetected; } private string ProcessChangeset(ITfsChangeset changeset, LogEntry log) { if (ExportMetadatas) { if (changeset.Summary.Workitems.Any()) { var workItemIds = TranslateWorkItems(changeset.Summary.Workitems.Select(wi => wi.Id.ToString())); if (workItemIds != null) { log.Log += "\nwork-items: " + string.Join(", ", workItemIds.Select(s => "#" + s)); } } if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment)) log.Log += "\n" + GitTfsConstants.GitTfsPolicyOverrideCommentPrefix + changeset.Summary.PolicyOverrideComment; if (!string.IsNullOrWhiteSpace(changeset.Summary.CodeReviewer)) log.Log += "\n" + GitTfsConstants.GitTfsCodeReviewerPrefix + changeset.Summary.CodeReviewer; if (!string.IsNullOrWhiteSpace(changeset.Summary.SecurityReviewer)) log.Log += "\n" + GitTfsConstants.GitTfsSecurityReviewerPrefix + changeset.Summary.SecurityReviewer; if (!string.IsNullOrWhiteSpace(changeset.Summary.PerformanceReviewer)) log.Log += "\n" + GitTfsConstants.GitTfsPerformanceReviewerPrefix + changeset.Summary.PerformanceReviewer; } var commitSha = Commit(log); UpdateTfsHead(commitSha, changeset.Summary.ChangesetId); StringBuilder metadatas = new StringBuilder(); if (changeset.Summary.Workitems.Any()) { string workitemNote = "Workitems:\n"; foreach (var workitem in changeset.Summary.Workitems) { var workitemId = workitem.Id.ToString(); var workitemUrl = workitem.Url; if (ExportMetadatas && ExportWorkitemsMapping.Count != 0) { if (ExportWorkitemsMapping.ContainsKey(workitemId)) { var oldWorkitemId = workitemId; workitemId = ExportWorkitemsMapping[workitemId]; workitemUrl = workitemUrl.Replace(oldWorkitemId, workitemId); } } workitemNote += String.Format("[{0}] {1}\n {2}\n", workitemId, workitem.Title, workitemUrl); } metadatas.Append(workitemNote); } if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment)) metadatas.Append("\nPolicy Override Comment:" + changeset.Summary.PolicyOverrideComment); if (!string.IsNullOrWhiteSpace(changeset.Summary.CodeReviewer)) metadatas.Append("\nCode Reviewer:" + changeset.Summary.CodeReviewer); if (!string.IsNullOrWhiteSpace(changeset.Summary.SecurityReviewer)) metadatas.Append("\nSecurity Reviewer:" + changeset.Summary.SecurityReviewer); if (!string.IsNullOrWhiteSpace(changeset.Summary.PerformanceReviewer)) metadatas.Append("\nPerformance Reviewer:" + changeset.Summary.PerformanceReviewer); if (!string.IsNullOrWhiteSpace(changeset.OmittedParentBranch)) metadatas.Append("\nOmitted parent branch: " + changeset.OmittedParentBranch); if (metadatas.Length != 0) Repository.CreateNote(commitSha, metadatas.ToString(), log.AuthorName, log.AuthorEmail, log.Date); return commitSha; } private IEnumerable<string> TranslateWorkItems(IEnumerable<string> workItemsOriginal) { if (ExportWorkitemsMapping.Count == 0) return workItemsOriginal; List<string> workItemsTranslated = new List<string>(); if (workItemsOriginal == null) return workItemsTranslated; foreach (var oldWorkItemId in workItemsOriginal) { string translatedWorkItemId = null; if (oldWorkItemId != null && !ExportWorkitemsMapping.TryGetValue(oldWorkItemId, out translatedWorkItemId)) translatedWorkItemId = oldWorkItemId; if (translatedWorkItemId != null) workItemsTranslated.Add(translatedWorkItemId); } return workItemsTranslated; } private string FindRootRemoteAndFetch(int parentChangesetId, IRenameResult renameResult = null) { string omittedParentBranch; return FindRemoteAndFetch(parentChangesetId, false, false, renameResult, out omittedParentBranch); } private string FindMergedRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, out string omittedParentBranch) { return FindRemoteAndFetch(parentChangesetId, false, true, null, out omittedParentBranch); } private string FindRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch) { var tfsRemote = FindOrInitTfsRemoteOfChangeset(parentChangesetId, mergeChangeset, renameResult, out omittedParentBranch); if (tfsRemote != null && string.Compare(tfsRemote.TfsRepositoryPath, TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) != 0) { stdout.WriteLine("\tFetching from dependent TFS remote '{0}'...", tfsRemote.Id); try { var fetchResult = ((GitTfsRemote) tfsRemote).FetchWithMerge(-1, stopOnFailMergeCommit, parentChangesetId, renameResult); } finally { Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); if (tfsRemote.Repository.IsBare) tfsRemote.Repository.UpdateRef(GitRepository.ShortToLocalName(tfsRemote.Id), tfsRemote.MaxCommitHash); } return Repository.FindCommitHashByChangesetId(parentChangesetId); } return null; } private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch) { omittedParentBranch = null; IGitTfsRemote tfsRemote; IChangeset parentChangeset = Tfs.GetChangeset(parentChangesetId); //I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply. //Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!! var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null)); if (remote != null) tfsRemote = remote; else { // If the changeset has created multiple folders, the expected branch folder will not always be the first // so we scan all the changes of type folder to try to detect the first one which is a branch. // In most cases it will change nothing: the first folder is the good one IBranchObject tfsBranch = null; string tfsPath = null; var allBranches = Tfs.GetBranches(true); foreach (var change in parentChangeset.Changes) { tfsPath = change.Item.ServerItem; tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/"; tfsBranch = allBranches.SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/")); if(tfsBranch != null) { // we found a branch, we stop here break; } } if (mergeChangeset && tfsBranch != null && Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches) == true.ToString()) { stdout.WriteLine("warning: skip not initialized branch for path " + tfsBranch.Path); tfsRemote = null; omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId; } else if (tfsBranch == null) { stdout.WriteLine("error: branch not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath); tfsRemote = null; omittedParentBranch = ";C" + parentChangesetId; } else { tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId, renameResult); if (tfsRemote == null) omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId; } } return tfsRemote; } private IGitTfsRemote InitTfsRemoteOfChangeset(IBranchObject tfsBranch, int parentChangesetId, IRenameResult renameResult = null) { if (tfsBranch.IsRoot) { return InitTfsBranch(this.remoteOptions, tfsBranch.Path); } var branchesDatas = Tfs.GetRootChangesetForBranch(tfsBranch.Path, parentChangesetId); IGitTfsRemote remote = null; foreach (var branch in branchesDatas) { var rootChangesetId = branch.SourceBranchChangesetId; remote = InitBranch(this.remoteOptions, tfsBranch.Path, rootChangesetId, true); if (remote == null) { stdout.WriteLine("warning: root commit not found corresponding to changeset " + rootChangesetId); stdout.WriteLine("=> continuing anyway by creating a branch without parent..."); return InitTfsBranch(this.remoteOptions, tfsBranch.Path); } if (branch.IsRenamedBranch) { try { remote.Fetch(renameResult: renameResult); } finally { Trace.WriteLine("Cleaning..."); remote.CleanupWorkspaceDirectory(); if (remote.Repository.IsBare) remote.Repository.UpdateRef(GitRepository.ShortToLocalName(remote.Id), remote.MaxCommitHash); } } } return remote; } public void QuickFetch() { var changeset = GetLatestChangeset(); quickFetch(changeset); } public void QuickFetch(int changesetId) { var changeset = Tfs.GetChangeset(changesetId, this); quickFetch(changeset); } private void quickFetch(ITfsChangeset changeset) { var log = CopyTree(MaxCommitHash, changeset); UpdateTfsHead(Commit(log), changeset.Summary.ChangesetId); DoGcIfNeeded(); } private IEnumerable<ITfsChangeset> FetchChangesets(bool byLots, int lastVersion = -1) { int lowerBoundChangesetId; // If we're starting at the Root side of a branch commit (e.g. C1) but there are invalid commits between C1 and the actual branch-side of the commit operation // (e.g. a Folder with the branch name was created [C2] and then deleted [C3], THEN the root-side was branched [C4; C1 --branch--> C4]), this will detect // only the folder creation and deletion operations due to the lowerBound being detected as the root-side commit +1 (C1+1=C2) instead of referencing // the branch-side of the branching operation [C4]. if(properties.InitialChangeset.HasValue) lowerBoundChangesetId = Math.Max(MaxChangesetId + 1, properties.InitialChangeset.Value); else lowerBoundChangesetId = MaxChangesetId + 1; Trace.WriteLine(RemoteRef + ": Getting changesets from " + lowerBoundChangesetId + " to " + lastVersion + " ...", "info"); if (!IsSubtreeOwner) return Tfs.GetChangesets(TfsRepositoryPath, lowerBoundChangesetId, this, lastVersion, byLots); return globals.Repository.GetSubtrees(this) .SelectMany(x => Tfs.GetChangesets(x.TfsRepositoryPath, lowerBoundChangesetId, x, lastVersion, byLots)) .OrderBy(x => x.Summary.ChangesetId); } public ITfsChangeset GetChangeset(int changesetId) { return Tfs.GetChangeset(changesetId, this); } private ITfsChangeset GetLatestChangeset() { if (!string.IsNullOrEmpty(TfsRepositoryPath)) return Tfs.GetLatestChangeset(this); var changesetId = globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangeset(x)).Max(x => x.Summary.ChangesetId); return GetChangeset(changesetId); } private int GetLatestChangesetId() { if (!string.IsNullOrEmpty(TfsRepositoryPath)) return Tfs.GetLatestChangesetId(this); return globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangesetId(x)).Max(); } public void UpdateTfsHead(string commitHash, int changesetId) { MaxCommitHash = commitHash; MaxChangesetId = changesetId; Repository.UpdateRef(RemoteRef, MaxCommitHash, "C" + MaxChangesetId); if (Autotag) Repository.UpdateRef(TagPrefix + "C" + MaxChangesetId, MaxCommitHash); LogCurrentMapping(); } private void LogCurrentMapping() { stdout.WriteLine("C" + MaxChangesetId + " = " + MaxCommitHash); } private string TagPrefix { get { return "refs/tags/tfs/" + Id + "/"; } } public string RemoteRef { get { return "refs/remotes/tfs/" + Id; } } private void DoGcIfNeeded() { Trace.WriteLine("GC Countdown: " + globals.GcCountdown); if (--globals.GcCountdown < 0) { globals.GcCountdown = globals.GcPeriod; Repository.GarbageCollect(true, "Try running it after git-tfs is finished."); } } private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries) { return Apply(parent, changeset, entries, null); } private LogEntry Apply(string parent, ITfsChangeset changeset, Action<Exception> ignorableErrorHandler) { return Apply(parent, changeset, BuildEntryDictionary(), ignorableErrorHandler); } private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries, Action<Exception> ignorableErrorHandler) { LogEntry result = null; WithWorkspace(changeset.Summary, workspace => { var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(parent); result = changeset.Apply(parent, treeBuilder, workspace, entries, ignorableErrorHandler); result.Tree = treeBuilder.GetTree(); }); if (!String.IsNullOrEmpty(parent)) result.CommitParents.Add(parent); return result; } private LogEntry CopyTree(string lastCommit, ITfsChangeset changeset) { LogEntry result = null; WithWorkspace(changeset.Summary, workspace => { var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(null); result = changeset.CopyTree(treeBuilder, workspace); result.Tree = treeBuilder.GetTree(); }); if (!String.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit); return result; } private string Commit(LogEntry logEntry) { logEntry.Log = BuildCommitMessage(logEntry.Log, logEntry.ChangesetId); return Repository.Commit(logEntry).Sha; } private string BuildCommitMessage(string tfsCheckinComment, int changesetId) { var builder = new StringWriter(); builder.WriteLine(tfsCheckinComment); builder.WriteLine(GitTfsConstants.TfsCommitInfoFormat, TfsUrl, TfsRepositoryPath, changesetId); return builder.ToString(); } public void Unshelve(string shelvesetOwner, string shelvesetName, string destinationBranch, Action<Exception> ignorableErrorHandler, bool force) { var destinationRef = GitRepository.ShortToLocalName(destinationBranch); if(Repository.HasRef(destinationRef)) throw new GitTfsException("ERROR: Destination branch (" + destinationBranch + ") already exists!"); var shelvesetChangeset = Tfs.GetShelvesetData(this, shelvesetOwner, shelvesetName); var parentId = shelvesetChangeset.BaseChangesetId; var ch = GetTfsChangesetById(parentId); string rootCommit; if (ch == null) { if (!force) throw new GitTfsException("ERROR: Parent changeset C" + parentId + " not found.", new[] { "Try fetching the latest changes from TFS", "Try applying the shelveset on the currently checkouted commit using the '--force' option" } ); stdout.WriteLine("warning: Parent changeset C" + parentId + " not found." + " Trying to apply the shelveset on the current commit..."); rootCommit = Repository.GetCurrentCommit(); } else { rootCommit = ch.GitCommit; } var log = Apply(rootCommit, shelvesetChangeset, ignorableErrorHandler); var commit = Commit(log); Repository.UpdateRef(destinationRef, commit, "Shelveset " + shelvesetName + " from " + shelvesetOwner); } public void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies) { WithWorkspace(parentChangeset, workspace => Shelve(shelvesetName, head, parentChangeset, options, evaluateCheckinPolicies, workspace)); } public bool HasShelveset(string shelvesetName) { return Tfs.HasShelveset(shelvesetName); } private void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); workspace.Shelve(shelvesetName, evaluateCheckinPolicies, options, () => Repository.GetCommitMessage(head, parentChangeset.GitCommit)); } public int CheckinTool(string head, TfsChangesetInfo parentChangeset) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = CheckinTool(head, parentChangeset, workspace)); return changeset; } private int CheckinTool(string head, TfsChangesetInfo parentChangeset, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); return workspace.CheckinTool(() => Repository.GetCommitMessage(head, parentChangeset.GitCommit)); } private void PendChangesToWorkspace(string head, string parent, ITfsWorkspaceModifier workspace) { using (var tidyWorkspace = new DirectoryTidier(workspace, () => GetLatestChangeset().GetFullTree())) { foreach (var change in Repository.GetChangedFiles(parent, head)) { change.Apply(tidyWorkspace); } } } public int Checkin(string head, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parentChangeset.GitCommit, workspace, options, sourceTfsPath)); return changeset; } public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parent, workspace, options, sourceTfsPath)); return changeset; } private void WithWorkspace(TfsChangesetInfo parentChangeset, Action<ITfsWorkspace> action) { //are there any subtrees? var subtrees = globals.Repository.GetSubtrees(this); if (subtrees.Any()) { Tfs.WithWorkspace(WorkingDirectory, this, subtrees.Select(x => new Tuple<string, string>(x.TfsRepositoryPath, x.Prefix)), parentChangeset, action); } else { Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, action); } } private int Checkin(string head, string parent, ITfsWorkspace workspace, CheckinOptions options, string sourceTfsPath) { PendChangesToWorkspace(head, parent, workspace); if (!string.IsNullOrWhiteSpace(sourceTfsPath)) workspace.Merge(sourceTfsPath, TfsRepositoryPath); return workspace.Checkin(options, () => Repository.GetCommitMessage(head, parent)); } public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath) { if(!MatchesTfsUrl(tfsUrl)) return false; if(TfsRepositoryPath == null) return tfsRepositoryPath == null; return TfsRepositoryPath.Equals(tfsRepositoryPath, StringComparison.OrdinalIgnoreCase); } private bool MatchesTfsUrl(string tfsUrl) { return TfsUrl.Equals(tfsUrl, StringComparison.OrdinalIgnoreCase) || Aliases.Contains(tfsUrl, StringComparison.OrdinalIgnoreCase); } private string ExtractGitBranchNameFromTfsRepositoryPath(string tfsRepositoryPath) { var gitBranchName = Repository.AssertValidBranchName(tfsRepositoryPath.ToGitBranchNameFromTfsRepositoryPath()); stdout.WriteLine("The name of the local branch will be : " + gitBranchName); return gitBranchName; } public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null, IRenameResult renameResult = null) { return InitTfsBranch(remoteOptions, tfsRepositoryPath, rootChangesetId, fetchParentBranch, gitBranchNameExpected, renameResult); } private IGitTfsRemote InitTfsBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId = -1, bool fetchParentBranch = false, string gitBranchNameExpected = null, IRenameResult renameResult = null) { Trace.WriteLine("Begin process of creating branch for remote :" + tfsRepositoryPath); // TFS string representations of repository paths do not end in trailing slashes tfsRepositoryPath = (tfsRepositoryPath ?? string.Empty).TrimEnd('/'); string gitBranchName = ExtractGitBranchNameFromTfsRepositoryPath( string.IsNullOrWhiteSpace(gitBranchNameExpected) ? tfsRepositoryPath : gitBranchNameExpected); if (string.IsNullOrWhiteSpace(gitBranchName)) throw new GitTfsException("error: The Git branch name '" + gitBranchName + "' is not valid...\n"); Trace.WriteLine("Git local branch will be :" + gitBranchName); string sha1RootCommit = null; if (rootChangesetId != -1) { sha1RootCommit = Repository.FindCommitHashByChangesetId(rootChangesetId); if (fetchParentBranch && string.IsNullOrWhiteSpace(sha1RootCommit)) sha1RootCommit = FindRootRemoteAndFetch(rootChangesetId, renameResult); if (string.IsNullOrWhiteSpace(sha1RootCommit)) return null; Trace.WriteLine("Found commit " + sha1RootCommit + " for changeset :" + rootChangesetId); } IGitTfsRemote tfsRemote; if (Repository.HasRemote(gitBranchName)) { Trace.WriteLine("Remote already exist"); tfsRemote = Repository.ReadTfsRemote(gitBranchName); if (tfsRemote.TfsUrl != TfsUrl) Trace.WriteLine("warning: Url is different"); if (tfsRemote.TfsRepositoryPath != tfsRepositoryPath) Trace.WriteLine("warning: TFS repository path is different"); } else { Trace.WriteLine("Try creating remote..."); tfsRemote = Repository.CreateTfsRemote(new RemoteInfo { Id = gitBranchName, Url = TfsUrl, Repository = tfsRepositoryPath, RemoteOptions = remoteOptions }, string.Empty); } if (sha1RootCommit != null && !Repository.HasRef(tfsRemote.RemoteRef)) { if (!Repository.CreateBranch(tfsRemote.RemoteRef, sha1RootCommit)) throw new GitTfsException("error: Fail to create remote branch ref file!"); } Trace.WriteLine("Remote created!"); return tfsRemote; } } }
// ---------------------------------------------------------------------------------- // // 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.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common.Storage; using Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions.DSC; using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions { /// <summary> /// Uploads a Desired State Configuration script to Azure blob storage, which /// later can be applied to Azure Virtual Machines using the /// Set-AzureVMDscExtension cmdlet. /// </summary> [Cmdlet(VerbsData.Publish, "AzureVMDscConfiguration", SupportsShouldProcess = true, DefaultParameterSetName = UploadArchiveParameterSetName)] public class PublishAzureVMDscConfigurationCommand : ServiceManagementBaseCmdlet { private const string CreateArchiveParameterSetName = "CreateArchive"; private const string UploadArchiveParameterSetName = "UploadArchive"; /// <summary> /// Path to a file containing one or more configurations; the file can be a /// PowerShell script (*.ps1) or MOF interface (*.mof). /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file containing one or more configurations")] [ValidateNotNullOrEmpty] public string ConfigurationPath { get; set; } /// <summary> /// Name of the Azure Storage Container the configuration is uploaded to. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } /// <summary> /// By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs. /// Use -Force to overwrite them. /// </summary> [Parameter(HelpMessage = "By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs")] public SwitchParameter Force { get; set; } /// <summary> /// The Azure Storage Context that provides the security settings used to upload /// the configuration script to the container specified by ContainerName. This /// context should provide write access to the container. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "The Azure Storage Context that provides the security settings used to upload " + "the configuration script to the container specified by ContainerName")] [ValidateNotNullOrEmpty] public AzureStorageContext StorageContext { get; set; } /// <summary> /// Path to a local ZIP file to write the configuration archive to. /// When using this parameter, Publish-AzureVMDscConfiguration creates a /// local ZIP archive instead of uploading it to blob storage.. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CreateArchiveParameterSetName, HelpMessage = "Path to a local ZIP file to write the configuration archive to.")] [ValidateNotNullOrEmpty] public string ConfigurationArchivePath { get; set; } /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; private const string Ps1FileExtension = ".ps1"; private const string Psm1FileExtension = ".psm1"; private const string ZipFileExtension = ".zip"; private static readonly HashSet<String> UploadArchiveAllowedFileExtensions = new HashSet<String>(StringComparer.OrdinalIgnoreCase) { Ps1FileExtension, Psm1FileExtension, ZipFileExtension }; private static readonly HashSet<String> CreateArchiveAllowedFileExtensions = new HashSet<String>(StringComparer.OrdinalIgnoreCase) { Ps1FileExtension, Psm1FileExtension}; private const int MinMajorPowerShellVersion = 4; private List<string> _temporaryFilesToDelete = new List<string>(); private List<string> _temporaryDirectoriesToDelete = new List<string>(); protected override void ProcessRecord() { try { // Create a cloud context, only in case of upload. if (this.ParameterSetName == UploadArchiveParameterSetName) { base.ProcessRecord(); } ExecuteCommand(); } finally { foreach (var file in this._temporaryFilesToDelete) { try { DeleteFile(file); WriteVerbose(string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionDeletedFileMessage, file)); } catch (Exception e) { WriteVerbose(string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionDeleteErrorMessage, file, e.Message)); } } foreach (var directory in this._temporaryDirectoriesToDelete) { try { DeleteDirectory(directory); WriteVerbose(string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionDeletedFileMessage, directory)); } catch (Exception e) { WriteVerbose(string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionDeleteErrorMessage, directory, e.Message)); } } } } internal void ExecuteCommand() { ValidatePsVersion(); ValidateParameters(); PublishConfiguration(); } protected void ValidatePsVersion() { using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create()) { powershell.AddScript("$PSVersionTable.PSVersion.Major"); int major = powershell.Invoke<int>().FirstOrDefault(); if (major < MinMajorPowerShellVersion) { this.ThrowTerminatingError( new ErrorRecord( new InvalidOperationException( string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionRequiredPsVersion, MinMajorPowerShellVersion, major)), "InvalidPowerShellVersion", ErrorCategory.InvalidOperation, null)); } } } protected void ValidateParameters() { this.ConfigurationPath = this.GetUnresolvedProviderPathFromPSPath(this.ConfigurationPath); if (!File.Exists(this.ConfigurationPath)) { this.ThrowInvalidArgumentError(Resources.PublishVMDscExtensionUploadArchiveConfigFileNotExist, this.ConfigurationPath); } var configurationFileExtension = Path.GetExtension(this.ConfigurationPath); if (this.ParameterSetName == UploadArchiveParameterSetName) { // Check that ConfigurationPath points to a valid file if (!File.Exists(this.ConfigurationPath)) { this.ThrowInvalidArgumentError(Resources.PublishVMDscExtensionConfigFileNotFound, this.ConfigurationPath); } if (!UploadArchiveAllowedFileExtensions.Contains(Path.GetExtension(configurationFileExtension))) { this.ThrowInvalidArgumentError(Resources.PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension, this.ConfigurationPath); } this._storageCredentials = this.GetStorageCredentials(this.StorageContext); if (this.ContainerName == null) { this.ContainerName = VirtualMachineDscExtensionCmdletBase.DefaultContainerName; } } else if (this.ParameterSetName == CreateArchiveParameterSetName) { if (!CreateArchiveAllowedFileExtensions.Contains(Path.GetExtension(configurationFileExtension))) { this.ThrowInvalidArgumentError(Resources.PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension, this.ConfigurationPath); } this.ConfigurationArchivePath = this.GetUnresolvedProviderPathFromPSPath(this.ConfigurationArchivePath); } } /// <summary> /// Publish the configuration and its modules /// </summary> protected void PublishConfiguration() { if (this.ParameterSetName == CreateArchiveParameterSetName) { this.ConfirmAction(true, string.Empty, Resources.AzureVMDscCreateArchiveAction, this.ConfigurationArchivePath, ()=> CreateConfigurationArchive()); } else { var archivePath = string.Compare(Path.GetExtension(this.ConfigurationPath), ZipFileExtension, StringComparison.OrdinalIgnoreCase) == 0 ? this.ConfigurationPath : CreateConfigurationArchive(); UploadConfigurationArchive(archivePath); } } private string CreateConfigurationArchive() { WriteVerbose(String.Format(CultureInfo.CurrentUICulture, Resources.AzureVMDscParsingConfiguration, this.ConfigurationPath)); ConfigurationParseResult parseResult = null; try { parseResult = ConfigurationParsingHelper.ParseConfiguration(this.ConfigurationPath); } catch (GetDscResourceException e) { ThrowTerminatingError(new ErrorRecord(e, "CannotAccessDscResource", ErrorCategory.PermissionDenied, null)); } if (parseResult.Errors.Any()) { ThrowTerminatingError( new ErrorRecord( new ParseException( String.Format( CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionStorageParserErrors, this.ConfigurationPath, String.Join("\n", parseResult.Errors.Select(error => error.ToString())))), "DscConfigurationParseError", ErrorCategory.ParserError, null)); } List<string> requiredModules = parseResult.RequiredModules; //Since LCM always uses the latest module there is no need to copy PSDesiredStateConfiguration if (requiredModules.Contains("PSDesiredStateConfiguration")) { requiredModules.Remove("PSDesiredStateConfiguration"); } WriteVerbose(String.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionRequiredModulesVerbose, String.Join(", ", requiredModules))); // Create a temporary directory for uploaded zip file string tempZipFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); WriteVerbose(String.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionTempFolderVerbose, tempZipFolder)); Directory.CreateDirectory(tempZipFolder); this._temporaryDirectoriesToDelete.Add(tempZipFolder); // CopyConfiguration string configurationName = Path.GetFileName(this.ConfigurationPath); string configurationDestination = Path.Combine(tempZipFolder, configurationName); WriteVerbose(String.Format( CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionCopyFileVerbose, this.ConfigurationPath, configurationDestination)); File.Copy(this.ConfigurationPath, configurationDestination); // CopyRequiredModules foreach (var module in requiredModules) { using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create()) { // Wrapping script in a function to prevent script injection via $module variable. powershell.AddScript( @"function Copy-Module([string]$module, [string]$tempZipFolder) { $mi = Get-Module -List -Name $module; $moduleFolder = Split-Path $mi.Path; Copy-Item -Recurse -Path $moduleFolder -Destination ""$tempZipFolder\$($mi.Name)"" }" ); powershell.Invoke(); powershell.Commands.Clear(); powershell.AddCommand("Copy-Module") .AddParameter("module", module) .AddParameter("tempZipFolder", tempZipFolder); WriteVerbose(String.Format( CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionCopyModuleVerbose, module, tempZipFolder)); powershell.Invoke(); } } // // Zip the directory // string archive; if (this.ParameterSetName == CreateArchiveParameterSetName) { archive = this.ConfigurationArchivePath; if (!this.Force && System.IO.File.Exists(archive)) { this.ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException(string.Format(CultureInfo.CurrentUICulture, Resources.AzureVMDscArchiveAlreadyExists, archive)), "FileAlreadyExists", ErrorCategory.PermissionDenied, null)); } } else { string tempArchiveFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); WriteVerbose(String.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionTempFolderVerbose, tempArchiveFolder)); Directory.CreateDirectory(tempArchiveFolder); this._temporaryDirectoriesToDelete.Add(tempArchiveFolder); archive = Path.Combine(tempArchiveFolder, configurationName + ZipFileExtension); this._temporaryFilesToDelete.Add(archive); } if (File.Exists(archive)) { File.Delete(archive); } System.IO.Compression.ZipFile.CreateFromDirectory(tempZipFolder, archive); return archive; } private void UploadConfigurationArchive(string archivePath) { CloudBlobContainer cloudBlobContainer = GetStorageContainer(); var blobName = Path.GetFileName(archivePath); CloudBlockBlob modulesBlob = cloudBlobContainer.GetBlockBlobReference(blobName); this.ConfirmAction(true, string.Empty, string.Format(CultureInfo.CurrentUICulture, Resources.AzureVMDscUploadToBlobStorageAction, archivePath), modulesBlob.Uri.AbsoluteUri, () => { if (!this.Force && modulesBlob.Exists()) { this.ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException(string.Format(CultureInfo.CurrentUICulture, Resources.AzureVMDscStorageBlobAlreadyExists, modulesBlob.Uri.AbsoluteUri)), "StorageBlobAlreadyExists", ErrorCategory.PermissionDenied, null)); } modulesBlob.UploadFromFile(archivePath, FileMode.Open); WriteVerbose(string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionArchiveUploadedMessage, modulesBlob.Uri.AbsoluteUri)); }); } private CloudBlobContainer GetStorageContainer() { var storageAccount = new CloudStorageAccount(this._storageCredentials, true); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer containerReference = blobClient.GetContainerReference(this.ContainerName); containerReference.CreateIfNotExists(); return containerReference; } private static void DeleteFile(string path) { try { File.Delete(path); } catch (System.UnauthorizedAccessException) { // the exception may have occurred due to a read-only file DeleteReadOnlyFile(path); } } /// <summary> /// Turns off the ReadOnly attribute from the given file and then attemps to delete it /// </summary> private static void DeleteReadOnlyFile(string path) { var attributes = System.IO.File.GetAttributes(path); if ((attributes & FileAttributes.ReadOnly) != 0) { File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly); } File.Delete(path); } private static void DeleteDirectory(string path) { try { Directory.Delete(path, true); } catch (System.UnauthorizedAccessException) { // the exception may have occurred due to a read-only file or directory DeleteReadOnlyDirectory(path); } } /// <summary> /// Recusively turns off the ReadOnly attribute from the given directory and then attemps to delete it /// </summary> private static void DeleteReadOnlyDirectory(string path) { var directory = new DirectoryInfo(path); foreach (var child in directory.GetDirectories()) { DeleteReadOnlyDirectory(child.FullName); } foreach (var child in directory.GetFiles()) { DeleteReadOnlyFile(child.FullName); } if ((directory.Attributes & FileAttributes.ReadOnly) != 0) { directory.Attributes &= ~FileAttributes.ReadOnly; } directory.Delete(); } } }
namespace iTin.Export.Model { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Serialization; using ComponentModel; using Helpers; /// <summary> /// Base class for model elements. /// Implements functionality to record and read configuration files. /// </summary> /// <typeparam name="T">Represents a model node type</typeparam> [Serializable] public class BaseModel<T> { #region private constants private const string DefaultClassName = "BuiltInFunctions"; #endregion #region private static memebrs [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static XmlSerializer _serializer; #endregion #region private members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private PropertiesModel _properties; #endregion #region public properties #region [public] (PropertiesModel) Properties: Gets or sets a reference to user-defined property list for this element /// <summary> /// Gets or sets a reference to user-defined property list for this element. /// </summary> /// <value> /// List of user-defined properties available for this element. /// </value> [XmlIgnore] [XmlArrayItem("Property", typeof(PropertyModel), IsNullable = false)] public PropertiesModel Properties { get { if (_properties == null) { _properties = new PropertiesModel(); } foreach (var property in _properties) { property.SetOwner(_properties); } return _properties; } set => _properties = value; } #endregion #endregion #region public virtual properties #region [public] {virtual} (bool) IsDefault: When overridden in a derived class, gets a value indicating whether this instance contains the default /// <summary> /// When overridden in a derived class, gets a value indicating whether this instance contains the default. /// </summary> /// <value> /// <strong>true</strong> if this instance contains the default; otherwise, <strong>false</strong>. /// </value> [Browsable(false)] public virtual bool IsDefault => true; #endregion #endregion #region public virtual methods #region [public] {virtual} (void) SaveToFile(string): Serializes current BaseModel object into an Xml document /// <summary> /// Saves to file. /// </summary> /// <param name="fileName">Name of the file.</param> public virtual void SaveToFile(string fileName) { SentinelHelper.ArgumentNull(fileName); try { var xmlString = Serialize(); xmlString = xmlString .Replace("<References />", string.Empty) .Replace("<Properties />", string.Empty) .Replace("<Font />", string.Empty) .Replace("<Text />", string.Empty) .Replace("<Lines />", string.Empty) .Replace("<Images />", string.Empty) .Replace("<Margins />", string.Empty) .Replace("<Alignment />", string.Empty) .Replace("<Fixed />", string.Empty) .Replace("<Styles />", string.Empty) .Replace("<Groups />", string.Empty) .Replace("<Negative />", string.Empty) .Replace("<Pattern />", string.Empty) .Replace("<Borders />", string.Empty) .Replace("<Filter />", string.Empty) .Replace("<BlockLines />", string.Empty) .Replace("<Header />", string.Empty) .Replace("<Headers />", string.Empty) .Replace("<Footer />", string.Empty) .Replace("<Charts />", string.Empty) .Replace("<Plots />", string.Empty) .Replace("<Series />", string.Empty) .Replace("<Behaviors />", string.Empty) .Replace("<Aggregate />", string.Empty); var xmlFile = new FileInfo(fileName); using (var stream = xmlFile.CreateText()) { stream.Write(xmlString); stream.Flush(); } } catch { // re-throw throw; } } #endregion #region [public] {virtual} (bool) SaveToFile(string, out Exception): Serializes current BaseModel object into file /// <summary> /// Serializes current BaseModel object into file /// </summary> /// <param name="fileName">Full path of output Xml file</param> /// <param name="exception">Output Exception value if failed</param> /// <returns> /// <strong>true</strong> if can serialize and save into file; otherwise, <strong>false</strong>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] public virtual bool SaveToFile(string fileName, out Exception exception) { SentinelHelper.ArgumentNull(fileName); exception = null; try { SaveToFile(fileName); return true; } catch (Exception ex) { exception = ex; return false; } } #endregion #region [public] {virtual} (string) Serialize(): Serializes current BaseModel object into an Xml document /// <summary> /// Serializes current BaseModel object into an Xml document. /// </summary> /// <returns> /// string Xml value. /// </returns> public virtual string Serialize() { MemoryStream stream = null; try { string xml; stream = new MemoryStream(); Serializer.Serialize(stream, this); stream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(stream)) { stream = null; xml = streamReader.ReadToEnd(); } return xml; } finally { stream?.Dispose(); } } #endregion #endregion #region public overrides methods #region [public] {override} (string) ToString(): Returns a string that represents the current object /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String" /> that represents the current object. /// </returns> public override string ToString() { return !IsDefault ? "Modified" : "Default"; } #endregion #endregion #region protected virtual methods #region [protected] {virtual} (string) GetStaticBindingValue(string): Gets the static binding value by reflection /// <summary> /// Gets the static binding value by reflection. /// </summary> /// <param name="value">The value.</param> /// <returns> /// A <see cref="T:System.String" /> that contains property, method or raw value. /// </returns> protected virtual string GetStaticBindingValue(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } var isBinded = RegularExpressionHelper.IsStaticBindingResource(value); if (!isBinded) { return value; } var assemblies = new List<Assembly> { GetType().Assembly }; var references = ModelService.Instance.References; foreach (var reference in references) { var assemblyName = reference.Assembly.ToUpperInvariant(); var hasExtension = assemblyName.EndsWith(".DLL"); if (!hasExtension) { assemblyName = string.Concat(assemblyName, ".DLL"); } var assemblyRelativePath = reference.Path; var qualifiedAssemblyPath = string.Concat(assemblyRelativePath, assemblyName); var qualifiedAssemblyPathParsed = PathHelper.ResolveRelativePath(qualifiedAssemblyPath); //, root); var assembly = Assembly.LoadFile(qualifiedAssemblyPathParsed); assemblies.Add(assembly); } object returnValue; var targetValue = value.Replace("{", string.Empty).Replace("}", string.Empty).Trim(); var bindParts = targetValue.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); var qualifiedFunctionName = bindParts[1].Trim(); string className; string functionName; var qualifiedFunctionParts = qualifiedFunctionName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (qualifiedFunctionParts.Length == 1) { className = DefaultClassName; functionName = qualifiedFunctionParts[0].Trim(); } else { className = qualifiedFunctionParts[0].Trim(); functionName = qualifiedFunctionParts[1].Trim(); } var casm = assemblies.Count == 1 ? assemblies.First() : assemblies.Last(); var assemblyTypes = casm.GetExportedTypes(); var classType = assemblyTypes.FirstOrDefault(cls => cls.Name == className); var instanceMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Instance); if (instanceMethodInfo != null) { returnValue = instanceMethodInfo.Invoke(this, null); } else { var staticMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Static); if (staticMethodInfo != null) { returnValue = staticMethodInfo.Invoke(null, null); } else { var instancePropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (instancePropertyInfo != null) { var instancePropertyGetMethod = instancePropertyInfo.GetGetMethod(true); returnValue = instancePropertyGetMethod.Invoke(this, null); } else { var staticPropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.FlattenHierarchy); var staticPropertyGetMethod = staticPropertyInfo.GetGetMethod(true); returnValue = staticPropertyGetMethod.Invoke(null, null); } } } return returnValue.ToString(); } #endregion #endregion #region public static methods #region [public] {static} (T) Deserialize(string): Deserializes the specified Xml /// <summary> /// Deserializes the specified Xml. /// </summary> /// <param name="xml">The Xml.</param> /// <returns> /// T object /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Deserialize(string xml) { SentinelHelper.ArgumentNull(xml); StringReader reader = null; try { reader = new StringReader(xml); return (T)Serializer.Deserialize(XmlReader.Create(reader)); } finally { reader?.Dispose(); } } #endregion #region [public] {static} (T) Deserialize(Stream): Deserializes the specified stream /// <summary> /// Deserializes the specified stream. /// </summary> /// <param name="stream">Stream to deserialize.</param> /// <returns> /// T object /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Deserialize(Stream stream) { return (T)Serializer.Deserialize(stream); } #endregion #region [public] {static} (bool) Deserialize(string, out T): Deserializes the specified Xml /// <summary> /// Deserializes the specified Xml. /// </summary> /// <param name="xml">Xml to deserialize.</param> /// <param name="obj">The object.</param> /// <returns> /// T object /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] public static bool Deserialize(string xml, out T obj) { SentinelHelper.ArgumentNull(xml); return Deserialize(xml, out obj, out var exception); } #endregion #region [public] {static} (bool) Deserialize(string, out T, out Exception): Deserializes workflow markup into an BaseModel object /// <summary> /// Deserializes workflow markup into an BaseModel object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output BaseModel object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns> /// <strong>true</strong> if this XmlSerializer can deserialize the object; otherwise, <strong>false</strong> /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#"), SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")] public static bool Deserialize(string xml, out T obj, out Exception exception) { SentinelHelper.ArgumentNull(xml); exception = null; obj = default(T); try { obj = Deserialize(xml); return true; } catch (Exception ex) { exception = ex; return false; } } #endregion #region [public] {static} (T) LoadFromFile(string): Loads from file /// <summary> /// Loads from file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns> /// T object /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T LoadFromFile(string fileName) { SentinelHelper.ArgumentNull(fileName); FileStream file = null; try { string xmlString; file = new FileStream(fileName, FileMode.Open, FileAccess.Read); using (var reader = new StreamReader(file)) { file = null; xmlString = reader.ReadToEnd(); } return Deserialize(xmlString); } finally { file?.Dispose(); } } #endregion #region [public] {static} (T) LoadFromUri(Uri): Loads from file /// <summary> /// Loads from file. /// </summary> /// <param name="pathUri">Name of the file.</param> /// <returns> /// T object /// </returns> public static T LoadFromUri(Uri pathUri) { SentinelHelper.ArgumentNull(pathUri); return LoadFromFile(pathUri.LocalPath); } #endregion #region [public] {static} (bool) LoadFromFile(string, out T): Loads from file /// <summary> /// Loads from file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="obj">The object.</param> /// <returns> /// T object /// </returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static bool LoadFromFile(string fileName, out T obj) { SentinelHelper.IsTrue(string.IsNullOrEmpty(fileName)); return LoadFromFile(fileName, out obj, out var exception); } #endregion #region [public] {static} (bool) LoadFromFile(string, out T obj, out Exception): Deserializes xml markup from file into an BaseModel object /// <summary> /// Deserializes xml markup from file into an BaseModel object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output BaseModel object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns> /// <strong>true</strong> if this XmlSerializer can deserialize the object; otherwise, <strong>false</strong>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")] public static bool LoadFromFile(string fileName, out T obj, out Exception exception) { SentinelHelper.IsTrue(string.IsNullOrEmpty(fileName)); exception = null; obj = default(T); try { obj = LoadFromFile(fileName); return true; } catch (Exception ex) { exception = ex; return false; } } #endregion #endregion #region private static properties #region [private] {static} (XmlSerializer) Serializer: Gets the serializer reference /// <summary> /// Gets the serializer reference. /// </summary> /// <value> /// Serializer reference. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static XmlSerializer Serializer => _serializer ?? (_serializer = new XmlSerializer(typeof(T))); #endregion #endregion } } //#region [protected] {virtual} (string) GetValueByReflection(string): Gets the value by reflection ///// <summary> ///// Gets the value by reflection. ///// </summary> ///// <param name="value">The value.</param> ///// <returns> ///// A <see cref="T:System.String" /> that contains property, method or raw value. ///// </returns> //protected virtual string GetValueByReflection(string value) //ExportModel model, string value) //{ // if (string.IsNullOrEmpty(value)) // { // return string.Empty; // } // var linked = RegularExpressionHelper.IsBindableResource(value); // if (!linked) // { // return value; // } // var assemblies = new List<Assembly> { GetType().Assembly }; // var references = model.Owner.References; // foreach (var reference in references) // { // var assemblyName = reference.Assembly.ToUpperInvariant(); // var hasExtension = assemblyName.EndsWith(".DLL"); // if (!hasExtension) // { // assemblyName = string.Concat(assemblyName, ".DLL"); // } // var assemblyRelativePath = reference.Path; // var qualifiedAssemblyPath = string.Concat(assemblyRelativePath, assemblyName); // var qualifiedAssemblyPathParsed = model.ParseRelativeFilePath(qualifiedAssemblyPath); // var assembly = Assembly.LoadFile(qualifiedAssemblyPathParsed); // assemblies.Add(assembly); // } // object returnValue; // var targetValue = value.Replace("{", string.Empty).Replace("}", string.Empty).Trim(); // var bindParts = targetValue.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); // var qualifiedFunctionName = bindParts[1].Trim(); // string className; // string functionName; // var qualifiedFunctionParts = qualifiedFunctionName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); // if (qualifiedFunctionParts.Length == 1) // { // className = DefaultClassName; // functionName = qualifiedFunctionParts[0].Trim(); // } // else // { // className = qualifiedFunctionParts[0].Trim(); // functionName = qualifiedFunctionParts[1].Trim(); // } // var casm = assemblies.Count == 1 ? assemblies.First() : assemblies.Last(); // var assemblyTypes = casm.GetExportedTypes(); // var classType = assemblyTypes.FirstOrDefault(cls => cls.Name == className); // var instanceMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Instance); // if (instanceMethodInfo != null) // { // returnValue = instanceMethodInfo.Invoke(this, null); // } // else // { // var staticMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Static); // if (staticMethodInfo != null) // { // returnValue = staticMethodInfo.Invoke(null, null); // } // else // { // var instancePropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); // if (instancePropertyInfo != null) // { // var instancePropertyGetMethod = instancePropertyInfo.GetGetMethod(true); // returnValue = instancePropertyGetMethod.Invoke(this, null); // } // else // { // var staticPropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.FlattenHierarchy); // var staticPropertyGetMethod = staticPropertyInfo.GetGetMethod(true); // returnValue = staticPropertyGetMethod.Invoke(null, null); // } // } // } // return returnValue.ToString(); //} //#endregion //protected virtual string GetValueByReflection(string value) //{ // if (string.IsNullOrEmpty(value)) // { // return string.Empty; // } // var isValidStaticResource = RegularExpressionHelper.IsValidStaticResource(value); // if (!isValidStaticResource) // { // return value; // } // var assemblies = new List<Assembly>(); // var references = model.Owner.References; // foreach (var reference in references) // { // var assemblyName = reference.Assembly.ToUpperInvariant(); // var hasExtension = assemblyName.EndsWith(".DLL"); // if (!hasExtension) // { // assemblyName = string.Concat(assemblyName, ".DLL"); // } // var assemblyRelativePath = reference.Path; // var qualifiedAssemblyPath = string.Concat(assemblyRelativePath, assemblyName); // var qualifiedAssemblyPathParsed = model.ParseRelativeFilePath(qualifiedAssemblyPath); // var assembly = Assembly.LoadFile(qualifiedAssemblyPathParsed); // assemblies.Add(assembly); // } // object returnValue; // var targetValue = value.Replace("{", string.Empty).Replace("}", string.Empty).Trim(); // var bindParts = targetValue.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); // var qualifiedFunctionName = bindParts[1].Trim(); // string functionName; // var classType = this.GetType(); // var qualifiedFunctionParts = qualifiedFunctionName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); // if (qualifiedFunctionParts.Count() == 1) // { // functionName = qualifiedFunctionParts[0].Trim(); // } // else // { // var className = qualifiedFunctionParts[0].Trim(); // functionName = qualifiedFunctionParts[1].Trim(); // var casm = assemblies.Count == 1 ? assemblies.First() : assemblies.Last(); // var assemblyTypes = casm.GetExportedTypes(); // classType = assemblyTypes.FirstOrDefault(cls => cls.Name == className); // } // var instanceMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Instance); // if (instanceMethodInfo != null) // { // returnValue = instanceMethodInfo.Invoke(this, null); // } // else // { // var staticMethodInfo = classType.GetMethod(functionName, BindingFlags.Public | BindingFlags.Static); // if (staticMethodInfo != null) // { // returnValue = staticMethodInfo.Invoke(null, null); // } // else // { // var instancePropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); // if (instancePropertyInfo != null) // { // var instancePropertyGetMethod = instancePropertyInfo.GetGetMethod(true); // returnValue = instancePropertyGetMethod.Invoke(this, null); // } // else // { // var staticPropertyInfo = classType.GetProperty(functionName, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.FlattenHierarchy); // var staticPropertyGetMethod = staticPropertyInfo.GetGetMethod(true); // returnValue = staticPropertyGetMethod.Invoke(null, null); // } // } // } // return returnValue.ToString(); //}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if SUPPORTS_WINDOWSIDENTITY using System.Collections.Generic; using System.IdentityModel.Policy; using System.Runtime; using System.Security; using System.Security.Principal; using System.ServiceModel; namespace System.IdentityModel.Claims { public class WindowsClaimSet : ClaimSet, IIdentityInfo, IDisposable { internal const bool DefaultIncludeWindowsGroups = true; private WindowsIdentity _windowsIdentity; private DateTime _expirationTime; private bool _includeWindowsGroups; private IList<Claim> _claims; private bool _disposed = false; private string _authenticationType; public WindowsClaimSet(WindowsIdentity windowsIdentity) : this(windowsIdentity, DefaultIncludeWindowsGroups) { } public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups) : this(windowsIdentity, includeWindowsGroups, DateTime.UtcNow.AddHours(10)) { } public WindowsClaimSet(WindowsIdentity windowsIdentity, DateTime expirationTime) : this(windowsIdentity, DefaultIncludeWindowsGroups, expirationTime) { } public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups, DateTime expirationTime) : this(windowsIdentity, null, includeWindowsGroups, expirationTime, true) { } public WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime) : this( windowsIdentity, authenticationType, includeWindowsGroups, expirationTime, true ) { } internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, bool clone) : this( windowsIdentity, authenticationType, includeWindowsGroups, DateTime.UtcNow.AddHours( 10 ), clone ) { } internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone) { if (windowsIdentity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity"); _windowsIdentity = clone ? SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity; _includeWindowsGroups = includeWindowsGroups; _expirationTime = expirationTime; _authenticationType = authenticationType; } private WindowsClaimSet(WindowsClaimSet from) : this(from.WindowsIdentity, from._authenticationType, from._includeWindowsGroups, from._expirationTime, true) { } public override Claim this[int index] { get { ThrowIfDisposed(); EnsureClaims(); return _claims[index]; } } public override int Count { get { ThrowIfDisposed(); EnsureClaims(); return _claims.Count; } } IIdentity IIdentityInfo.Identity { get { ThrowIfDisposed(); return _windowsIdentity; } } public WindowsIdentity WindowsIdentity { get { ThrowIfDisposed(); return _windowsIdentity; } } public override ClaimSet Issuer { get { return ClaimSet.Windows; } } public DateTime ExpirationTime { get { return _expirationTime; } } internal WindowsClaimSet Clone() { ThrowIfDisposed(); return new WindowsClaimSet(this); } public void Dispose() { if (!_disposed) { _disposed = true; _windowsIdentity.Dispose(); } } IList<Claim> InitializeClaimsCore() { if (_windowsIdentity.AccessToken == null) return new List<Claim>(); List<Claim> claims = new List<Claim>(3); claims.Add(new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity)); Claim claim; if (TryCreateWindowsSidClaim(_windowsIdentity, out claim)) { claims.Add(claim); } claims.Add(Claim.CreateNameClaim(_windowsIdentity.Name)); if (_includeWindowsGroups) { // claims.AddRange(Groups); } return claims; } void EnsureClaims() { if (_claims != null) return; _claims = InitializeClaimsCore(); } void ThrowIfDisposed() { if (_disposed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName)); } } static bool SupportedClaimType(string claimType) { return claimType == null || ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType || ClaimTypes.Name == claimType; } // Note: null string represents any. public override IEnumerable<Claim> FindClaims(string claimType, string right) { ThrowIfDisposed(); if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right)) { yield break; } else if (_claims == null && (ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType)) { if (ClaimTypes.Sid == claimType) { if (right == null || Rights.Identity == right) { yield return new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity); } } if (right == null || Rights.PossessProperty == right) { Claim sid; if (TryCreateWindowsSidClaim(_windowsIdentity, out sid)) { if (claimType == sid.ClaimType) { yield return sid; } } } if (_includeWindowsGroups && (right == null || Rights.PossessProperty == right)) { // Not sure yet if GroupSidClaimCollections are necessary in .NET Core, but default // _includeWindowsGroups is true; don't throw here or we bust the default case on UWP/.NET Core } } else { EnsureClaims(); bool anyClaimType = (claimType == null); bool anyRight = (right == null); for (int i = 0; i < _claims.Count; ++i) { Claim claim = _claims[i]; if ((claim != null) && (anyClaimType || claimType == claim.ClaimType) && (anyRight || right == claim.Right)) { yield return claim; } } } } public override IEnumerator<Claim> GetEnumerator() { ThrowIfDisposed(); EnsureClaims(); return _claims.GetEnumerator(); } public override string ToString() { return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this); } public static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim) { throw ExceptionHelper.PlatformNotSupported("CreateWindowsSidClaim is not yet supported"); } } } #endif // SUPPORTS_WINDOWSIDENTITY
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableModuloTests { #region Test methods [Fact] public static void CheckNullableByteModuloTest() { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteModuloTest() { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteModulo(array[i], array[j]); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortModuloTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableShortModuloTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntModuloTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableIntModuloTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableULongModuloTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableLongModuloTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatModuloTest(bool useInterpreter) { float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleModuloTest(bool useInterpreter) { double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalModuloTest(bool useInterpreter) { decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalModulo(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharModuloTest() { char?[] array = { '\0', '\b', 'A', '\uffff', null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteModulo(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableSByteModulo(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableUShortModulo(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Modulo( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableShortModulo(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Modulo( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableUIntModulo(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Modulo( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableIntModulo(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Modulo( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableULongModulo(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Modulo( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableLongModulo(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Modulo( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableFloatModulo(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Modulo( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDoubleModulo(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Modulo( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDecimalModulo(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Modulo( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableCharModulo(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } #endregion } }
using UnityEngine; using UnityEditor; using UMA; public class UMAAvatarLoadSaveMenuItems : Editor { [MenuItem("UMA/Runtime/Save Selected Avatars generated textures to PNG")] public static void SaveSelectedAvatarsPNG() { if (!Application.isPlaying) { EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it"); return; } if (Selection.gameObjects.Length != 1) { EditorUtility.DisplayDialog("Notice", "Only one Avatar can be selected.", "OK"); return; } var selectedTransform = Selection.gameObjects[0].transform; var avatar = selectedTransform.GetComponent<UMAAvatarBase>(); if (avatar == null) { EditorUtility.DisplayDialog("Notice", "An Avatar must be selected to use this function", "OK"); return; } SkinnedMeshRenderer smr = avatar.gameObject.GetComponentInChildren<SkinnedMeshRenderer>(); if (smr == null) { EditorUtility.DisplayDialog("Warning", "Could not find SkinnedMeshRenderer in Avatar hierarchy", "OK"); return; } string path = EditorUtility.SaveFilePanelInProject("Save Texture(s)", "Texture.png", "png", "Base Filename to save PNG files to."); if (!string.IsNullOrEmpty(path)) { string basename = System.IO.Path.GetFileNameWithoutExtension(path); string pathname = System.IO.Path.GetDirectoryName(path); // save the diffuse texture for (int i = 0; i < smr.materials.Length; i++) { string PathBase = System.IO.Path.Combine(pathname, basename + "_material_" + i.ToString()); string DiffuseName = PathBase + "_Diffuse.PNG"; SaveTexture(smr.materials[i].GetTexture("_MainTex"), DiffuseName); } } } private static void SaveTexture(Texture texture, string diffuseName) { if (texture is RenderTexture) { SaveRenderTexture(texture as RenderTexture, diffuseName); return; } else if (texture is Texture2D) { SaveTexture2D(texture as Texture2D, diffuseName); return; } EditorUtility.DisplayDialog("Error", "Texture is not RenderTexture or Texture2D", "OK"); } static public Texture2D GetRTPixels(RenderTexture rt) { // Remember currently active render texture RenderTexture currentActiveRT = RenderTexture.active; // Set the supplied RenderTexture as the active one RenderTexture.active = rt; // Create a new Texture2D and read the RenderTexture image into it Texture2D tex = new Texture2D(rt.width, rt.height); tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); // Restorie previously active render texture RenderTexture.active = currentActiveRT; return tex; } private static void SaveRenderTexture(RenderTexture texture, string textureName) { Texture2D tex = GetRTPixels(texture); SaveTexture2D(tex, textureName); } private static void SaveTexture2D(Texture2D texture, string textureName) { byte[] data = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(textureName, data); } [MenuItem("UMA/Load and Save/Save Selected Avatar(s) Txt", priority=1)] public static void SaveSelectedAvatarsTxt() { for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMAAvatarBase>(); while (avatar == null && selectedTransform.parent != null) { selectedTransform = selectedTransform.parent; avatar = selectedTransform.GetComponent<UMAAvatarBase>(); } if (avatar != null) { var path = EditorUtility.SaveFilePanel("Save serialized Avatar", "Assets", avatar.name + ".txt", "txt"); if (path.Length != 0) { var asset = ScriptableObject.CreateInstance<UMATextRecipe>(); //check if Avatar is DCS if (avatar is UMACharacterSystem.DynamicCharacterAvatar) { asset.Save(avatar.umaData.umaRecipe, avatar.context, (avatar as UMACharacterSystem.DynamicCharacterAvatar).WardrobeRecipes, true); } else { asset.Save(avatar.umaData.umaRecipe, avatar.context); } System.IO.File.WriteAllText(path, asset.recipeString); ScriptableObject.Destroy(asset); } } } } [MenuItem("UMA/Load and Save/Save Selected Avatar(s) asset", priority = 1)] public static void SaveSelectedAvatarsAsset() { for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMAAvatarBase>(); while (avatar == null && selectedTransform.parent != null) { selectedTransform = selectedTransform.parent; avatar = selectedTransform.GetComponent<UMAAvatarBase>(); } if (avatar != null) { var path = EditorUtility.SaveFilePanelInProject("Save serialized Avatar", avatar.name + ".asset", "asset", "Message 2"); if (path.Length != 0) { var asset = ScriptableObject.CreateInstance<UMATextRecipe>(); //check if Avatar is DCS if (avatar is UMACharacterSystem.DynamicCharacterAvatar) { asset.Save(avatar.umaData.umaRecipe, avatar.context, (avatar as UMACharacterSystem.DynamicCharacterAvatar).WardrobeRecipes,true); } else { asset.Save(avatar.umaData.umaRecipe, avatar.context); } AssetDatabase.CreateAsset(asset, path); AssetDatabase.SaveAssets(); Debug.Log("Recipe size: " + asset.recipeString.Length + " chars"); } } } } [MenuItem("UMA/Load and Save/Load Selected Avatar(s) txt")] public static void LoadSelectedAvatarsTxt() { for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMAAvatarBase>(); while (avatar == null && selectedTransform.parent != null) { selectedTransform = selectedTransform.parent; avatar = selectedTransform.GetComponent<UMAAvatarBase>(); } if (avatar != null) { var path = EditorUtility.OpenFilePanel("Load serialized Avatar", "Assets", "txt"); if (path.Length != 0) { var asset = ScriptableObject.CreateInstance<UMATextRecipe>(); asset.recipeString = FileUtils.ReadAllText(path); //check if Avatar is DCS if (avatar is UMACharacterSystem.DynamicCharacterAvatar) { (avatar as UMACharacterSystem.DynamicCharacterAvatar).LoadFromRecipeString(asset.recipeString); } else { avatar.Load(asset); } Destroy(asset); } } } } [MenuItem("UMA/Load and Save/Load Selected Avatar(s) assets")] public static void LoadSelectedAvatarsAsset() { for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMAAvatarBase>(); while (avatar == null && selectedTransform.parent != null) { selectedTransform = selectedTransform.parent; avatar = selectedTransform.GetComponent<UMAAvatarBase>(); } if (avatar != null) { var path = EditorUtility.OpenFilePanel("Load serialized Avatar", "Assets", "asset"); if (path.Length != 0) { var index = path.IndexOf("/Assets/"); if (index > 0) { path = path.Substring(index + 1); } var asset = AssetDatabase.LoadMainAssetAtPath(path) as UMARecipeBase; if (asset != null) { //check if Avatar is DCS if (avatar is UMACharacterSystem.DynamicCharacterAvatar) { (avatar as UMACharacterSystem.DynamicCharacterAvatar).LoadFromRecipe(asset); } else { avatar.Load(asset); } } else { Debug.LogError("Failed To Load Asset \"" + path + "\"\nAssets must be inside the project and descend from the UMARecipeBase type"); } } } } } //@jaimi this is the equivalent of your previous JSON save but the resulting file does not need a special load method [MenuItem("UMA/Load and Save/Save DynamicCharacterAvatar(s) txt (optimized)", priority = 1)] public static void SaveSelectedAvatarsDCSTxt() { if (!Application.isPlaying) { EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it"); return; } else { EditorUtility.DisplayDialog("Notice", "The optimized save type is only compatible with DynamicCharacterAvatar avatars (or child classes of)", "Continue"); } for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMACharacterSystem.DynamicCharacterAvatar>(); if (avatar != null) { var path = EditorUtility.SaveFilePanel("Save DynamicCharacterAvatar Optimized Text", "Assets", avatar.name + ".txt", "txt"); if (path.Length != 0) { avatar.DoSave(false, path); } } } } //@jaimi this is the equivalent of your previous JSON save but the resulting file does not need a special load method and the resulting asset can also be inspected and edited [MenuItem("UMA/Load and Save/Save DynamicCharacterAvatar(s) asset (optimized)", priority = 1)] public static void SaveSelectedAvatarsDCSAsset() { if (!Application.isPlaying) { EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it"); return; } else { EditorUtility.DisplayDialog("Notice", "The optimized save type is only compatible with DynamicCharacterAvatar avatars (or child classes of)", "Continue"); } for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMACharacterSystem.DynamicCharacterAvatar>(); if (avatar != null) { var path = EditorUtility.SaveFilePanelInProject("Save DynamicCharacterAvatar Optimized Asset", avatar.name + ".asset", "asset", "Message 2"); if (path.Length != 0) { avatar.DoSave(true, path); } } } } //We dont need this now pUMATextRecipe works out which model was used itself /*[MenuItem("UMA/Load and Save/Load Dynamic Character Avatar From JSON", priority = 1)] public static void LoadSelectedAvatarsJSON() { if (!Application.isPlaying) { EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it"); return; } for (int i = 0; i < Selection.gameObjects.Length; i++) { var selectedTransform = Selection.gameObjects[i].transform; var avatar = selectedTransform.GetComponent<UMACharacterSystem.DynamicCharacterAvatar>(); if (avatar != null) { var path = EditorUtility.OpenFilePanel("Load DynamicCharacterAvatar from JSON Text", "Assets", "json"); if (path.Length != 0) { avatar.FromJson(System.IO.File.ReadAllText(path)); } } } }*/ }
// // DapSource.cs // // Author: // Gabriel Burt <gburt@novell.com> // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Collection; using Banshee.Playlist; using Banshee.Collection.Database; using Banshee.Hardware; using Banshee.MediaEngine; using Banshee.MediaProfiles; using Banshee.Preferences; using Banshee.Dap.Gui; namespace Banshee.Dap { public abstract class DapSource : RemovableSource, IDisposable { private bool flushed = false; private DapSync sync; private DapInfoBar dap_info_bar; private Page page; private DapPropertiesDisplay dap_properties_display; private IDevice device; protected internal IDevice Device { get { return device; } } private string addin_id; internal string AddinId { get { return addin_id; } set { addin_id = value; } } private MediaGroupSource music_group_source; protected MediaGroupSource MusicGroupSource { get { return music_group_source; } } private MediaGroupSource podcast_group_source; protected MediaGroupSource PodcastGroupSource { get { return podcast_group_source; } } protected DapSource () { } public virtual void DeviceInitialize (IDevice device, bool force) { this.device = device; TypeUniqueId = device.Serial; } private object internal_lock = new object (); protected virtual object InternalLock { get { return internal_lock; } } public override void Dispose () { lock (InternalLock) { if (load_thread != null) { if (load_thread.IsAlive) { load_thread.Abort (); } load_thread = null; } } if (dap_info_bar != null) { var info_bar = dap_info_bar; ThreadAssist.ProxyToMain (info_bar.Destroy); dap_info_bar = null; } Properties.Remove ("Nereid.SourceContents.FooterWidget"); /*Properties.Remove ("Nereid.SourceContents"); dap_properties_display.Destroy (); dap_properties_display = null;*/ if (sync != null) sync.Dispose (); base.Dispose (); } private void PurgeTemporaryPlaylists () { ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" BEGIN TRANSACTION; DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID IN (SELECT SmartPlaylistID FROM CoreSmartPlaylists WHERE PrimarySourceID = ?); DELETE FROM CoreSmartPlaylists WHERE PrimarySourceID = ?; COMMIT TRANSACTION", DbId, DbId )); ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" BEGIN TRANSACTION; DELETE FROM CorePlaylistEntries WHERE PlaylistID IN (SELECT PlaylistID FROM CorePlaylists WHERE PrimarySourceID = ?); DELETE FROM CorePlaylists WHERE PrimarySourceID = ?; COMMIT TRANSACTION", DbId, DbId )); } internal void RaiseUpdated () { OnUpdated (); } public virtual void SyncPlaylists () { } public override void Rename (string newName) { Name = newName; base.Rename (newName); } private bool supports_video = true; public bool SupportsVideo { get { return supports_video; } protected set { supports_video = value; } } private bool supports_podcasts = true; public bool SupportsPodcasts { get { return supports_podcasts; } protected set { supports_podcasts = value; } } internal event EventHandler RequestUnmap; #region Source protected override void Initialize () { PurgeTemporaryPlaylists (); base.Initialize (); Expanded = true; Properties.SetStringList ("Icon.Name", GetIconNames ()); Properties.Set<string> ("SourcePropertiesActionLabel", Catalog.GetString ("Device Properties")); Properties.Set<OpenPropertiesDelegate> ("SourceProperties.GuiHandler", delegate { new DapPropertiesDialog (this).RunDialog (); }); Properties.Set<bool> ("Nereid.SourceContents.HeaderVisible", false); Properties.Set<bool> ("Nereid.SourceContents.FooterVisible", false); Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", System.Reflection.Assembly.GetExecutingAssembly ()); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); sync = new DapSync (this); if (String.IsNullOrEmpty (GenericName)) { GenericName = Catalog.GetString ("Media Player"); } if (String.IsNullOrEmpty (Name)) { Name = device.Name; } AddDapProperty (Catalog.GetString ("Product"), device.Product); AddDapProperty (Catalog.GetString ("Vendor"), device.Vendor); if (acceptable_mimetypes == null) { acceptable_mimetypes = HasMediaCapabilities ? MediaCapabilities.PlaybackMimeTypes : null; if (acceptable_mimetypes == null || acceptable_mimetypes.Length == 0) { acceptable_mimetypes = new string [] { "taglib/mp3" }; } } AddChildSource (music_group_source = music_group_source ?? new MusicGroupSource (this)); // We want the group sources to be on top of the list, with Music first music_group_source.Order = -30; if (SupportsPodcasts && null == podcast_group_source) { podcast_group_source = new PodcastGroupSource (this); podcast_group_source.Order = -10; } BuildPreferences (); Properties.Set<Gtk.Widget> ("Nereid.SourceContents.FooterWidget", dap_info_bar = dap_info_bar ?? new DapInfoBar (this)); Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", dap_properties_display = dap_properties_display ?? new DapContent (this)); } private void BuildPreferences () { page = new Page (); Section main_section = new Section (); main_section.Order = -1; space_for_data = CreateSchema<long> ("space_for_data", 0, "How much space, in bytes, to reserve for data on the device.", ""); main_section.Add (space_for_data); page.Add (main_section); foreach (Section section in sync.PreferenceSections) { page.Add (section); } } // Force to zero so that count doesn't show up public override int Count { get { return 0; } } public override bool HasProperties { get { return true; } } public override bool CanSearch { get { return false; } } public override void SetStatus (string message, bool can_close, bool is_spinning, string icon_name) { base.SetStatus (message, can_close, is_spinning, icon_name); foreach (Source child in Children) { child.SetStatus (message, can_close, is_spinning, icon_name); } } public override void HideStatus () { base.HideStatus (); foreach (Source child in Children) { child.HideStatus (); } } #endregion #region Track Management/Syncing public void LoadDeviceContents () { load_thread = ThreadAssist.Spawn (ThreadedLoadDeviceContents); } private Thread load_thread; private void ThreadedLoadDeviceContents () { try { PreLoad (); SetStatus (String.Format (Catalog.GetString ("Loading {0}"), Name), false); LoadFromDevice (); PostLoad (); } catch (Exception e) { Log.Error (e); } } protected virtual void PreLoad () { PurgeTracks (); } protected virtual void PostLoad () { HideStatus (); sync.DapLoaded (); sync.CalculateSync (); if (sync.AutoSync) { sync.Sync (); } } public void RemovePlaylists () { // First remove any playlists on the device List<Source> children = new List<Source> (sync.Dap.Children); foreach (Source child in children) { if (child is AbstractPlaylistSource && !(child is MediaGroupSource)) { (child as IUnmapableSource).Unmap (); } } } protected virtual void LoadFromDevice () { } protected override void Eject () { Flush (); var h = RequestUnmap; if (h != null) { h (this, EventArgs.Empty); } } private void Flush () { if (!flushed) { flushed = true; if (!Sync.Enabled) { // If sync isn't enabled, then make sure we've written saved our playlists // Track transfers happen immediately, but playlists saves don't SyncPlaylists (); } } } HyenaSqliteCommand track_on_dap_query = new HyenaSqliteCommand ( "SELECT TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND MetadataHash = ? LIMIT 1"); private void AttemptToAddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri) { if (!Banshee.IO.File.Exists (fromUri)) { throw new FileNotFoundException (Catalog.GetString ("File not found"), fromUri.ToString ()); } // Ensure there's enough space if (BytesAvailable - Banshee.IO.File.GetSize (fromUri) >= 0) { // Ensure it's not already on the device if (ServiceManager.DbConnection.Query<long> (track_on_dap_query, DbId, track.MetadataHash) == 0) { AddTrackToDevice (track, fromUri); } } } protected abstract void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri); protected bool TrackNeedsTranscoding (TrackInfo track) { string extension = ServiceManager.MediaProfileManager.GetExtensionForMimeType (track.MimeType) ?? Path.GetExtension (track.LocalPath); if (extension != null) { extension = extension.ToLower().TrimStart ('.'); foreach (string mimetype in AcceptableMimeTypes) { if (extension == ServiceManager.MediaProfileManager.GetExtensionForMimeType (mimetype)) { return false; } } } return true; } public class DapProperty { public string Name; public string Value; public DapProperty (string k, string v) { Name = k; Value = v; } } private IDictionary<string, string> dap_properties = new Dictionary<string, string> (); protected void AddDapProperty (string key, string val) { dap_properties [key] = val; } protected void AddYesNoDapProperty (string key, bool val) { AddDapProperty (key, val ? Catalog.GetString ("Yes") : Catalog.GetString ("No")); } public IEnumerable<DapProperty> DapProperties { get { return dap_properties.Select(kv => new DapProperty(kv.Key, kv.Value)); } } protected override void AddTrackAndIncrementCount (DatabaseTrackInfo track) { if (!TrackNeedsTranscoding (track)) { AttemptToAddTrackToDevice (track, track.Uri); IncrementAddedTracks (); return; } // If it's a video and needs transcoding, we don't support that yet // TODO have preferred profiles for Audio and Video separately if (PreferredConfiguration == null || (track.MediaAttributes & TrackMediaAttributes.VideoStream) != 0) { string format = System.IO.Path.GetExtension (track.Uri.LocalPath); format = String.IsNullOrEmpty (format) ? Catalog.GetString ("Unknown") : format.Substring (1); throw new ApplicationException (String.Format (Catalog.GetString ( "The {0} format is not supported by the device, and no converter was found to convert it"), format)); } TranscoderService transcoder = ServiceManager.Get<TranscoderService> (); if (transcoder == null) { throw new ApplicationException (Catalog.GetString ( "File format conversion support is not available")); } transcoder.Enqueue (track, PreferredConfiguration, OnTrackTranscoded, OnTrackTranscodeCancelled, OnTrackTranscodeError); } private void OnTrackTranscoded (TrackInfo track, SafeUri outputUri) { AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle); try { AttemptToAddTrackToDevice ((DatabaseTrackInfo)track, outputUri); } catch (Exception e) { Log.Error (e); } IncrementAddedTracks (); } private void OnTrackTranscodeCancelled () { IncrementAddedTracks (); } private void OnTrackTranscodeError (TrackInfo track) { ErrorSource.AddMessage (Catalog.GetString ("Error converting file"), track.Uri.ToString ()); IncrementAddedTracks (); } #endregion #region Device Properties protected virtual string [] GetIconNames () { string vendor = device.Vendor; string product = device.Product; vendor = vendor != null ? vendor.Trim () : null; product = product != null ? product.Trim () : null; if (!String.IsNullOrEmpty (vendor) && !String.IsNullOrEmpty (product)) { return new string [] { String.Format ("multimedia-player-{0}-{1}", vendor, product).Replace (' ', '-').ToLower (), FallbackIcon }; } else { return new string [] { FallbackIcon }; } } public static string FallbackIcon { get { return "multimedia-player"; } } protected virtual bool HasMediaCapabilities { get { return MediaCapabilities != null; } } protected virtual IDeviceMediaCapabilities MediaCapabilities { get { return device.MediaCapabilities; } } public Page Preferences { get { return page; } } public DapSync Sync { get { return sync; } } private ProfileConfiguration preferred_config; private ProfileConfiguration PreferredConfiguration { get { if (preferred_config != null) { return preferred_config; } MediaProfileManager manager = ServiceManager.MediaProfileManager; if (manager == null) { return null; } preferred_config = manager.GetActiveProfileConfiguration (UniqueId, acceptable_mimetypes); return preferred_config; } } internal protected virtual bool CanHandleDeviceCommand (DeviceCommand command) { return false; } private string [] acceptable_mimetypes; public string [] AcceptableMimeTypes { get { return acceptable_mimetypes; } protected set { acceptable_mimetypes = value; } } public long BytesMusic { get { return MusicGroupSource == null ? 0 : MusicGroupSource.BytesUsed; } } public long BytesData { get { return BytesUsed - BytesMusic; } } public long BytesReserved { get { return space_for_data.Get (); } set { space_for_data.Set (value); } } public override long BytesAvailable { get { return BytesCapacity - BytesUsed - Math.Max (0, BytesReserved - BytesData); } } public override bool PlaylistsReadOnly { get { return IsReadOnly; } } public virtual bool IsConnected { get { return true; } } private Banshee.Configuration.SchemaEntry<long> space_for_data; #endregion } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // There are 2 #defines that have an impact on performance of this ByteBuffer implementation // // UNSAFE_BYTEBUFFER // This will use unsafe code to manipulate the underlying byte array. This // can yield a reasonable performance increase. // // BYTEBUFFER_NO_BOUNDS_CHECK // This will disable the bounds check asserts to the byte array. This can // yield a small performance gain in normal code.. // // Using UNSAFE_BYTEBUFFER and BYTEBUFFER_NO_BOUNDS_CHECK together can yield a // performance gain of ~15% for some operations, however doing so is potentially // dangerous. Do so at your own risk! // using System; using System.Collections.Generic; using System.IO; using System.Text; namespace FlatBuffers { /// <summary> /// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers. /// </summary> public class ByteBuffer { protected byte[] _buffer; private int _pos; // Must track start of the buffer. public int Length { get { return _buffer.Length; } } public ByteBuffer(int size) : this(new byte[size]) { } public ByteBuffer(byte[] buffer) : this(buffer, 0) { } public ByteBuffer(byte[] buffer, int pos) { _buffer = buffer; _pos = pos; } public int Position { get { return _pos; } set { _pos = value; } } public void Reset() { _pos = 0; } // Create a new ByteBuffer on the same underlying data. // The new ByteBuffer's position will be same as this buffer's. public ByteBuffer Duplicate() { return new ByteBuffer(_buffer, Position); } // Increases the size of the ByteBuffer, and copies the old data towards // the end of the new buffer. public void GrowFront(int newSize) { if ((Length & 0xC0000000) != 0) throw new Exception( "ByteBuffer: cannot grow buffer beyond 2 gigabytes."); if (newSize < Length) throw new Exception("ByteBuffer: cannot truncate buffer."); byte[] newBuffer = new byte[newSize]; Buffer.BlockCopy(_buffer, 0, newBuffer, newSize - Length, Length); _buffer = newBuffer; } public byte[] ToArray(int pos, int len) { return ToArray<byte>(pos, len); } /// <summary> /// A lookup of type sizes. Used instead of Marshal.SizeOf() which has additional /// overhead, but also is compatible with generic functions for simplified code. /// </summary> private static Dictionary<Type, int> genericSizes = new Dictionary<Type, int>() { { typeof(bool), sizeof(bool) }, { typeof(float), sizeof(float) }, { typeof(double), sizeof(double) }, { typeof(sbyte), sizeof(sbyte) }, { typeof(byte), sizeof(byte) }, { typeof(short), sizeof(short) }, { typeof(ushort), sizeof(ushort) }, { typeof(int), sizeof(int) }, { typeof(uint), sizeof(uint) }, { typeof(ulong), sizeof(ulong) }, { typeof(long), sizeof(long) }, }; /// <summary> /// Get the wire-size (in bytes) of a type supported by flatbuffers. /// </summary> /// <param name="t">The type to get the wire size of</param> /// <returns></returns> public static int SizeOf<T>() { return genericSizes[typeof(T)]; } /// <summary> /// Checks if the Type provided is supported as scalar value /// </summary> /// <typeparam name="T">The Type to check</typeparam> /// <returns>True if the type is a scalar type that is supported, falsed otherwise</returns> public static bool IsSupportedType<T>() { return genericSizes.ContainsKey(typeof(T)); } /// <summary> /// Get the wire-size (in bytes) of an typed array /// </summary> /// <typeparam name="T">The type of the array</typeparam> /// <param name="x">The array to get the size of</param> /// <returns>The number of bytes the array takes on wire</returns> public static int ArraySize<T>(T[] x) { return SizeOf<T>() * x.Length; } // Get a portion of the buffer casted into an array of type T, given // the buffer position and length. public T[] ToArray<T>(int pos, int len) where T: struct { AssertOffsetAndLength(pos, len); T[] arr = new T[len]; Buffer.BlockCopy(_buffer, pos, arr, 0, ArraySize(arr)); return arr; } public byte[] ToSizedArray() { return ToArray<byte>(Position, Length - Position); } public byte[] ToFullArray() { return ToArray<byte>(0, Length); } public ArraySegment<byte> ToArraySegment(int pos, int len) { return new ArraySegment<byte>(_buffer, pos, len); } public MemoryStream ToMemoryStream(int pos, int len) { return new MemoryStream(_buffer, pos, len); } #if !UNSAFE_BYTEBUFFER // Pre-allocated helper arrays for convertion. private float[] floathelper = new[] { 0.0f }; private int[] inthelper = new[] { 0 }; private double[] doublehelper = new[] { 0.0 }; private ulong[] ulonghelper = new[] { 0UL }; #endif // !UNSAFE_BYTEBUFFER // Helper functions for the unsafe version. static public ushort ReverseBytes(ushort input) { return (ushort)(((input & 0x00FFU) << 8) | ((input & 0xFF00U) >> 8)); } static public uint ReverseBytes(uint input) { return ((input & 0x000000FFU) << 24) | ((input & 0x0000FF00U) << 8) | ((input & 0x00FF0000U) >> 8) | ((input & 0xFF000000U) >> 24); } static public ulong ReverseBytes(ulong input) { return (((input & 0x00000000000000FFUL) << 56) | ((input & 0x000000000000FF00UL) << 40) | ((input & 0x0000000000FF0000UL) << 24) | ((input & 0x00000000FF000000UL) << 8) | ((input & 0x000000FF00000000UL) >> 8) | ((input & 0x0000FF0000000000UL) >> 24) | ((input & 0x00FF000000000000UL) >> 40) | ((input & 0xFF00000000000000UL) >> 56)); } #if !UNSAFE_BYTEBUFFER // Helper functions for the safe (but slower) version. protected void WriteLittleEndian(int offset, int count, ulong data) { if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)(data >> i * 8); } } else { for (int i = 0; i < count; i++) { _buffer[offset + count - 1 - i] = (byte)(data >> i * 8); } } } protected ulong ReadLittleEndian(int offset, int count) { AssertOffsetAndLength(offset, count); ulong r = 0; if (BitConverter.IsLittleEndian) { for (int i = 0; i < count; i++) { r |= (ulong)_buffer[offset + i] << i * 8; } } else { for (int i = 0; i < count; i++) { r |= (ulong)_buffer[offset + count - 1 - i] << i * 8; } } return r; } #endif // !UNSAFE_BYTEBUFFER private void AssertOffsetAndLength(int offset, int length) { #if !BYTEBUFFER_NO_BOUNDS_CHECK if (offset < 0 || offset > _buffer.Length - length) throw new ArgumentOutOfRangeException(); #endif } public void PutSbyte(int offset, sbyte value) { AssertOffsetAndLength(offset, sizeof(sbyte)); _buffer[offset] = (byte)value; } public void PutByte(int offset, byte value) { AssertOffsetAndLength(offset, sizeof(byte)); _buffer[offset] = value; } public void PutByte(int offset, byte value, int count) { AssertOffsetAndLength(offset, sizeof(byte) * count); for (var i = 0; i < count; ++i) _buffer[offset + i] = value; } // this method exists in order to conform with Java ByteBuffer standards public void Put(int offset, byte value) { PutByte(offset, value); } public void PutStringUTF8(int offset, string value) { AssertOffsetAndLength(offset, value.Length); Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, offset); } #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Put*. public void PutShort(int offset, short value) { PutUshort(offset, (ushort)value); } public unsafe void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); fixed (byte* ptr = _buffer) { *(ushort*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public void PutInt(int offset, int value) { PutUint(offset, (uint)value); } public unsafe void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); fixed (byte* ptr = _buffer) { *(uint*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public unsafe void PutLong(int offset, long value) { PutUlong(offset, (ulong)value); } public unsafe void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); fixed (byte* ptr = _buffer) { *(ulong*)(ptr + offset) = BitConverter.IsLittleEndian ? value : ReverseBytes(value); } } public unsafe void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { *(float*)(ptr + offset) = value; } else { *(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value)); } } } public unsafe void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { *(double*)(ptr + offset) = value; } else { *(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(ptr + offset)); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Put* for when unsafe code is not allowed. public void PutShort(int offset, short value) { AssertOffsetAndLength(offset, sizeof(short)); WriteLittleEndian(offset, sizeof(short), (ulong)value); } public void PutUshort(int offset, ushort value) { AssertOffsetAndLength(offset, sizeof(ushort)); WriteLittleEndian(offset, sizeof(ushort), (ulong)value); } public void PutInt(int offset, int value) { AssertOffsetAndLength(offset, sizeof(int)); WriteLittleEndian(offset, sizeof(int), (ulong)value); } public void PutUint(int offset, uint value) { AssertOffsetAndLength(offset, sizeof(uint)); WriteLittleEndian(offset, sizeof(uint), (ulong)value); } public void PutLong(int offset, long value) { AssertOffsetAndLength(offset, sizeof(long)); WriteLittleEndian(offset, sizeof(long), (ulong)value); } public void PutUlong(int offset, ulong value) { AssertOffsetAndLength(offset, sizeof(ulong)); WriteLittleEndian(offset, sizeof(ulong), value); } public void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); floathelper[0] = value; Buffer.BlockCopy(floathelper, 0, inthelper, 0, sizeof(float)); WriteLittleEndian(offset, sizeof(float), (ulong)inthelper[0]); } public void PutDouble(int offset, double value) { AssertOffsetAndLength(offset, sizeof(double)); doublehelper[0] = value; Buffer.BlockCopy(doublehelper, 0, ulonghelper, 0, sizeof(double)); WriteLittleEndian(offset, sizeof(double), ulonghelper[0]); } /// <summary> /// Copies an array of type T into this buffer, ending at the given /// offset into this buffer. The starting offset is calculated based on the length /// of the array and is the value returned. /// </summary> /// <typeparam name="T">The type of the input data (must be a struct)</typeparam> /// <param name="offset">The offset into this buffer where the copy will end</param> /// <param name="x">The array to copy data from</param> /// <returns>The 'start' location of this buffer now, after the copy completed</returns> public int Put<T>(int offset, T[] x) where T : struct { if(x == null) { throw new ArgumentNullException("Cannot put a null array"); } if(x.Length == 0) { throw new ArgumentException("Cannot put an empty array"); } if(!IsSupportedType<T>()) { throw new ArgumentException("Cannot put an array of type " + typeof(T) + " into this buffer"); } if (BitConverter.IsLittleEndian) { int numBytes = ByteBuffer.ArraySize(x); offset -= numBytes; AssertOffsetAndLength(offset, numBytes); // if we are LE, just do a block copy Buffer.BlockCopy(x, 0, _buffer, offset, numBytes); } else { throw new NotImplementedException("Big Endian Support not implemented yet " + "for putting typed arrays"); // if we are BE, we have to swap each element by itself //for(int i = x.Length - 1; i >= 0; i--) //{ // todo: low priority, but need to genericize the Put<T>() functions //} } return offset; } #endif // UNSAFE_BYTEBUFFER public sbyte GetSbyte(int index) { AssertOffsetAndLength(index, sizeof(sbyte)); return (sbyte)_buffer[index]; } public byte Get(int index) { AssertOffsetAndLength(index, sizeof(byte)); return _buffer[index]; } public string GetStringUTF8(int startPos, int len) { return Encoding.UTF8.GetString(_buffer, startPos, len); } #if UNSAFE_BYTEBUFFER // Unsafe but more efficient versions of Get*. public short GetShort(int offset) { return (short)GetUshort(offset); } public unsafe ushort GetUshort(int offset) { AssertOffsetAndLength(offset, sizeof(ushort)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(ushort*)(ptr + offset) : ReverseBytes(*(ushort*)(ptr + offset)); } } public int GetInt(int offset) { return (int)GetUint(offset); } public unsafe uint GetUint(int offset) { AssertOffsetAndLength(offset, sizeof(uint)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(uint*)(ptr + offset) : ReverseBytes(*(uint*)(ptr + offset)); } } public long GetLong(int offset) { return (long)GetUlong(offset); } public unsafe ulong GetUlong(int offset) { AssertOffsetAndLength(offset, sizeof(ulong)); fixed (byte* ptr = _buffer) { return BitConverter.IsLittleEndian ? *(ulong*)(ptr + offset) : ReverseBytes(*(ulong*)(ptr + offset)); } } public unsafe float GetFloat(int offset) { AssertOffsetAndLength(offset, sizeof(float)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { return *(float*)(ptr + offset); } else { uint uvalue = ReverseBytes(*(uint*)(ptr + offset)); return *(float*)(&uvalue); } } } public unsafe double GetDouble(int offset) { AssertOffsetAndLength(offset, sizeof(double)); fixed (byte* ptr = _buffer) { if (BitConverter.IsLittleEndian) { return *(double*)(ptr + offset); } else { ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset)); return *(double*)(&uvalue); } } } #else // !UNSAFE_BYTEBUFFER // Slower versions of Get* for when unsafe code is not allowed. public short GetShort(int index) { return (short)ReadLittleEndian(index, sizeof(short)); } public ushort GetUshort(int index) { return (ushort)ReadLittleEndian(index, sizeof(ushort)); } public int GetInt(int index) { return (int)ReadLittleEndian(index, sizeof(int)); } public uint GetUint(int index) { return (uint)ReadLittleEndian(index, sizeof(uint)); } public long GetLong(int index) { return (long)ReadLittleEndian(index, sizeof(long)); } public ulong GetUlong(int index) { return ReadLittleEndian(index, sizeof(ulong)); } public float GetFloat(int index) { int i = (int)ReadLittleEndian(index, sizeof(float)); inthelper[0] = i; Buffer.BlockCopy(inthelper, 0, floathelper, 0, sizeof(float)); return floathelper[0]; } public double GetDouble(int index) { ulong i = ReadLittleEndian(index, sizeof(double)); // There's Int64BitsToDouble but it uses unsafe code internally. ulonghelper[0] = i; Buffer.BlockCopy(ulonghelper, 0, doublehelper, 0, sizeof(double)); return doublehelper[0]; } #endif // UNSAFE_BYTEBUFFER } }
using System; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Utilities; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities; namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Digests { /** * Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is * based on a draft this implementation is subject to change. * * <pre> * block word digest * SHA-1 512 32 160 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ internal class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha256Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if(++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for(int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch( uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + ((x & y) ^ ((~x) & z)); } private static uint Sum0Maj( uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + ((x & y) ^ (x & z) ^ (y & z)); } // /* SHA-256 functions */ // private static uint Ch( // uint x, // uint y, // uint z) // { // return ((x & y) ^ ((~x) & z)); // } // // private static uint Maj( // uint x, // uint y, // uint z) // { // return ((x & y) ^ (x & z) ^ (y & z)); // } // // private static uint Sum0( // uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1( // uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0( uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1( uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha256Digest(this); } public override void Reset(IMemoable other) { Sha256Digest d = (Sha256Digest)other; CopyIn(d); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // XmlTextEncoder // // This class does special handling of text content for XML. For example // it will replace special characters with entities whenever necessary. internal class XmlTextEncoder { // // Fields // // output text writer TextWriter textWriter; // true when writing out the content of attribute value bool inAttribute; // quote char of the attribute (when inAttribute) char quoteChar; // caching of attribute value StringBuilder attrValue; bool cacheAttrValue; // XmlCharType XmlCharType xmlCharType; // // Constructor // internal XmlTextEncoder(TextWriter textWriter) { this.textWriter = textWriter; this.quoteChar = '"'; this.xmlCharType = XmlCharType.Instance; } // // Internal methods and properties // internal char QuoteChar { set { this.quoteChar = value; } } internal void StartAttribute(bool cacheAttrValue) { this.inAttribute = true; this.cacheAttrValue = cacheAttrValue; if (cacheAttrValue) { if (attrValue == null) { attrValue = new StringBuilder(); } else { attrValue.Length = 0; } } } internal void EndAttribute() { if (cacheAttrValue) { attrValue.Length = 0; } this.inAttribute = false; this.cacheAttrValue = false; } internal string AttributeValue { get { if (cacheAttrValue) { return attrValue.ToString(); } else { return String.Empty; } } } internal void WriteSurrogateChar(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, highChar); } textWriter.Write(highChar); textWriter.Write(lowChar); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (cacheAttrValue) { attrValue.Append(array, offset, count); } int endPos = offset + count; int i = offset; char ch = (char)0; for (;;) { int startPos = i; unsafe { while (i < endPos && (xmlCharType.charProperties[ch = array[i]] & XmlCharType.fAttrValue) != 0) { i++; } } if (startPos < i) { textWriter.Write(array, startPos, i - startPos); } if (i == endPos) { break; } switch (ch) { case (char)0x9: textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (inAttribute) { WriteCharEntityImpl(ch); } else { textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("apos"); } else { textWriter.Write('\''); } break; case '"': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("quot"); } else { textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < endPos) { WriteSurrogateChar(array[++i], ch); } else { throw new ArgumentException(SR.Xml_SurrogatePairSplit); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; } } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, highChar); } int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar); if (cacheAttrValue) { attrValue.Append(highChar); attrValue.Append(lowChar); } textWriter.Write("&#x"); textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo)); textWriter.Write(';'); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(string text) { if (text == null) { return; } if (cacheAttrValue) { attrValue.Append(text); } // scan through the string to see if there are any characters to be escaped int len = text.Length; int i = 0; int startPos = 0; char ch = (char)0; for (;;) { unsafe { while (i < len && (xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { i++; } } if (i == len) { // reached the end of the string -> write it whole out textWriter.Write(text); return; } if (inAttribute) { if (ch == 0x9) { i++; continue; } } else { if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'') { i++; continue; } } // some character that needs to be escaped is found: break; } char[] helperBuffer = new char[256]; for (;;) { if (startPos < i) { WriteStringFragment(text, startPos, i - startPos, helperBuffer); } if (i == len) { break; } switch (ch) { case (char)0x9: textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (inAttribute) { WriteCharEntityImpl(ch); } else { textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("apos"); } else { textWriter.Write('\''); } break; case '"': if (inAttribute && quoteChar == ch) { WriteEntityRefImpl("quot"); } else { textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { WriteSurrogateChar(text[++i], ch); } else { throw XmlConvertEx.CreateInvalidSurrogatePairException(text[i], ch); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; startPos = i; unsafe { while (i < len && (xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { i++; } } } } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void WriteRawWithSurrogateChecking(string text) { if (text == null) { return; } if (cacheAttrValue) { attrValue.Append(text); } int len = text.Length; int i = 0; char ch = (char)0; for (;;) { unsafe { while (i < len && ((xmlCharType.charProperties[ch = text[i]] & XmlCharType.fCharData) != 0 || ch < 0x20)) { i++; } } if (i == len) { break; } if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { char lowChar = text[i + 1]; if (XmlCharType.IsLowSurrogate(lowChar)) { i += 2; continue; } else { throw XmlConvertEx.CreateInvalidSurrogatePairException(lowChar, ch); } } throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvertEx.CreateInvalidHighSurrogateCharException(ch); } else { i++; } } textWriter.Write(text); return; } internal void WriteRaw(string value) { if (cacheAttrValue) { attrValue.Append(value); } textWriter.Write(value); } internal void WriteRaw(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (cacheAttrValue) { attrValue.Append(array, offset, count); } textWriter.Write(array, offset, count); } internal void WriteCharEntity(char ch) { if (XmlCharType.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo); if (cacheAttrValue) { attrValue.Append("&#x"); attrValue.Append(strVal); attrValue.Append(';'); } WriteCharEntityImpl(strVal); } internal void WriteEntityRef(string name) { if (cacheAttrValue) { attrValue.Append('&'); attrValue.Append(name); attrValue.Append(';'); } WriteEntityRefImpl(name); } internal void Flush() { } // // Private implementation methods // // This is a helper method to woraround the fact that TextWriter does not have a Write method // for fragment of a string such as Write( string, offset, count). // The string fragment will be written out by copying into a small helper buffer and then // calling textWriter to write out the buffer. private void WriteStringFragment(string str, int offset, int count, char[] helperBuffer) { int bufferSize = helperBuffer.Length; while (count > 0) { int copyCount = count; if (copyCount > bufferSize) { copyCount = bufferSize; } str.CopyTo(offset, helperBuffer, 0, copyCount); textWriter.Write(helperBuffer, 0, copyCount); offset += copyCount; count -= copyCount; } } private void WriteCharEntityImpl(char ch) { WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo)); } private void WriteCharEntityImpl(string strVal) { textWriter.Write("&#x"); textWriter.Write(strVal); textWriter.Write(';'); } private void WriteEntityRefImpl(string name) { textWriter.Write('&'); textWriter.Write(name); textWriter.Write(';'); } } }
/* ***** 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 <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (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; namespace Ude.Core { public class ThaiModel : SequenceModel { /**************************************************************** 255: Control characters that usually does not exist in any text 254: Carriage/Return 253: symbol (punctuation) that does not belong to word 252: 0 - 9 *****************************************************************/ // The following result for thai was collected from a limited sample (1M) private readonly static byte[] TIS620_CHAR_TO_ORDER_MAP = { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 +253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253,182,106,107,100,183,184,185,101, 94,186,187,108,109,110,111, //40 188,189,190, 89, 95,112,113,191,192,193,194,253,253,253,253,253, //50 253, 64, 72, 73,114, 74,115,116,102, 81,201,117, 90,103, 78, 82, //60 96,202, 91, 79, 84,104,105, 97, 98, 92,203,253,253,253,253,253, //70 209,210,211,212,213, 88,214,215,216,217,218,219,220,118,221,222, 223,224, 99, 85, 83,225,226,227,228,229,230,231,232,233,234,235, 236, 5, 30,237, 24,238, 75, 8, 26, 52, 34, 51,119, 47, 58, 57, 49, 53, 55, 43, 20, 19, 44, 14, 48, 3, 17, 25, 39, 62, 31, 54, 45, 9, 16, 2, 61, 15,239, 12, 42, 46, 18, 21, 76, 4, 66, 63, 22, 10, 1, 36, 23, 13, 40, 27, 32, 35, 86,240,241,242,243,244, 11, 28, 41, 29, 33,245, 50, 37, 6, 7, 67, 77, 38, 93,246,247, 68, 56, 59, 65, 69, 60, 70, 80, 71, 87,248,249,250,251,252,253, }; //Model Table: //total sequences: 100% //first 512 sequences: 92.6386% //first 1024 sequences:7.3177% //rest sequences: 1.0230% //negative sequences: 0.0436% private readonly static byte[] THAI_LANG_MODEL = { 0,1,3,3,3,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,3,3, 0,3,3,0,0,0,1,3,0,3,3,2,3,3,0,1,2,3,3,3,3,0,2,0,2,0,0,3,2,1,2,2, 3,0,3,3,2,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,0,3,2,3,0,2,2,2,3, 0,2,3,0,0,0,0,1,0,1,2,3,1,1,3,2,2,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,3,3,2,3,2,3,3,2,2,2, 3,1,2,3,0,3,3,2,2,1,2,3,3,1,2,0,1,3,0,1,0,0,1,0,0,0,0,0,0,0,1,1, 3,3,2,2,3,3,3,3,1,2,3,3,3,3,3,2,2,2,2,3,3,2,2,3,3,2,2,3,2,3,2,2, 3,3,1,2,3,1,2,2,3,3,1,0,2,1,0,0,3,1,2,1,0,0,1,0,0,0,0,0,0,1,0,1, 3,3,3,3,3,3,2,2,3,3,3,3,2,3,2,2,3,3,2,2,3,2,2,2,2,1,1,3,1,2,1,1, 3,2,1,0,2,1,0,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,2,3,3,2,2,3,2,3,3,2,3,1,1,2,3,2,2,2,3,2,2,2,2,2,1,2,1, 2,2,1,1,3,3,2,1,0,1,2,2,0,1,3,0,0,0,1,1,0,0,0,0,0,2,3,0,0,2,1,1, 3,3,2,3,3,2,0,0,3,3,0,3,3,0,2,2,3,1,2,2,1,1,1,0,2,2,2,0,2,2,1,1, 0,2,1,0,2,0,0,2,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,2,3,3,2,0,0,3,3,0,2,3,0,2,1,2,2,2,2,1,2,0,0,2,2,2,0,2,2,1,1, 0,2,1,0,2,0,0,2,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,2,3,2,3,2,0,2,2,1,3,2,1,3,2,1,2,3,2,2,3,0,2,3,2,2,1,2,2,2,2, 1,2,2,0,0,0,0,2,0,1,2,0,1,1,1,0,1,0,3,1,1,0,0,0,0,0,0,0,0,0,1,0, 3,3,2,3,3,2,3,2,2,2,3,2,2,3,2,2,1,2,3,2,2,3,1,3,2,2,2,3,2,2,2,3, 3,2,1,3,0,1,1,1,0,2,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,2,0,0, 1,0,0,3,0,3,3,3,3,3,0,0,3,0,2,2,3,3,3,3,3,0,0,0,1,1,3,0,0,0,0,2, 0,0,1,0,0,0,0,0,0,0,2,3,0,0,0,3,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0, 2,0,3,3,3,3,0,0,2,3,0,0,3,0,3,3,2,3,3,3,3,3,0,0,3,3,3,0,0,0,3,3, 0,0,3,0,0,0,0,2,0,0,2,1,1,3,0,0,1,0,0,2,3,0,1,0,0,0,0,0,0,0,1,0, 3,3,3,3,2,3,3,3,3,3,3,3,1,2,1,3,3,2,2,1,2,2,2,3,1,1,2,0,2,1,2,1, 2,2,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0, 3,0,2,1,2,3,3,3,0,2,0,2,2,0,2,1,3,2,2,1,2,1,0,0,2,2,1,0,2,1,2,2, 0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,3,3,1,1,3,0,2,3,1,1,3,2,1,1,2,0,2,2,3,2,1,1,1,1,1,2, 3,0,0,1,3,1,2,1,2,0,3,0,0,0,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 3,3,1,1,3,2,3,3,3,1,3,2,1,3,2,1,3,2,2,2,2,1,3,3,1,2,1,3,1,2,3,0, 2,1,1,3,2,2,2,1,2,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 3,3,2,3,2,3,3,2,3,2,3,2,3,3,2,1,0,3,2,2,2,1,2,2,2,1,2,2,1,2,1,1, 2,2,2,3,0,1,3,1,1,1,1,0,1,1,0,2,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,3,2,2,1,1,3,2,3,2,3,2,0,3,2,2,1,2,0,2,2,2,1,2,2,2,2,1, 3,2,1,2,2,1,0,2,0,1,0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,2,3,1,2,3,3,2,2,3,0,1,1,2,0,3,3,2,2,3,0,1,1,3,0,0,0,0, 3,1,0,3,3,0,2,0,2,1,0,0,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,2,3,3,0,1,3,1,1,2,1,2,1,1,3,1,1,0,2,3,1,1,1,1,1,1,1,1, 3,1,1,2,2,2,2,1,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,2,2,1,1,2,1,3,3,2,3,2,2,3,2,2,3,1,2,2,1,2,0,3,2,1,2,2,2,2,2,1, 3,2,1,2,2,2,1,1,1,1,0,0,1,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,1,3,3,0,2,1,0,3,2,0,0,3,1,0,1,1,0,1,0,0,0,0,0,1, 1,0,0,1,0,3,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,2,2,2,3,0,0,1,3,0,3,2,0,3,2,2,3,3,3,3,3,1,0,2,2,2,0,2,2,1,2, 0,2,3,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,0,2,3,1,3,3,2,3,3,0,3,3,0,3,2,2,3,2,3,3,3,0,0,2,2,3,0,1,1,1,3, 0,0,3,0,0,0,2,2,0,1,3,0,1,2,2,2,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1, 3,2,3,3,2,0,3,3,2,2,3,1,3,2,1,3,2,0,1,2,2,0,2,3,2,1,0,3,0,0,0,0, 3,0,0,2,3,1,3,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,3,2,2,2,1,2,0,1,3,1,1,3,1,3,0,0,2,1,1,1,1,2,1,1,1,0,2,1,0,1, 1,2,0,0,0,3,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,3,1,0,0,0,1,0, 3,3,3,3,2,2,2,2,2,1,3,1,1,1,2,0,1,1,2,1,2,1,3,2,0,0,3,1,1,1,1,1, 3,1,0,2,3,0,0,0,3,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,2,3,0,3,3,0,2,0,0,0,0,0,0,0,3,0,0,1,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,2,3,1,3,0,0,1,2,0,0,2,0,3,3,2,3,3,3,2,3,0,0,2,2,2,0,0,0,2,2, 0,0,1,0,0,0,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,1,2,3,1,3,3,0,0,1,0,3,0,0,0,0,0, 0,0,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, 3,3,1,2,3,1,2,3,1,0,3,0,2,2,1,0,2,1,1,2,0,1,0,0,1,1,1,1,0,1,0,0, 1,0,0,0,0,1,1,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,0,1,1,1,3,1,2,2,2,2,2,2,1,1,1,1,0,3,1,0,1,3,1,1,1,1, 1,1,0,2,0,1,3,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1, 3,0,2,2,1,3,3,2,3,3,0,1,1,0,2,2,1,2,1,3,3,1,0,0,3,2,0,0,0,0,2,1, 0,1,0,0,0,0,1,2,0,1,1,3,1,1,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,3,0,0,1,0,0,0,3,0,0,3,0,3,1,0,1,1,1,3,2,0,0,0,3,0,0,0,0,2,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,1,3,2,1,3,3,1,2,2,0,1,2,1,0,1,2,0,0,0,0,0,3,0,0,0,3,0,0,0,0, 3,0,0,1,1,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, 3,0,1,2,0,3,3,3,2,2,0,1,1,0,1,3,0,0,0,2,2,0,0,0,0,3,1,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,2,3,1,2,0,0,2,1,0,3,1,0,1,2,0,1,1,1,1,3,0,0,3,1,1,0,2,2,1,1, 0,2,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,3,1,2,0,0,2,2,0,1,2,0,1,0,1,3,1,2,1,0,0,0,2,0,3,0,0,0,1,0, 0,1,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, 3,0,1,1,2,2,0,0,0,2,0,2,1,0,1,1,0,1,1,1,2,1,0,0,1,1,1,0,2,1,1,1, 0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1, 0,0,0,2,0,1,3,1,1,1,1,0,0,0,0,3,2,0,1,0,0,0,1,2,0,0,0,1,0,0,0,0, 0,0,0,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,3,3,3,3,1,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, 1,0,2,3,2,2,0,0,0,1,0,0,0,0,2,3,2,1,2,2,3,0,0,0,2,3,1,0,0,0,1,1, 0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0, 3,3,2,2,0,1,0,0,0,0,2,0,2,0,1,0,0,0,1,1,0,0,0,2,1,0,1,0,1,1,0,0, 0,1,0,2,0,0,1,0,3,0,1,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,1,0,0,1,0,0,0,0,0,1,1,2,0,0,0,0,1,0,0,1,3,1,0,0,0,0,1,1,0,0, 0,1,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0, 3,3,1,1,1,1,2,3,0,0,2,1,1,1,1,1,0,2,1,1,0,0,0,2,1,0,1,2,1,1,0,1, 2,1,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,3,1,0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1, 0,0,0,2,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,3,2,0,0,0,0,0,0,1,2,1,0,1,1,0,2,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,2,0,0,0,1,3,0,1,0,0,0,2,0,0,0,0,0,0,0,1,2,0,0,0,0,0, 3,3,0,0,1,1,2,0,0,1,2,1,0,1,1,1,0,1,1,0,0,2,1,1,0,1,0,0,1,1,1,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,1,0,0,0,0,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,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, 2,3,0,0,1,1,0,0,0,2,0,0,0,0,0,0,0,2,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,0,0,0,0,0,0,0,0,0,0,0, 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,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,1,0,1,2,0,1,2,0,0,1,1,0,2,0,1,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0, 1,0,0,1,0,1,1,0,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,1,0,0,0,0,0,0,0,1,1,0,1,1,0,2,1,3,0,0,0,0,1,1,0,0,0,0,0,0,0,3, 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,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,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, 2,0,1,0,1,0,0,2,0,0,2,0,0,1,1,2,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0, 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 1,0,0,3,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,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, 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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,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,0, 2,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1,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, 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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,3,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,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,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,0,0,2,1,0,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,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, 2,0,0,0,0,0,0,0,0,0,0,0,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,0,0,0,0,0,0,0,0,0,0,0,0,0, }; public ThaiModel(byte[] charToOrderMap, string name) : base(TIS620_CHAR_TO_ORDER_MAP, THAI_LANG_MODEL, 0.926386f, false, "TIS-620") { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using System.Globalization; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class PropertiesTests : XLinqTestCase { public static object Explicit(Type ret, XAttribute data) { switch (ret.Name) { case "Boolean": return (Boolean)data; case "Int32": return (Int32)data; case "UInt32": return (UInt32)data; case "Int64": return (Int64)data; case "UInt64": return (UInt64)data; case "Single": return (Single)data; case "Double": return (Double)data; case "Decimal": return (Decimal)data; case "DateTime": return (DateTime)data; case "DateTimeOffset": return (DateTimeOffset)data; case "TimeSpan": return (TimeSpan)data; case "Guid": return (Guid)data; case "Nullable`1": { switch (ret.ToString()) { case "System.Nullable`1[System.Boolean]": return (Boolean?)data; case "System.Nullable`1[System.Int32]": return (Int32?)data; case "System.Nullable`1[System.Int64]": return (Int64?)data; case "System.Nullable`1[System.UInt32]": return (UInt32?)data; case "System.Nullable`1[System.UInt64]": return (UInt64?)data; case "System.Nullable`1[System.Single]": return (Single?)data; case "System.Nullable`1[System.Double]": return (Double?)data; case "System.Nullable`1[System.Decimal]": return (Decimal?)data; case "System.Nullable`1[System.DateTime]": return (DateTime?)data; case "System.Nullable`1[System.DateTimeOffset]": return (DateTimeOffset?)data; case "System.Nullable`1[System.TimeSpan]": return (TimeSpan?)data; case "System.Nullable`1[System.Guid]": return (Guid?)data; default: throw new ArgumentOutOfRangeException(); } } default: throw new ArgumentOutOfRangeException(); } } public static object Explicit(Type ret, XElement data) { switch (ret.Name) { case "Boolean": return (Boolean)data; case "Int32": return (Int32)data; case "UInt32": return (UInt32)data; case "Int64": return (Int64)data; case "UInt64": return (UInt64)data; case "Single": return (Single)data; case "Double": return (Double)data; case "Decimal": return (Decimal)data; case "DateTime": return (DateTime)data; case "DateTimeOffset": return (DateTimeOffset)data; case "TimeSpan": return (TimeSpan)data; case "Guid": return (Guid)data; case "Nullable`1": { switch (ret.ToString()) { case "System.Nullable`1[System.Boolean]": return (Boolean?)data; case "System.Nullable`1[System.Int32]": return (Int32?)data; case "System.Nullable`1[System.Int64]": return (Int64?)data; case "System.Nullable`1[System.UInt32]": return (UInt32?)data; case "System.Nullable`1[System.UInt64]": return (UInt64?)data; case "System.Nullable`1[System.Single]": return (Single?)data; case "System.Nullable`1[System.Double]": return (Double?)data; case "System.Nullable`1[System.Decimal]": return (Decimal?)data; case "System.Nullable`1[System.DateTime]": return (DateTime?)data; case "System.Nullable`1[System.DateTimeOffset]": return (DateTimeOffset?)data; case "System.Nullable`1[System.TimeSpan]": return (TimeSpan?)data; case "System.Nullable`1[System.Guid]": return (Guid?)data; default: throw new ArgumentOutOfRangeException(); } } default: throw new ArgumentOutOfRangeException(); } } public enum ExplicitCastTestType { RoundTrip, XmlConvert } public enum NodeCreateType { Constructor, SetValue } //[TestCase(Name = "XElement - value conversion round trip (constructor)", Params = new object[] { typeof(XElement), ExplicitCastTestType.RoundTrip, NodeCreateType.Constructor })] //[TestCase(Name = "XAttribute - value conversion round trip (constructor)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.RoundTrip, NodeCreateType.Constructor })] //[TestCase(Name = "XElement - XmlConvert conformance (constructor)", Params = new object[] { typeof(XElement), ExplicitCastTestType.XmlConvert, NodeCreateType.Constructor })] //[TestCase(Name = "XAttribute - XmlConvert conformance (constructor)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.XmlConvert, NodeCreateType.Constructor })] //[TestCase(Name = "XElement - value conversion round trip (SetValue)", Params = new object[] { typeof(XElement), ExplicitCastTestType.RoundTrip, NodeCreateType.SetValue })] //[TestCase(Name = "XAttribute - value conversion round trip (SetValue)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.RoundTrip, NodeCreateType.SetValue })] //[TestCase(Name = "XElement - XmlConvert conformance (SetValue)", Params = new object[] { typeof(XElement), ExplicitCastTestType.XmlConvert, NodeCreateType.SetValue })] //[TestCase(Name = "XAttribute - XmlConvert conformance (SetValue)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.XmlConvert, NodeCreateType.SetValue })] public partial class XElement_Op_Eplicit : XLinqTestCase { private object[] _data = new object[] { // bool true, false, // Int32 (Int32) 1001, (Int32) 0, (Int32) (-321), Int32.MaxValue, Int32.MinValue, // UInt32 (UInt32) 1001, (UInt32) 0, UInt32.MaxValue, UInt32.MinValue, (Int64) 0, (Int64) (-641), Int64.MaxValue, Int64.MinValue, (UInt64) 1001, (UInt64) 0, UInt64.MaxValue, UInt64.MinValue, // float (Single) 12.1, (Single) (-12.1), (Single) 0.0, Single.Epsilon, Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity, Single.MinValue, Single.MaxValue, // double (Double)12.1, (Double)(-12.1), (Double)0.0, Double.Epsilon, Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity, Double.MinValue, Double.MaxValue, // decimal (Decimal)12.1, (Decimal)(-12.1), (Decimal) 0.0, Decimal.MinValue, Decimal.MaxValue, Decimal.MinusOne, Decimal.One, Decimal.Zero, //// DateTimeOffset DateTimeOffset.Now, DateTimeOffset.MaxValue, DateTimeOffset.MinValue, DateTimeOffset.UtcNow, new DateTimeOffset (DateTime.Today), new DateTimeOffset (1989,11,17,19,30,00,TimeSpan.FromHours(8)), new DateTimeOffset (1989,11,17,19,30,00,TimeSpan.FromHours(-8)), // timespan TimeSpan.MaxValue, TimeSpan.MinValue, TimeSpan.Zero, TimeSpan.FromHours (1.4), TimeSpan.FromMilliseconds (1.0), TimeSpan.FromMinutes (5.0), // Guid System.Guid.Empty, System.Guid.NewGuid(), System.Guid.NewGuid() }; public static Dictionary<Type, Type> typeMapper; static XElement_Op_Eplicit() { if (typeMapper == null) { typeMapper = new Dictionary<Type, Type>(); typeMapper.Add(typeof(bool), typeof(bool?)); typeMapper.Add(typeof(Int32), typeof(Int32?)); typeMapper.Add(typeof(Int64), typeof(Int64?)); typeMapper.Add(typeof(UInt32), typeof(UInt32?)); typeMapper.Add(typeof(UInt64), typeof(UInt64?)); typeMapper.Add(typeof(Single), typeof(Single?)); typeMapper.Add(typeof(Double), typeof(Double?)); typeMapper.Add(typeof(Decimal), typeof(Decimal?)); typeMapper.Add(typeof(DateTime), typeof(DateTime?)); typeMapper.Add(typeof(DateTimeOffset), typeof(DateTimeOffset?)); typeMapper.Add(typeof(TimeSpan), typeof(TimeSpan?)); typeMapper.Add(typeof(Guid), typeof(Guid?)); } } protected override void DetermineChildren() { base.DetermineChildren(); Type type = Params[0] as Type; ExplicitCastTestType testType = (ExplicitCastTestType)Params[1]; NodeCreateType createType = (NodeCreateType)Params[2]; // add normal types foreach (object o in _data) { string desc = o.GetType().ToString() + " : "; // On Arabic locale DateTime and DateTimeOffset types threw on serialization if the date was // too big for the Arabic calendar if (o is DateTime) desc += ((DateTime)o).ToString(CultureInfo.InvariantCulture); else if (o is DateTimeOffset) desc += ((DateTimeOffset)o).ToString(CultureInfo.InvariantCulture); else desc += o; AddChild(new ExplicitCastVariation(testType, createType, type, o, o.GetType(), this, desc)); } // add Nullable types check (not applicable for XmlConvert tests) if (testType == ExplicitCastTestType.RoundTrip) { foreach (object o in _data) { string desc = o.GetType().ToString() + " : "; // On Arabic locale DateTime and DateTimeOffset types threw on serialization if the date was // too big for the Arabic calendar if (o is DateTime) desc += ((DateTime)o).ToString(CultureInfo.InvariantCulture); else if (o is DateTimeOffset) desc += ((DateTimeOffset)o).ToString(CultureInfo.InvariantCulture); else desc += o; AddChild(new ExplicitCastVariation(testType, createType, type, o, typeMapper[o.GetType()], this, desc)); } } } //[Variation(Desc = "XElement.SetValue(null)", Param = null)] //[Variation(Desc = "XElement.SetValue(null)", Param = "")] //[Variation(Desc = "XElement.SetValue(null)", Param = "text")] //[Variation(Desc = "XElement.SetValue(null)", Param = typeof(XElement))] public void SetValueNull() { XElement el = new XElement("elem", Variation.Param is Type ? new XElement("X") : Variation.Param); try { el.SetValue(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Desc = "XAttribute.SetValue(null)")] public void SetValueNullAttr() { XAttribute a = new XAttribute("a", "A"); try { a.SetValue(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Desc = "Conversion to bool overloads (1,True,true)", Params = new object[] { true, new string[] { "1", "True", "true","TRUE", " TRue " } })] //[Variation(Desc = "Conversion to bool overloads (0,False,false)", Params = new object[] { false, new string[] { "0", "False", "false", "FALSE", " FalsE " } })] public void ConversionoBool() { Type type = Params[0] as Type; NodeCreateType nodeCreateType = (NodeCreateType)Params[2]; bool expV = (bool)CurrentChild.Params[0]; string[] strs = CurrentChild.Params[1] as string[]; object node = null; foreach (string data in strs) { switch (nodeCreateType) { case NodeCreateType.Constructor: if (type == typeof(XElement)) { node = new XElement(XName.Get("name"), data); } else if (type == typeof(XAttribute)) { node = new XAttribute(XName.Get("name"), data); } break; case NodeCreateType.SetValue: if (type == typeof(XElement)) { node = new XElement(XName.Get("name"), ""); ((XElement)node).SetValue(data); } else if (type == typeof(XAttribute)) { node = new XAttribute(XName.Get("name"), ""); ((XAttribute)node).SetValue(data); } break; default: TestLog.Compare(false, "test failed: wrong create type"); break; } object retData = type == typeof(XElement) ? (bool)(node as XElement) : (bool)(node as XAttribute); TestLog.Compare(retData.Equals(expV), "Data verification for string :: " + data); } } } public partial class ExplicitCastVariation : TestVariation { private object _data; private Type _nodeType; private Type _retType; private ExplicitCastTestType _testType; private NodeCreateType _nodeCreateType; private string _desc; public ExplicitCastVariation(ExplicitCastTestType testType, NodeCreateType nodeCreateType, Type nodeType, object data, Type retType, TestCase testCase, string desc) { _desc = desc; _data = data; _nodeType = nodeType; _testType = testType; _retType = retType; _nodeCreateType = nodeCreateType; } private XObject CreateContainer() { if (_nodeCreateType == NodeCreateType.Constructor) { if (_nodeType.Name.Equals("XElement")) { return new XElement(XName.Get("name"), _data); } if (_nodeType.Name.Equals("XAttribute")) { return new XAttribute(XName.Get("name"), _data); } } else if (_nodeCreateType == NodeCreateType.SetValue) { if (_nodeType.Name.Equals("XElement")) { var node = new XElement(XName.Get("name"), ""); node.SetValue(_data); return node; } if (_nodeType.Name.Equals("XAttribute")) { var node = new XAttribute(XName.Get("name"), ""); node.SetValue(_data); return node; } } throw new ArgumentOutOfRangeException("Unknown NodeCreateType: " + _nodeCreateType); } public override TestResult Execute() { var node = CreateContainer(); switch (_testType) { case ExplicitCastTestType.RoundTrip: if (_nodeType.Name.Equals("XElement")) { var retData = Explicit(_retType, (XElement)node); TestLog.Compare(retData, _data, "XElement (" + _retType + ")"); } else { var retData = Explicit(_retType, (XAttribute)node); TestLog.Compare(retData, _data, "XElement (" + _retType + ")"); } break; case ExplicitCastTestType.XmlConvert: string xmlConv = ""; switch (_data.GetType().Name) { case "Boolean": xmlConv = XmlConvert.ToString((Boolean)_data); break; case "Int32": xmlConv = XmlConvert.ToString((Int32)_data); break; case "UInt32": xmlConv = XmlConvert.ToString((UInt32)_data); break; case "Int64": xmlConv = XmlConvert.ToString((Int64)_data); break; case "UInt64": xmlConv = XmlConvert.ToString((UInt64)_data); break; case "Single": xmlConv = XmlConvert.ToString((Single)_data); break; case "Double": xmlConv = XmlConvert.ToString((Double)_data); break; case "Decimal": xmlConv = XmlConvert.ToString((Decimal)_data); break; case "DateTime": TestLog.Skip("DateTime Convert include +8:00"); break; case "DateTimeOffset": xmlConv = XmlConvert.ToString((DateTimeOffset)_data); break; case "TimeSpan": xmlConv = XmlConvert.ToString((TimeSpan)_data); break; case "Guid": xmlConv = XmlConvert.ToString((Guid)_data); break; default: TestLog.Skip("No XmlConvert.ToString (" + _data.GetType().Name + ")"); break; } string value = node is XElement ? ((XElement)node).Value : ((XAttribute)node).Value; TestLog.Compare(value == xmlConv, "XmlConvert verification"); break; default: TestLog.Compare(false, "Test failed: wrong test type"); break; } return TestResult.Passed; } } public partial class XElement_Op_Eplicit_Null : XLinqTestCase { protected override void DetermineChildren() { Type nodeType = Params[0] as Type; foreach (Type retType in XElement_Op_Eplicit.typeMapper.Values) { AddChild(new ExplicitCastNullVariation(nodeType, retType, false, this, retType.ToString())); } foreach (Type retType in XElement_Op_Eplicit.typeMapper.Keys) { AddChild(new ExplicitCastNullVariation(nodeType, retType, true, this, retType.ToString())); } } } public partial class ExplicitCastNullVariation : TestVariation { private Type _nodeType, _retType; private bool _shouldThrow; public ExplicitCastNullVariation(Type nodeType, Type retType, bool shouldThrow, TestCase tc, string desc) { this.Desc = desc; _nodeType = nodeType; _retType = retType; _shouldThrow = shouldThrow; } public override TestResult Execute() { try { object ret = null; if (_nodeType.Equals(typeof(XElement))) { XElement e = null; ret = Explicit(_retType, e); } else if (_nodeType.Equals(typeof(XAttribute))) { XAttribute a = null; ret = Explicit(_retType, a); } TestLog.Compare(!_shouldThrow, "The call should throw!"); TestLog.Compare(ret == null, "Return value should be null"); } catch (ArgumentNullException e) { TestLog.Compare(e is ArgumentNullException, "e.InnerException is ArgumentNullException"); TestLog.Compare(_shouldThrow, "shouldThrow"); } return TestResult.Passed; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.SuggestionSupport; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { [Export(typeof(ISuggestedActionsSourceProvider))] [VisualStudio.Utilities.ContentType(ContentTypeNames.CSharpContentType)] [VisualStudio.Utilities.ContentType(ContentTypeNames.VisualBasicContentType)] [VisualStudio.Utilities.Name("Roslyn Code Fix")] [VisualStudio.Utilities.Order] internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider { private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a"); private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6"); private const int InvalidSolutionVersion = -1; private readonly ICodeRefactoringService _codeRefactoringService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeFixService _codeFixService; private readonly ICodeActionEditHandlerService _editHandler; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] public SuggestedActionsSourceProvider( ICodeRefactoringService codeRefactoringService, IDiagnosticAnalyzerService diagnosticService, ICodeFixService codeFixService, ICodeActionEditHandlerService editHandler, [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _codeRefactoringService = codeRefactoringService; _diagnosticService = diagnosticService; _codeFixService = codeFixService; _editHandler = editHandler; _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb); } public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer) { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(textBuffer); return new Source(this, textView, textBuffer); } private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource { // state that will be only reset when source is disposed. private SuggestedActionsSourceProvider _owner; private ITextView _textView; private ITextBuffer _subjectBuffer; private WorkspaceRegistration _registration; // mutable state private Workspace _workspace; private int _lastSolutionVersionReported; public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer) { _owner = owner; _textView = textView; _textView.Closed += OnTextViewClosed; _subjectBuffer = textBuffer; _registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer()); _lastSolutionVersionReported = InvalidSolutionVersion; var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService; updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated; if (_registration.Workspace != null) { _workspace = _registration.Workspace; _workspace.DocumentActiveContextChanged += OnActiveContextChanged; } _registration.WorkspaceChanged += OnWorkspaceChanged; } public event EventHandler<EventArgs> SuggestedActionsChanged; public bool TryGetTelemetryId(out Guid telemetryId) { telemetryId = default(Guid); var workspace = _workspace; if (workspace == null || _subjectBuffer == null) { return false; } var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer()); if (documentId == null) { return false; } var project = workspace.CurrentSolution.GetProject(documentId.ProjectId); if (project == null) { return false; } switch (project.Language) { case LanguageNames.CSharp: telemetryId = s_CSharpSourceGuid; return true; case LanguageNames.VisualBasic: telemetryId = s_visualBasicSourceGuid; return true; default: return false; } } public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken) { AssertIsForeground(); using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken)) { if (range.IsEmpty) { return null; } var documentAndSnapshot = GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken); if (!documentAndSnapshot.HasValue) { // this is here to fail test and see why it is failed. System.Diagnostics.Trace.WriteLine("given range is not current"); return null; } var document = documentAndSnapshot.Value.Item1; var snapshot = documentAndSnapshot.Value.Item2; var workspace = document.Project.Solution.Workspace; var optionService = workspace.Services.GetService<IOptionService>(); var supportSuggestion = workspace.Services.GetService<IDocumentSupportsSuggestionService>(); IEnumerable<SuggestedActionSet> result = null; if (supportSuggestion.SupportsCodeFixes(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix)) { var suggestions = Task.Run( async () => await _owner._codeFixService.GetFixesAsync(document, range.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false), cancellationToken).WaitAndGetResult(cancellationToken); result = OrganizeFixes(workspace, suggestions); } if (supportSuggestion.SupportsRefactorings(document)) { var refactoringResult = GetRefactorings(requestedActionCategories, document, snapshot, workspace, optionService, cancellationToken); result = result == null ? refactoringResult : refactoringResult == null ? result : result.Concat(refactoringResult); } return result; } } /// <summary> /// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups. /// </summary> private IEnumerable<SuggestedActionSet> OrganizeFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections) { var map = ImmutableDictionary.CreateBuilder<Diagnostic, IList<SuggestedAction>>(); var order = ImmutableArray.CreateBuilder<Diagnostic>(); // First group fixes by issue (diagnostic). GroupFixes(workspace, fixCollections, map, order); // Then prioritize between the groups. return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable()); } /// <summary> /// Groups fixes by the diagnostic being addressed by each fix. /// </summary> private void GroupFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, IDictionary<Diagnostic, IList<SuggestedAction>> map, IList<Diagnostic> order) { foreach (var fixCollection in fixCollections) { var fixes = fixCollection.Fixes; var fixCount = fixes.Length; foreach (var fix in fixes) { // Suppression fixes are handled below. if (!(fix.Action is SuppressionCodeAction)) { var fixAllSuggestedActionSet = CodeFixSuggestedAction.GetFixAllSuggestedActionSet(fix.Action, fixCount, fixCollection.FixAllContext, workspace, _subjectBuffer, _owner._editHandler); var suggestedAction = new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, fixCollection.Provider, fixAllSuggestedActionSet); AddFix(fix, suggestedAction, map, order); } } // Add suppression fixes to the end of a given SuggestedActionSet so that they always show up last in a group. foreach (var fix in fixes) { if (fix.Action is SuppressionCodeAction) { var suggestedAction = new SuppressionSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, fixCollection.Provider); AddFix(fix, suggestedAction, map, order); } } } } private static void AddFix(CodeFix fix, SuggestedAction suggestedAction, IDictionary<Diagnostic, IList<SuggestedAction>> map, IList<Diagnostic> order) { var diag = fix.PrimaryDiagnostic; if (!map.ContainsKey(diag)) { // Remember the order of the keys for the 'map' dictionary. order.Add(diag); map[diag] = ImmutableArray.CreateBuilder<SuggestedAction>(); } map[diag].Add(suggestedAction); } /// <summary> /// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list. /// </summary> /// <remarks> /// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default. /// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes - /// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes /// always show up last after all other fixes (and refactorings) for the selected line of code. /// </remarks> private static IEnumerable<SuggestedActionSet> PrioritizeFixGroups(IDictionary<Diagnostic, IList<SuggestedAction>> map, IList<Diagnostic> order) { var sets = ImmutableArray.CreateBuilder<SuggestedActionSet>(); foreach (var diag in order) { var fixes = map[diag]; var priority = fixes.All(s => s is SuppressionSuggestedAction) ? SuggestedActionSetPriority.None : SuggestedActionSetPriority.Medium; var applicableToSpan = new Span(diag.Location.SourceSpan.Start, diag.Location.SourceSpan.Length); sets.Add(new SuggestedActionSet(fixes, priority, applicableToSpan)); } return sets.ToImmutable(); } private IEnumerable<SuggestedActionSet> GetRefactorings( ISuggestedActionCategorySet requestedActionCategories, Document document, ITextSnapshot snapshot, Workspace workspace, IOptionService optionService, CancellationToken cancellationToken) { // For Dev14 Preview, we also want to show refactorings in the CodeFix list when users press Ctrl+. if (requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring) || requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix)) { var refactoringsOn = optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings); if (!refactoringsOn) { return null; } // Get the selection while on the UI thread. var selection = GetCodeRefactoringSelection(snapshot); if (!selection.HasValue) { // this is here to fail test and see why it is failed. System.Diagnostics.Trace.WriteLine("given range is not current"); return null; } var refactorings = Task.Run( async () => await _owner._codeRefactoringService.GetRefactoringsAsync(document, selection.Value, cancellationToken).ConfigureAwait(false), cancellationToken).WaitAndGetResult(cancellationToken); return refactorings.Select(r => OrganizeRefactorings(workspace, r)); } return null; } /// <summary> /// Arrange refactorings into groups. /// </summary> /// <remarks> /// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/> /// and should show up after fixes but before suppression fixes in the light bulb menu. /// </remarks> private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring) { var refactoringSuggestedActions = ImmutableArray.CreateBuilder<SuggestedAction>(); foreach (var a in refactoring.Actions) { refactoringSuggestedActions.Add( new CodeRefactoringSuggestedAction( workspace, _subjectBuffer, _owner._editHandler, a, refactoring.Provider)); } return new SuggestedActionSet(refactoringSuggestedActions.ToImmutable(), SuggestedActionSetPriority.Low); } public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken) { var view = _textView; var buffer = _subjectBuffer; var provider = _owner; if (view == null || buffer == null || provider == null) { return false; } using (var asyncToken = provider._listener.BeginAsyncOperation("HasSuggesetedActionsAsync")) { var result = await HasSuggesetedActionCoreAsync(view, buffer, provider._codeFixService, range, cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return false; } if (result.Value.HasFix) { Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync); return true; } if (result.Value.PartialResult) { // reset solution version number so that we can raise suggested action changed event Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion); return false; } return false; } } private static async Task<FirstDiagnosticResult?> HasSuggesetedActionCoreAsync( ITextView view, ITextBuffer buffer, ICodeFixService service, SnapshotSpan range, CancellationToken cancellationToken) { var documentAndSnapshot = await GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).ConfigureAwait(false); if (!documentAndSnapshot.HasValue) { return null; } var document = documentAndSnapshot.Value.Item1; // make sure current document support codefix var supportCodeFix = document.Project.Solution.Workspace.Services.GetService<IDocumentSupportsSuggestionService>(); if (!supportCodeFix.SupportsCodeFixes(document)) { return null; } return await service.GetFirstDiagnosticWithFixAsync(document, range.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false); } private TextSpan? GetCodeRefactoringSelection(ITextSnapshot snapshot) { var selectedSpans = _textView.Selection.SelectedSpans .SelectMany(ss => _textView.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, _subjectBuffer)) .Where(ss => !_textView.IsReadOnlyOnSurfaceBuffer(ss)) .ToList(); // We only support refactorings when there is a single selection in the document. if (selectedSpans.Count != 1) { return null; } var selectedSpan = selectedSpans[0]; return selectedSpan.TranslateTo(snapshot, SpanTrackingMode.EdgeInclusive).Span.ToTextSpan(); } private static async Task<ValueTuple<Document, ITextSnapshot>?> GetMatchingDocumentAndSnapshotAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken) { var buffer = givenSnapshot.TextBuffer; if (buffer == null) { return null; } var workspace = buffer.GetWorkspace(); if (workspace == null) { return null; } var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()); if (documentId == null) { return null; } var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { return null; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var snapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber) { return null; } return ValueTuple.Create(document, snapshot); } private void OnTextViewClosed(object sender, EventArgs e) { Dispose(); } private void OnWorkspaceChanged(object sender, EventArgs e) { // REVIEW: this event should give both old and new workspace as argument so that // one doesnt need to hold onto workspace in field. // remove existing event registration if (_workspace != null) { _workspace.DocumentActiveContextChanged -= OnActiveContextChanged; } // REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace? // add new event registration _workspace = _registration.Workspace; if (_workspace != null) { _workspace.DocumentActiveContextChanged += OnActiveContextChanged; } } private void OnActiveContextChanged(object sender, DocumentEventArgs e) { // REVIEW: it would be nice for changed event to pass in both old and new document. OnSuggestedActionsChanged(e.Document.Project.Solution.Workspace, e.Document.Id, e.Document.Project.Solution.WorkspaceVersion); } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { // document removed case. no reason to raise event if (e.Solution == null) { return; } OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion); } private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null) { if (_subjectBuffer == null) { return; } var workspace = _subjectBuffer.GetWorkspace(); // workspace is not ready, nothing to do. if (workspace == null || workspace != currentWorkspace) { return; } if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer()) || solutionVersion == Volatile.Read(ref _lastSolutionVersionReported)) { return; } // make sure we only raise event once for same solution version. // light bulb controller will call us back to find out new information var changed = this.SuggestedActionsChanged; if (changed != null) { changed(this, EventArgs.Empty); } Volatile.Write(ref _lastSolutionVersionReported, solutionVersion); } public void Dispose() { if (_owner != null) { var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService; updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated; _owner = null; } if (_workspace != null) { _workspace.DocumentActiveContextChanged -= OnActiveContextChanged; _workspace = null; } if (_registration != null) { _registration.WorkspaceChanged -= OnWorkspaceChanged; _registration = null; } if (_textView != null) { _textView.Closed -= OnTextViewClosed; _textView = null; } if (_subjectBuffer != null) { _subjectBuffer = null; } } } } }
// // MacEngine.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGSize = System.Drawing.SizeF; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using MonoMac.CoreGraphics; #else using Foundation; using AppKit; using ObjCRuntime; using CoreGraphics; #endif namespace Xwt.Mac { public class MacEngine: Xwt.Backends.ToolkitEngineBackend { static AppDelegate appDelegate; static NSAutoreleasePool pool; public static AppDelegate App { get { return appDelegate; } } public override void InitializeApplication () { NSApplication.Init (); //Hijack (); if (pool != null) pool.Dispose (); pool = new NSAutoreleasePool (); appDelegate = new AppDelegate (IsGuest); NSApplication.SharedApplication.Delegate = appDelegate; // If NSPrincipalClass is not set, set it now. This allows running // the application without a bundle var info = NSBundle.MainBundle.InfoDictionary; if (info.ValueForKey ((NSString)"NSPrincipalClass") == null) info.SetValueForKey ((NSString)"NSApplication", (NSString)"NSPrincipalClass"); } public override void InitializeBackends () { base.InitializeBackends (); RegisterBackend <Xwt.Backends.ICustomWidgetBackend, CustomWidgetBackend> (); RegisterBackend <Xwt.Backends.IWindowBackend, WindowBackend> (); RegisterBackend <Xwt.Backends.ILabelBackend, LabelBackend> (); RegisterBackend <Xwt.Backends.IBoxBackend, BoxBackend> (); RegisterBackend <Xwt.Backends.IButtonBackend, ButtonBackend> (); RegisterBackend <Xwt.Backends.IMenuButtonBackend, MenuButtonBackend> (); RegisterBackend <Xwt.Backends.INotebookBackend, NotebookBackend> (); RegisterBackend <Xwt.Backends.ITreeViewBackend, TreeViewBackend> (); RegisterBackend <Xwt.Backends.IListViewBackend, ListViewBackend> (); RegisterBackend <Xwt.Backends.ICanvasBackend, CanvasBackend> (); RegisterBackend <Xwt.Backends.ImageBackendHandler, ImageHandler> (); RegisterBackend <Xwt.Backends.ContextBackendHandler, MacContextBackendHandler> (); RegisterBackend <Xwt.Backends.DrawingPathBackendHandler, MacPathBackendHandler> (); RegisterBackend <Xwt.Backends.ImageBuilderBackendHandler, MacImageBuilderBackendHandler> (); RegisterBackend <Xwt.Backends.ImagePatternBackendHandler, MacImagePatternBackendHandler> (); RegisterBackend <Xwt.Backends.GradientBackendHandler, MacGradientBackendHandler> (); RegisterBackend <Xwt.Backends.TextLayoutBackendHandler, MacTextLayoutBackendHandler> (); RegisterBackend <Xwt.Backends.FontBackendHandler, MacFontBackendHandler> (); RegisterBackend <Xwt.Backends.IMenuBackend, MenuBackend> (); RegisterBackend <Xwt.Backends.IMenuItemBackend, MenuItemBackend> (); RegisterBackend <Xwt.Backends.ICheckBoxMenuItemBackend, CheckBoxMenuItemBackend> (); RegisterBackend <Xwt.Backends.IRadioButtonMenuItemBackend, RadioButtonMenuItemBackend> (); RegisterBackend <Xwt.Backends.IRadioButtonBackend, RadioButtonBackend> (); RegisterBackend <Xwt.Backends.ISeparatorMenuItemBackend, SeparatorMenuItemBackend> (); RegisterBackend <Xwt.Backends.IComboBoxBackend, ComboBoxBackend> (); RegisterBackend <Xwt.Backends.IComboBoxEntryBackend, ComboBoxEntryBackend> (); RegisterBackend <Xwt.Backends.ITextEntryBackend, TextEntryBackend> (); RegisterBackend <Xwt.Backends.IImageViewBackend, ImageViewBackend> (); RegisterBackend <Xwt.Backends.ICheckBoxBackend, CheckBoxBackend> (); RegisterBackend <Xwt.Backends.IFrameBackend, FrameBackend> (); RegisterBackend <Xwt.Backends.IScrollViewBackend, ScrollViewBackend> (); RegisterBackend <Xwt.Backends.IToggleButtonBackend, ToggleButtonBackend> (); RegisterBackend <Xwt.Backends.ISeparatorBackend, SeparatorBackend> (); RegisterBackend <Xwt.Backends.IPanedBackend, PanedBackend> (); RegisterBackend <Xwt.Backends.IAlertDialogBackend, AlertDialogBackend> (); RegisterBackend <Xwt.Backends.IStatusIconBackend, StatusIconBackend> (); RegisterBackend <Xwt.Backends.IProgressBarBackend, ProgressBarBackend> (); RegisterBackend <Xwt.Backends.IListStoreBackend, Xwt.DefaultListStoreBackend> (); RegisterBackend <Xwt.Backends.ILinkLabelBackend, LinkLabelBackend> (); RegisterBackend <Xwt.Backends.ISpinnerBackend, SpinnerBackend> (); RegisterBackend <Xwt.Backends.ISpinButtonBackend, SpinButtonBackend> (); RegisterBackend <Xwt.Backends.IExpanderBackend, ExpanderBackend> (); RegisterBackend <Xwt.Backends.IPopoverBackend, PopoverBackend> (); RegisterBackend <Xwt.Backends.ISelectFolderDialogBackend, SelectFolderDialogBackend> (); RegisterBackend <Xwt.Backends.IOpenFileDialogBackend, OpenFileDialogBackend> (); RegisterBackend <Xwt.Backends.ClipboardBackend, MacClipboardBackend> (); RegisterBackend <Xwt.Backends.DesktopBackend, MacDesktopBackend> (); RegisterBackend <Xwt.Backends.IMenuButtonBackend, MenuButtonBackend> (); RegisterBackend <Xwt.Backends.IListBoxBackend, ListBoxBackend> (); RegisterBackend <Xwt.Backends.IDialogBackend, DialogBackend> (); RegisterBackend <Xwt.Backends.IRichTextViewBackend, RichTextViewBackend> (); RegisterBackend <Xwt.Backends.IScrollbarBackend, ScrollbarBackend> (); RegisterBackend <Xwt.Backends.IDatePickerBackend, DatePickerBackend> (); RegisterBackend <Xwt.Backends.ISliderBackend, SliderBackend> (); RegisterBackend <Xwt.Backends.IEmbeddedWidgetBackend, EmbedNativeWidgetBackend> (); RegisterBackend <Xwt.Backends.KeyboardHandler, MacKeyboardHandler> (); RegisterBackend <Xwt.Backends.IPasswordEntryBackend, PasswordEntryBackend> (); RegisterBackend <Xwt.Backends.IWebViewBackend, WebViewBackend> (); RegisterBackend <Xwt.Backends.ISaveFileDialogBackend, SaveFileDialogBackend> (); RegisterBackend <Xwt.Backends.IColorPickerBackend, ColorPickerBackend> (); RegisterBackend <Xwt.Backends.ICalendarBackend,CalendarBackend> (); RegisterBackend <Xwt.Backends.ISelectFontDialogBackend, SelectFontDialogBackend> (); } public override void RunApplication () { pool.Dispose (); NSApplication.Main (new string [0]); pool = new NSAutoreleasePool (); } public override void ExitApplication () { NSApplication.SharedApplication.Terminate(appDelegate); } static Selector hijackedSel = new Selector ("hijacked_loadNibNamed:owner:"); static Selector originalSel = new Selector ("loadNibNamed:owner:"); static void Hijack () { Class c = ObjcHelper.GetMetaClass ("NSBundle"); if (!c.AddMethod (hijackedSel.Handle, new Func<IntPtr, IntPtr, IntPtr, IntPtr,bool>(HijackedLoadNibNamed), "B@:@@")) throw new Exception ("Failed to add method"); c.MethodExchange (originalSel.Handle, hijackedSel.Handle); } static bool HijackedLoadNibNamed (IntPtr self, IntPtr sel, IntPtr filePath, IntPtr owner) { var str = (NSString) Runtime.GetNSObject (filePath); if (str.Length == 0) return true; return Messaging.bool_objc_msgSend_IntPtr_IntPtr (self, hijackedSel.Handle, filePath, owner); } public override void InvokeAsync (Action action) { if (action == null) throw new ArgumentNullException ("action"); NSRunLoop.Main.BeginInvokeOnMainThread (delegate { action (); }); } public override object TimerInvoke (Func<bool> action, TimeSpan timeSpan) { NSTimer timer = null; var runLoop = NSRunLoop.Current; timer = NSTimer.CreateRepeatingTimer (timeSpan, delegate { if (!action ()) timer.Invalidate (); }); runLoop.AddTimer (timer, NSRunLoop.NSDefaultRunLoopMode); runLoop.AddTimer (timer, NSRunLoop.NSRunLoopModalPanelMode); return timer; } public override void CancelTimerInvoke (object id) { ((NSTimer)id).Invalidate (); } public override object GetNativeWidget (Widget w) { var wb = GetNativeBackend (w); wb.SetAutosizeMode (true); return wb.Widget; } public override bool HasNativeParent (Widget w) { var wb = GetNativeBackend (w); return wb.Widget.Superview != null; } public ViewBackend GetNativeBackend (Widget w) { var backend = Toolkit.GetBackend (w); if (backend is ViewBackend) return (ViewBackend)backend; if (backend is XwtWidgetBackend) return GetNativeBackend ((Widget)backend); return null; } public override Xwt.Backends.IWindowFrameBackend GetBackendForWindow (object nativeWindow) { throw new NotImplementedException (); } public override object GetBackendForContext (object nativeWidget, object nativeContext) { return new CGContextBackend { Context = (CGContext)nativeContext }; } public override void DispatchPendingEvents () { var until = NSDate.DistantPast; var app = NSApplication.SharedApplication; var p = new NSAutoreleasePool (); while (true) { var ev = app.NextEvent (NSEventMask.AnyEvent, until, NSRunLoop.NSDefaultRunLoopMode, true); if (ev != null) app.SendEvent (ev); else break; } p.Dispose (); } public override object RenderWidget (Widget w) { var view = ((ViewBackend)w.GetBackend ()).Widget; view.LockFocus (); var img = new NSImage (view.DataWithPdfInsideRect (view.Bounds)); var imageData = img.AsTiff (); var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData (imageData); var im = new NSImage (); im.AddRepresentation (imageRep); im.Size = new CGSize ((nfloat)view.Bounds.Width, (nfloat)view.Bounds.Height); return im; } } public class AppDelegate : NSApplicationDelegate { bool launched; List<WindowBackend> pendingWindows = new List<WindowBackend> (); public event EventHandler<TerminationEventArgs> Terminating; public event EventHandler Unhidden; public event EventHandler<OpenFilesEventArgs> OpenFilesRequest; public event EventHandler<OpenUrlEventArgs> OpenUrl; public AppDelegate (bool launched) { this.launched = launched; } internal void ShowWindow (WindowBackend w) { if (!launched) { if (!pendingWindows.Contains (w)) pendingWindows.Add (w); } else w.InternalShow (); } public override void DidFinishLaunching (NSNotification notification) { launched = true; foreach (var w in pendingWindows) w.InternalShow (); NSAppleEventManager eventManager = NSAppleEventManager.SharedAppleEventManager; eventManager.SetEventHandler (this, new Selector ("handleGetURLEvent:withReplyEvent:"), AEEventClass.Internet, AEEventID.GetUrl); } [Export("handleGetURLEvent:withReplyEvent:")] void HandleGetUrlEvent(NSAppleEventDescriptor descriptor, NSAppleEventDescriptor reply) { var openUrlEvent = OpenUrl; if (openUrlEvent == null) return; string keyDirectObjectString = "----"; uint keywordDirectObject = (((uint)keyDirectObjectString [0]) << 24 | ((uint)keyDirectObjectString [1]) << 16 | ((uint)keyDirectObjectString [2]) << 8 | ((uint)keyDirectObjectString [3])); string urlString = descriptor.ParamDescriptorForKeyword (keywordDirectObject).ToString (); openUrlEvent (NSApplication.SharedApplication, new OpenUrlEventArgs (urlString)); } public override void ScreenParametersChanged (NSNotification notification) { if (MacDesktopBackend.Instance != null) MacDesktopBackend.Instance.NotifyScreensChanged (); } public override NSApplicationTerminateReply ApplicationShouldTerminate (NSApplication sender) { var terminatingEvent = Terminating; if (terminatingEvent != null) { var args = new TerminationEventArgs (); terminatingEvent (NSApplication.SharedApplication, args); return args.Reply; } return NSApplicationTerminateReply.Now; } public override void DidUnhide (NSNotification notification) { var unhiddenEvent = Unhidden; if (unhiddenEvent != null) unhiddenEvent (NSApplication.SharedApplication, EventArgs.Empty); } public override void OpenFiles (NSApplication sender, string[] filenames) { var openFilesEvent = OpenFilesRequest; if (openFilesEvent != null) { var args = new OpenFilesEventArgs (filenames); openFilesEvent (NSApplication.SharedApplication, args); } } } public class TerminationEventArgs : EventArgs { public NSApplicationTerminateReply Reply {get; set;} public TerminationEventArgs () { Reply = NSApplicationTerminateReply.Now; } } public class OpenFilesEventArgs : EventArgs { public string[] Filenames { get; set; } public OpenFilesEventArgs (string[] filenames) { Filenames = filenames; } } public class OpenUrlEventArgs : EventArgs { public string Url { get; set; } public OpenUrlEventArgs (string url) { Url = url; } } }
using DocumentFormat.OpenXml.Packaging; using Signum.Entities.Word; using System.IO; using Signum.Engine.UserAssets; using Signum.Engine.Templating; using Signum.Entities.Files; using Signum.Utilities.DataStructures; using DocumentFormat.OpenXml; using W = DocumentFormat.OpenXml.Wordprocessing; using System.Data; using System.Globalization; using Signum.Entities.Reflection; using Signum.Entities.Templating; using Signum.Engine.Authorization; using Signum.Entities.Basics; namespace Signum.Engine.Word; public interface IWordDataTableProvider { string? Validate(string suffix, WordTemplateEntity template); DataTable GetDataTable(string suffix, WordTemplateLogic.WordContext context); } public static class WordTemplateLogic { public static bool AvoidSynchronize = false; public static ResetLazy<Dictionary<Lite<WordTemplateEntity>, WordTemplateEntity>> WordTemplatesLazy = null!; public static ResetLazy<Dictionary<object, List<WordTemplateEntity>>> TemplatesByQueryName = null!; public static ResetLazy<Dictionary<Type, List<WordTemplateEntity>>> TemplatesByEntityType = null!; public static Dictionary<WordTransformerSymbol, Action<WordContext, OpenXmlPackage>> Transformers = new Dictionary<WordTransformerSymbol, Action<WordContext, OpenXmlPackage>>(); public static Dictionary<WordConverterSymbol, Func<WordContext, byte[], byte[]>> Converters = new Dictionary<WordConverterSymbol, Func<WordContext, byte[], byte[]>>(); public static Dictionary<string, IWordDataTableProvider> ToDataTableProviders = new Dictionary<string, IWordDataTableProvider>(); public static Func<Entity?, CultureInfo>? GetCultureInfo; [AutoExpressionField] public static IQueryable<WordTemplateEntity> WordTemplates(this WordModelEntity e) => As.Expression(() => Database.Query<WordTemplateEntity>().Where(a => a.Model.Is(e))); public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<WordTemplateEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.Query, e.Culture, e.Template!.Entity.FileName }); new Graph<WordTemplateEntity>.Execute(WordTemplateOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (wt, _) => { if (!wt.IsNew) { var oldFile = wt.InDB(t => t.Template); if (oldFile != null && !wt.Template.Is(oldFile)) Transaction.PreRealCommit += dic => oldFile.Delete(); } }, }.Register(); new Graph<WordTemplateEntity>.Delete(WordTemplateOperation.Delete) { Delete = (e, _) => e.Delete(), }.Register(); sb.Schema.EntityEvents<WordTemplateEntity>().Retrieved += WordTemplateLogic_Retrieved; PermissionAuthLogic.RegisterPermissions(WordTemplatePermission.GenerateReport); WordModelLogic.Start(sb); SymbolLogic<WordTransformerSymbol>.Start(sb, () => Transformers.Keys.ToHashSet()); SymbolLogic<WordConverterSymbol>.Start(sb, () => Converters.Keys.ToHashSet()); sb.Include<WordTransformerSymbol>() .WithQuery(() => f => new { Entity = f, f.Key }); sb.Include<WordConverterSymbol>() .WithQuery(() => f => new { Entity = f, f.Key }); sb.Schema.Table<WordModelEntity>().PreDeleteSqlSync += e => Administrator.UnsafeDeletePreCommand(Database.Query<WordTemplateEntity>() .Where(a => a.Model.Is(e))); ToDataTableProviders.Add("Model", new ModelDataTableProvider()); ToDataTableProviders.Add("UserQuery", new UserQueryDataTableProvider()); ToDataTableProviders.Add("UserChart", new UserChartDataTableProvider()); QueryLogic.Expressions.Register((WordModelEntity e) => e.WordTemplates(), () => typeof(WordTemplateEntity).NiceName()); new Graph<WordTemplateEntity>.Execute(WordTemplateOperation.CreateWordReport) { CanExecute = et => { if (et.Model != null && WordModelLogic.RequiresExtraParameters(et.Model)) return WordTemplateMessage._01RequiresExtraParameters.NiceToString(typeof(WordModelEntity).NiceName(), et.Model); return null; }, Execute = (et, args) => { throw new InvalidOperationException("UI-only operation"); } }.Register(); WordTemplatesLazy = sb.GlobalLazy(() => Database.Query<WordTemplateEntity>() .ToDictionary(et => et.ToLite()), new InvalidateWith(typeof(WordTemplateEntity))); TemplatesByQueryName = sb.GlobalLazy(() => { return WordTemplatesLazy.Value.Values.SelectCatch(w => KeyValuePair.Create(w.Query.ToQueryName(), w)).GroupToDictionary(); }, new InvalidateWith(typeof(WordTemplateEntity))); TemplatesByEntityType = sb.GlobalLazy(() => { return (from pair in WordTemplatesLazy.Value.Values.SelectCatch(wr => new { wr, imp = QueryLogic.Queries.GetEntityImplementations(wr.Query.ToQueryName()) }) where !pair.imp.IsByAll from t in pair.imp.Types select KeyValuePair.Create(t, pair.wr)) .GroupToDictionary(); }, new InvalidateWith(typeof(WordTemplateEntity))); Schema.Current.Synchronizing += Schema_Synchronize_Tokens; Validator.PropertyValidator((WordTemplateEntity e) => e.Template).StaticPropertyValidation += ValidateTemplate; } } private static void WordTemplateLogic_Retrieved(WordTemplateEntity template, PostRetrievingContext ctx) { object? queryName = template.Query.ToQueryNameCatch(); if (queryName == null) return; QueryDescription description = QueryLogic.Queries.QueryDescription(queryName); template.ParseData(description); } public static Dictionary<Type, WordTemplateVisibleOn> VisibleOnDictionary = new Dictionary<Type, WordTemplateVisibleOn>() { { typeof(MultiEntityModel), WordTemplateVisibleOn.Single | WordTemplateVisibleOn.Multiple}, { typeof(QueryModel), WordTemplateVisibleOn.Single | WordTemplateVisibleOn.Multiple| WordTemplateVisibleOn.Query}, }; public static bool IsVisible(WordTemplateEntity wt, WordTemplateVisibleOn visibleOn) { if (wt.Model == null) return visibleOn == WordTemplateVisibleOn.Single; if (WordModelLogic.HasDefaultTemplateConstructor(wt.Model)) return false; var entityType = WordModelLogic.GetEntityType(wt.Model.ToType()); if (entityType.IsEntity()) return visibleOn == WordTemplateVisibleOn.Single; var should = VisibleOnDictionary.TryGet(entityType, WordTemplateVisibleOn.Single); return ((should & visibleOn) != 0); } public static List<Lite<WordTemplateEntity>> GetApplicableWordTemplates(object queryName, Entity? entity, WordTemplateVisibleOn visibleOn) { var isAllowed = Schema.Current.GetInMemoryFilter<WordTemplateEntity>(userInterface: false); return TemplatesByQueryName.Value.TryGetC(queryName).EmptyIfNull() .Where(a => isAllowed(a) && IsVisible(a, visibleOn)) .Where(a => a.IsApplicable(entity)) .Select(a => a.ToLite()) .ToList(); } public static void RegisterTransformer(WordTransformerSymbol transformerSymbol, Action<WordContext, OpenXmlPackage> transformer) { if (transformerSymbol == null) throw AutoInitAttribute.ArgumentNullException(typeof(WordTransformerSymbol), nameof(transformerSymbol)); Transformers.Add(transformerSymbol, transformer); } public class WordContext { public WordTemplateEntity Template; public Entity? Entity; public IWordModel? Model; public WordContext(WordTemplateEntity template, Entity? entity, IWordModel? model) { Template = template; Entity = entity; Model = model; } public Entity? GetEntity() => Entity ?? Model?.UntypedEntity as Entity; } public static void RegisterConverter(WordConverterSymbol converterSymbol, Func<WordContext, byte[], byte[]> converter) { if (converterSymbol == null) throw new ArgumentNullException(nameof(converterSymbol)); Converters.Add(converterSymbol, converter); } static string? ValidateTemplate(WordTemplateEntity template, PropertyInfo pi) { if (template.Template == null) return null; using (template.DisableAuthorization ? ExecutionMode.Global() : null) { QueryDescription qd = QueryLogic.Queries.QueryDescription(template.Query.ToQueryName()); string? error = null; template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); parser.ParseDocument(); Dump(document, "1.Match.txt"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); parser.AssertClean(); error = parser.Errors.IsEmpty() ? null : parser.Errors.ToString(e => e.Message, "\r\n"); }); return error; } } public class FileNameBox { public string? FileName { get; set; } } public static FileContent CreateReportFileContent(this Lite<WordTemplateEntity> liteTemplate, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false) { var box = new FileNameBox { FileName = null }; var bytes = liteTemplate.GetFromCache().CreateReport(modifiableEntity, model, avoidConversion, box); return new FileContent(box.FileName!, bytes); } public static byte[] CreateReport(this Lite<WordTemplateEntity> liteTemplate, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false, FileNameBox? fileNameBox = null) { return liteTemplate.GetFromCache().CreateReport(modifiableEntity, model, avoidConversion, fileNameBox); } public static WordTemplateEntity GetFromCache(this Lite<WordTemplateEntity> liteTemplate) { WordTemplateEntity template = WordTemplatesLazy.Value.GetOrThrow(liteTemplate, "Word report template {0} not in cache".FormatWith(liteTemplate)); return template; } public static FileContent CreateReportFileContent(this WordTemplateEntity template, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false) { var box = new FileNameBox { FileName = null }; var bytes = template.CreateReport(modifiableEntity, model, avoidConversion, box); return new FileContent(box.FileName!, bytes); } public static string? DumpFileFolder = null; public static byte[] CreateReport(this WordTemplateEntity template, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false, FileNameBox? fileNameBox = null) { using (HeavyProfiler.Log("CreateReport", () => $"{template.Name} {modifiableEntity?.ToString()} {model?.UntypedEntity.ToString()}")) { try { WordTemplatePermission.GenerateReport.AssertAuthorized(); Entity? entity = null; if (template.Model != null) { if (model == null) model = WordModelLogic.CreateDefaultWordModel(template.Model, modifiableEntity); else if (template.Model.ToType() != model.GetType()) throw new ArgumentException("model should be a {0} instead of {1}".FormatWith(template.Model.FullClassName, model.GetType().FullName)); } else { entity = modifiableEntity as Entity ?? throw new InvalidOperationException("Model should be an Entity"); } using (template.DisableAuthorization ? ExecutionMode.Global() : null) using (CultureInfoUtils.ChangeBothCultures(template.Culture.ToCultureInfo())) { QueryDescription qd = QueryLogic.Queries.QueryDescription(template.Query.ToQueryName()); using (var p = HeavyProfiler.Log("ProcessOpenXmlPackage")) { var array = template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); p.Switch("ParseDocument"); parser.ParseDocument(); Dump(document, "1.Match.txt"); p.Switch("CreateNodes"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); p.Switch("AssertClean"); parser.AssertClean(); if (parser.Errors.Any()) throw new InvalidOperationException("Error in template {0}:\r\n".FormatWith(template) + parser.Errors.ToString(e => e.Message, "\r\n")); var parsedFileName = fileNameBox != null ? TextTemplateParser.Parse(template.FileName, qd, template.Model?.ToType()) : null; var renderer = new WordTemplateRenderer(document, qd, template.Culture.ToCultureInfo(), template, model, entity, parsedFileName); p.Switch("MakeQuery"); renderer.ExecuteQuery(); p.Switch("RenderNodes"); renderer.RenderNodes(); Dump(document, "3.Replaced.txt"); p.Switch("AssertClean"); renderer.AssertClean(); p.Switch("FixDocument"); FixDocument(document); Dump(document, "4.Fixed.txt"); if (fileNameBox != null) { p.Switch("RenderFileName"); fileNameBox.FileName = renderer.RenderFileName(); } if (template.WordTransformer != null) { p.Switch("WordTransformer"); Transformers.GetOrThrow(template.WordTransformer)(new WordContext(template, entity, model), document); } }); if (!avoidConversion && template.WordConverter != null) { p.Switch("WordConverter"); array = Converters.GetOrThrow(template.WordConverter)(new WordContext(template, entity, model), array); } return array; } } } catch (Exception e) { e.Data["WordTemplate"] = template.ToLite(); e.Data["ModifiableEntity"] = modifiableEntity; e.Data["Model"] = model; throw; } } } private static void FixDocument(OpenXmlPackage document) { foreach (var root in document.AllRootElements()) { foreach (var cell in root.Descendants<W.TableCell>().ToList()) { if (!cell.ChildElements.Any(c => !(c is W.TableCellProperties))) cell.AppendChild(new W.Paragraph()); } } } private static void Dump(OpenXmlPackage document, string fileName) { if (DumpFileFolder == null) return; if (!Directory.Exists(DumpFileFolder)) Directory.CreateDirectory(DumpFileFolder); foreach (var part in AllParts(document).Where(p => p.RootElement != null)) { string fullFileName = Path.Combine(DumpFileFolder, part.Uri.ToString().Replace("/", "_") + "." + fileName); File.WriteAllText(fullFileName, part.RootElement!.NiceToString()); } } static SqlPreCommand? Schema_Synchronize_Tokens(Replacements replacements) { if (AvoidSynchronize) return null; StringDistance sd = new StringDistance(); var emailTemplates = Database.Query<WordTemplateEntity>().ToList(); SqlPreCommand? cmd = emailTemplates.Select(uq => SynchronizeWordTemplate(replacements, uq, sd)).Combine(Spacing.Double); return cmd; } internal static SqlPreCommand? SynchronizeWordTemplate(Replacements replacements, WordTemplateEntity template, StringDistance sd) { Console.Write("."); try { if (template.Template == null || !replacements.Interactive) return null; var queryName = QueryLogic.ToQueryName(template.Query.Key); QueryDescription qd = QueryLogic.Queries.QueryDescription(queryName); using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "WordTemplate: " + template.Name))) using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + template.Query.Key))) { var file = template.Template.RetrieveAndRemember(); var oldHash = file.Hash; try { var sc = new TemplateSynchronizationContext(replacements, sd, qd, template.Model?.ToType()); var bytes = template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); parser.ParseDocument(); Dump(document, "1.Match.txt"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); parser.AssertClean(); foreach (var root in document.AllRootElements()) { foreach (var node in root.Descendants<BaseNode>().ToList()) { node.Synchronize(sc); } } if (sc.HasChanges) { Dump(document, "3.Synchronized.txt"); var variables = new ScopedDictionary<string, ValueProviderBase>(null); foreach (var root in document.AllRootElements()) { foreach (var node in root.Descendants<BaseNode>().ToList()) { node.RenderTemplate(variables); } } Dump(document, "4.Rendered.txt"); } }); if (!sc.HasChanges) return null; file.AllowChange = true; file.BinaryFile = bytes; using (replacements.WithReplacedDatabaseName()) return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, f => f.Hash == oldHash, comment: "WordTemplate: " + template.Name); } catch (TemplateSyncException ex) { if (ex.Result == FixTokenResult.SkipEntity) return null; if (ex.Result == FixTokenResult.DeleteEntity) return SqlPreCommandConcat.Combine(Spacing.Simple, Schema.Current.Table<WordTemplateEntity>().DeleteSqlSync(template, wt => wt.Name == template.Name), Schema.Current.Table<FileEntity>().DeleteSqlSync(file, f => f.Hash == file.Hash)); if (ex.Result == FixTokenResult.ReGenerateEntity) return Regenerate(template, replacements); throw new InvalidOperationException("Unexcpected {0}".FormatWith(ex.Result)); } } } catch (Exception e) { return new SqlPreCommandSimple("-- Exception in {0}: \r\n{1}".FormatWith(template.BaseToString(), e.Message.Indent(2, '-'))); } } public static byte[] ProcessOpenXmlPackage(this WordTemplateEntity template, Action<OpenXmlPackage> processPackage) { var file = template.Template!.RetrieveAndRemember(); using (var memory = new MemoryStream()) { memory.WriteAllBytes(file.BinaryFile); var ext = Path.GetExtension(file.FileName).ToLower(); var document = ext == ".docx" ? (OpenXmlPackage)WordprocessingDocument.Open(memory, true) : ext == ".pptx" ? (OpenXmlPackage)PresentationDocument.Open(memory, true) : ext == ".xlsx" ? (OpenXmlPackage)SpreadsheetDocument.Open(memory, true) : throw new InvalidOperationException("Extension '{0}' not supported".FormatWith(ext)); using (document) { processPackage(document); } return memory.ToArray(); } } public static bool Regenerate(WordTemplateEntity template) { var result = Regenerate(template, null); if (result == null) return false; result.ExecuteLeaves(); return true; } private static SqlPreCommand? Regenerate(WordTemplateEntity template, Replacements? replacements) { var newTemplate = template.Model == null ? null : WordModelLogic.CreateDefaultTemplate(template.Model); if (newTemplate == null) return null; var file = template.Template!.RetrieveAndRemember(); using (file.AllowChanges()) { file.BinaryFile = newTemplate.Template!.Entity.BinaryFile; file.FileName = newTemplate.Template!.Entity.FileName; return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, f => f.Hash == file.Hash, comment: "WordTemplate Regenerated: " + template.Name); } } public static IEnumerable<OpenXmlPartRootElement> AllRootElements(this OpenXmlPartContainer document) { return AllParts(document).Select(p => p.RootElement).NotNull(); } public static IEnumerable<OpenXmlPart> AllParts(this OpenXmlPartContainer container) { var roots = container.Parts.Select(a => a.OpenXmlPart); var result = DirectedGraph<OpenXmlPart>.Generate(roots, c => c.Parts.Select(a => a.OpenXmlPart)); return result; } public static void GenerateDefaultTemplates() { var wordModels = Database.Query<WordModelEntity>().Where(se => !se.WordTemplates().Any()).ToList(); List<string> exceptions = new List<string>(); foreach (var se in wordModels) { try { var defaultTemplate = WordModelLogic.CreateDefaultTemplate(se); if (defaultTemplate != null) defaultTemplate.Save(); } catch (Exception ex) { exceptions.Add("{0} in {1}:\r\n{2}".FormatWith(ex.GetType().Name, se.FullClassName, ex.Message.Indent(4))); } } if (exceptions.Any()) throw new Exception(exceptions.ToString("\r\n\r\n")); } public static void OverrideWordTemplatesConsole() { var wordTemplates = Database.Query<WordTemplateEntity>().Where(a=>a.Model != null).GroupToDictionary(a => a.Model!); var wordModels = Database.Query<WordModelEntity>().ToList(); List<string> exceptions = new List<string>(); bool? rememberedAnswer = null; foreach (var se in wordModels) { try { var defaultTemplate = WordModelLogic.CreateDefaultTemplate(se); if (defaultTemplate != null && defaultTemplate.Template != null) { var already = wordTemplates.TryGetC(se); if (already == null) { defaultTemplate.Save(); SafeConsole.WriteLineColor(ConsoleColor.Green, $"Created {se.FullClassName}"); } else { var toModify = already.Only() ?? already.ChooseConsole(); if (toModify != null) { if (toModify.Template == null) { toModify.Template = defaultTemplate.Template; toModify.Save(); SafeConsole.WriteLineColor(ConsoleColor.Yellow, $"Initialized {se.FullClassName}"); } else if (MemoryExtensions.SequenceEqual<byte>(toModify.Template.Retrieve().BinaryFile, defaultTemplate.Template.Entity.BinaryFile)) { SafeConsole.WriteLineColor(ConsoleColor.DarkGray, $"Identical {se.FullClassName}"); } else { if (SafeConsole.Ask(ref rememberedAnswer, $"Override {se.FullClassName}?")) { toModify.Template = defaultTemplate.Template; toModify.Save(); SafeConsole.WriteLineColor(ConsoleColor.Yellow, $"Overriden {se.FullClassName}"); } } } } } } catch (Exception ex) { SafeConsole.WriteLineColor(ConsoleColor.Red, se.FullClassName); SafeConsole.WriteLineColor(ConsoleColor.Red, "{0} in {1}:\r\n{2}".FormatWith(ex.GetType().Name, se.FullClassName, ex.Message.Indent(4))); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading.Tasks; using System.Xml; namespace System.ServiceModel.Channels { public abstract class Message : IDisposable { private MessageState _state; internal const int InitialBufferSize = 1024; public abstract MessageHeaders Headers { get; } // must never return null protected bool IsDisposed { get { return _state == MessageState.Closed; } } public virtual bool IsFault { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return false; } } public virtual bool IsEmpty { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return false; } } public abstract MessageProperties Properties { get; } public abstract MessageVersion Version { get; } // must never return null internal virtual RecycledMessageState RecycledMessageState { get { return null; } } public MessageState State { get { return _state; } } internal void BodyToString(XmlDictionaryWriter writer) { OnBodyToString(writer); } public void Close() { if (_state != MessageState.Closed) { _state = MessageState.Closed; OnClose(); } else { } } public MessageBuffer CreateBufferedCopy(int maxBufferSize) { if (maxBufferSize < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, SR.ValueMustBeNonNegative), this); switch (_state) { case MessageState.Created: _state = MessageState.Copied; break; case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } return OnCreateBufferedCopy(maxBufferSize); } private static Type GetObjectType(object value) { return (value == null) ? typeof(object) : value.GetType(); } static public Message CreateMessage(MessageVersion version, string action, object body) { return CreateMessage(version, action, body, DataContractSerializerDefaults.CreateSerializer(GetObjectType(body), int.MaxValue/*maxItems*/)); } static public Message CreateMessage(MessageVersion version, string action, object body, XmlObjectSerializer serializer) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return new BodyWriterMessage(version, action, new XmlObjectSerializerBodyWriter(body, serializer)); } static public Message CreateMessage(MessageVersion version, string action, XmlReader body) { return CreateMessage(version, action, XmlDictionaryReader.CreateDictionaryReader(body)); } static public Message CreateMessage(MessageVersion version, string action, XmlDictionaryReader body) { if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("body"); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); return CreateMessage(version, action, new XmlReaderBodyWriter(body, version.Envelope)); } static public Message CreateMessage(MessageVersion version, string action, BodyWriter body) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body")); return new BodyWriterMessage(version, action, body); } static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter body) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body")); return new BodyWriterMessage(version, actionHeader, body); } static public Message CreateMessage(MessageVersion version, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, action, EmptyBodyWriter.Value); } static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, actionHeader, EmptyBodyWriter.Value); } static public Message CreateMessage(XmlReader envelopeReader, int maxSizeOfHeaders, MessageVersion version) { return CreateMessage(XmlDictionaryReader.CreateDictionaryReader(envelopeReader), maxSizeOfHeaders, version); } static public Message CreateMessage(XmlDictionaryReader envelopeReader, int maxSizeOfHeaders, MessageVersion version) { if (envelopeReader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("envelopeReader")); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); Message message = new StreamedMessage(envelopeReader, maxSizeOfHeaders, version); return message; } static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (faultCode == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode")); if (reason == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason")); return CreateMessage(version, MessageFault.CreateFault(faultCode, reason), action); } static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, object detail, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (faultCode == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode")); if (reason == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason")); return CreateMessage(version, MessageFault.CreateFault(faultCode, new FaultReason(reason), detail), action); } static public Message CreateMessage(MessageVersion version, MessageFault fault, string action) { if (fault == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("fault")); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, action, new FaultBodyWriter(fault, version.Envelope)); } internal Exception CreateMessageDisposedException() { return new ObjectDisposedException("", SR.MessageClosed); } void IDisposable.Dispose() { Close(); } public T GetBody<T>() { XmlDictionaryReader reader = GetReaderAtBodyContents(); // This call will change the message state to Read. return OnGetBody<T>(reader); } protected virtual T OnGetBody<T>(XmlDictionaryReader reader) { return this.GetBodyCore<T>(reader, DataContractSerializerDefaults.CreateSerializer(typeof(T), int.MaxValue/*maxItems*/)); } public T GetBody<T>(XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return this.GetBodyCore<T>(GetReaderAtBodyContents(), serializer); } private T GetBodyCore<T>(XmlDictionaryReader reader, XmlObjectSerializer serializer) { T value; using (reader) { value = (T)serializer.ReadObject(reader); this.ReadFromBodyContentsToEnd(reader); } return value; } internal virtual XmlDictionaryReader GetReaderAtHeader() { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); WriteStartEnvelope(writer); MessageHeaders headers = this.Headers; for (int i = 0; i < headers.Count; i++) headers.WriteHeader(i, writer); writer.WriteEndElement(); writer.WriteEndElement(); buffer.CloseSection(); buffer.Close(); XmlDictionaryReader reader = buffer.GetReader(0); reader.ReadStartElement(); reader.MoveToStartElement(); return reader; } public XmlDictionaryReader GetReaderAtBodyContents() { EnsureReadMessageState(); if (IsEmpty) throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageIsEmpty), this); return OnGetReaderAtBodyContents(); } internal void EnsureReadMessageState() { switch (_state) { case MessageState.Created: _state = MessageState.Read; break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } } internal void InitializeReply(Message request) { UniqueId requestMessageID = request.Headers.MessageId; if (requestMessageID == null) throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.RequestMessageDoesNotHaveAMessageID), request); Headers.RelatesTo = requestMessageID; } static internal bool IsFaultStartElement(XmlDictionaryReader reader, EnvelopeVersion version) { return reader.IsStartElement(XD.MessageDictionary.Fault, version.DictionaryNamespace); } protected virtual void OnBodyToString(XmlDictionaryWriter writer) { writer.WriteString(SR.MessageBodyIsUnknown); } protected virtual MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max); } internal MessageBuffer OnCreateBufferedCopy(int maxBufferSize, XmlDictionaryReaderQuotas quotas) { XmlBuffer msgBuffer = new XmlBuffer(maxBufferSize); XmlDictionaryWriter writer = msgBuffer.OpenSection(quotas); OnWriteMessage(writer); msgBuffer.CloseSection(); msgBuffer.Close(); return new DefaultMessageBuffer(this, msgBuffer); } protected virtual void OnClose() { } protected virtual XmlDictionaryReader OnGetReaderAtBodyContents() { XmlBuffer bodyBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = bodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); if (this.Version.Envelope != EnvelopeVersion.None) { OnWriteStartEnvelope(writer); OnWriteStartBody(writer); } OnWriteBodyContents(writer); if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } bodyBuffer.CloseSection(); bodyBuffer.Close(); XmlDictionaryReader reader = bodyBuffer.GetReader(0); if (this.Version.Envelope != EnvelopeVersion.None) { reader.ReadStartElement(); reader.ReadStartElement(); } reader.MoveToContent(); return reader; } protected virtual void OnWriteStartBody(XmlDictionaryWriter writer) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Body, Version.Envelope.DictionaryNamespace); } public void WriteBodyContents(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); OnWriteBodyContents(writer); } public Task WriteBodyContentsAsync(XmlDictionaryWriter writer) { this.WriteBodyContents(writer); return TaskHelpers.CompletedTask(); } public IAsyncResult BeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { EnsureWriteMessageState(writer); return this.OnBeginWriteBodyContents(writer, callback, state); } public void EndWriteBodyContents(IAsyncResult result) { this.OnEndWriteBodyContents(result); } protected abstract void OnWriteBodyContents(XmlDictionaryWriter writer); protected virtual Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { this.OnWriteBodyContents(writer); return TaskHelpers.CompletedTask(); } protected virtual IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return OnWriteBodyContentsAsync(writer).ToApm(callback, state); } protected virtual void OnEndWriteBodyContents(IAsyncResult result) { result.ToApmEnd(); } public void WriteStartEnvelope(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); OnWriteStartEnvelope(writer); } protected virtual void OnWriteStartEnvelope(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; if (envelopeVersion != EnvelopeVersion.None) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Envelope, envelopeVersion.DictionaryNamespace); WriteSharedHeaderPrefixes(writer); } } protected virtual void OnWriteStartHeaders(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; if (envelopeVersion != EnvelopeVersion.None) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Header, envelopeVersion.DictionaryNamespace); } } public override string ToString() { if (IsDisposed) { return base.ToString(); } XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlWriter textWriter = XmlWriter.Create(stringWriter, settings)) { using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter)) { try { ToString(writer); writer.Flush(); return stringWriter.ToString(); } catch (XmlException e) { return SR.Format(SR.MessageBodyToStringError, e.GetType().ToString(), e.Message); } } } } } internal void ToString(XmlDictionaryWriter writer) { if (IsDisposed) { throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); } if (this.Version.Envelope != EnvelopeVersion.None) { WriteStartEnvelope(writer); WriteStartHeaders(writer); MessageHeaders headers = this.Headers; for (int i = 0; i < headers.Count; i++) { headers.WriteHeader(i, writer); } writer.WriteEndElement(); MessageDictionary messageDictionary = XD.MessageDictionary; WriteStartBody(writer); } BodyToString(writer); if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } } public string GetBodyAttribute(string localName, string ns) { if (localName == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("localName"), this); if (ns == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("ns"), this); switch (_state) { case MessageState.Created: break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } return OnGetBodyAttribute(localName, ns); } protected virtual string OnGetBodyAttribute(string localName, string ns) { return null; } internal void ReadFromBodyContentsToEnd(XmlDictionaryReader reader) { Message.ReadFromBodyContentsToEnd(reader, this.Version.Envelope); } private static void ReadFromBodyContentsToEnd(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion) { if (envelopeVersion != EnvelopeVersion.None) { reader.ReadEndElement(); // </Body> reader.ReadEndElement(); // </Envelope> } reader.MoveToContent(); } internal static bool ReadStartBody(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion, out bool isFault, out bool isEmpty) { if (reader.IsEmptyElement) { reader.Read(); isEmpty = true; isFault = false; reader.ReadEndElement(); return false; } else { reader.Read(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Element) { isFault = IsFaultStartElement(reader, envelopeVersion); isEmpty = false; } else if (reader.NodeType == XmlNodeType.EndElement) { isEmpty = true; isFault = false; Message.ReadFromBodyContentsToEnd(reader, envelopeVersion); return false; } else { isEmpty = false; isFault = false; } return true; } } public void WriteBody(XmlWriter writer) { WriteBody(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteBody(XmlDictionaryWriter writer) { WriteStartBody(writer); WriteBodyContents(writer); writer.WriteEndElement(); } public void WriteStartBody(XmlWriter writer) { WriteStartBody(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteStartBody(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); OnWriteStartBody(writer); } internal void WriteStartHeaders(XmlDictionaryWriter writer) { OnWriteStartHeaders(writer); } public void WriteMessage(XmlWriter writer) { WriteMessage(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteMessage(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); OnWriteMessage(writer); } public virtual Task WriteMessageAsync(XmlWriter writer) { this.WriteMessage(writer); return TaskHelpers.CompletedTask(); } public virtual async Task WriteMessageAsync(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); await this.OnWriteMessageAsync(writer); } public virtual async Task OnWriteMessageAsync(XmlDictionaryWriter writer) { this.WriteMessagePreamble(writer); // We should call OnWriteBodyContentsAsync instead of WriteBodyContentsAsync here, // otherwise EnsureWriteMessageState would get called twice. Also see OnWriteMessage() // for the example. await this.OnWriteBodyContentsAsync(writer); this.WriteMessagePostamble(writer); } private void EnsureWriteMessageState(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); switch (_state) { case MessageState.Created: _state = MessageState.Written; break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } } // WriteMessageAsync public IAsyncResult BeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { EnsureWriteMessageState(writer); return OnBeginWriteMessage(writer, callback, state); } public void EndWriteMessage(IAsyncResult result) { OnEndWriteMessage(result); } // OnWriteMessageAsync protected virtual void OnWriteMessage(XmlDictionaryWriter writer) { WriteMessagePreamble(writer); OnWriteBodyContents(writer); WriteMessagePostamble(writer); } internal void WriteMessagePreamble(XmlDictionaryWriter writer) { if (this.Version.Envelope != EnvelopeVersion.None) { OnWriteStartEnvelope(writer); MessageHeaders headers = this.Headers; int headersCount = headers.Count; if (headersCount > 0) { OnWriteStartHeaders(writer); for (int i = 0; i < headersCount; i++) { headers.WriteHeader(i, writer); } writer.WriteEndElement(); } OnWriteStartBody(writer); } } internal void WriteMessagePostamble(XmlDictionaryWriter writer) { if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } } protected virtual IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected virtual void OnEndWriteMessage(IAsyncResult result) { OnWriteMessageAsyncResult.End(result); } private void WriteSharedHeaderPrefixes(XmlDictionaryWriter writer) { MessageHeaders headers = Headers; int count = headers.Count; int prefixesWritten = 0; for (int i = 0; i < count; i++) { if (this.Version.Addressing == AddressingVersion.None && headers[i].Namespace == AddressingVersion.None.Namespace) { continue; } IMessageHeaderWithSharedNamespace headerWithSharedNamespace = headers[i] as IMessageHeaderWithSharedNamespace; if (headerWithSharedNamespace != null) { XmlDictionaryString prefix = headerWithSharedNamespace.SharedPrefix; string prefixString = prefix.Value; if (!((prefixString.Length == 1))) { Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixString.Length == 1) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix."); throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this); } int prefixIndex = prefixString[0] - 'a'; if (!((prefixIndex >= 0 && prefixIndex < 26))) { Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixIndex >= 0 && prefixIndex < 26) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix."); throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this); } int prefixBit = 1 << prefixIndex; if ((prefixesWritten & prefixBit) == 0) { writer.WriteXmlnsAttribute(prefixString, headerWithSharedNamespace.SharedNamespace); prefixesWritten |= prefixBit; } } } } private class OnWriteMessageAsyncResult : ScheduleActionItemAsyncResult { private Message _message; private XmlDictionaryWriter _writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, Message message, AsyncCallback callback, object state) : base(callback, state) { Fx.Assert(message != null, "message should never be null"); _message = message; _writer = writer; Schedule(); } protected override void OnDoWork() { _message.OnWriteMessage(_writer); } } } internal class EmptyBodyWriter : BodyWriter { private static EmptyBodyWriter s_value; private EmptyBodyWriter() : base(true) { } public static EmptyBodyWriter Value { get { if (s_value == null) s_value = new EmptyBodyWriter(); return s_value; } } internal override bool IsEmpty { get { return true; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { } } internal class FaultBodyWriter : BodyWriter { private MessageFault _fault; private EnvelopeVersion _version; public FaultBodyWriter(MessageFault fault, EnvelopeVersion version) : base(true) { _fault = fault; _version = version; } internal override bool IsFault { get { return true; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { _fault.WriteTo(writer, _version); } } internal class XmlObjectSerializerBodyWriter : BodyWriter { private object _body; private XmlObjectSerializer _serializer; public XmlObjectSerializerBodyWriter(object body, XmlObjectSerializer serializer) : base(true) { _body = body; _serializer = serializer; } private object ThisLock { get { return this; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { lock (ThisLock) { _serializer.WriteObject(writer, _body); } } } internal class XmlReaderBodyWriter : BodyWriter { private XmlDictionaryReader _reader; private bool _isFault; public XmlReaderBodyWriter(XmlDictionaryReader reader, EnvelopeVersion version) : base(false) { _reader = reader; if (reader.MoveToContent() != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidReaderPositionOnCreateMessage, "reader")); _isFault = Message.IsFaultStartElement(reader, version); } internal override bool IsFault { get { return _isFault; } } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { using (_reader) { XmlNodeType type = _reader.MoveToContent(); while (!_reader.EOF && type != XmlNodeType.EndElement) { if (type != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidReaderPositionOnCreateMessage, "reader")); writer.WriteNode(_reader, false); type = _reader.MoveToContent(); } } } } internal class BodyWriterMessage : Message { private MessageProperties _properties; private MessageHeaders _headers; private BodyWriter _bodyWriter; private BodyWriterMessage(BodyWriter bodyWriter) { _bodyWriter = bodyWriter; } public BodyWriterMessage(MessageVersion version, string action, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(version); _headers.Action = action; } public BodyWriterMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(version); _headers.SetActionHeader(actionHeader); } public BodyWriterMessage(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(headers); _properties = new MessageProperties(properties); } public override bool IsFault { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _bodyWriter.IsFault; } } public override bool IsEmpty { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _bodyWriter.IsEmpty; } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } public override MessageProperties Properties { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); if (_properties == null) _properties = new MessageProperties(); return _properties; } } public override MessageVersion Version { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers.MessageVersion; } } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BodyWriter bufferedBodyWriter; if (_bodyWriter.IsBuffered) { bufferedBodyWriter = _bodyWriter; } else { bufferedBodyWriter = _bodyWriter.CreateBufferedCopy(maxBufferSize); } KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count]; ((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0); return new BodyWriterMessageBuffer(_headers, properties, bufferedBodyWriter); } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { if (_properties != null) _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); _bodyWriter = null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { _bodyWriter.WriteBodyContents(writer); } protected override Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { return _bodyWriter.WriteBodyContentsAsync(writer); } protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return null; //WriteMessagePreamble(writer); //return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected override void OnEndWriteMessage(IAsyncResult result) { //OnWriteMessageAsyncResult.End(result); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return _bodyWriter.BeginWriteBodyContents(writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { _bodyWriter.EndWriteBodyContents(result); } protected override void OnBodyToString(XmlDictionaryWriter writer) { if (_bodyWriter.IsBuffered) { _bodyWriter.WriteBodyContents(writer); } else { writer.WriteString(SR.MessageBodyIsStream); } } protected internal BodyWriter BodyWriter { get { return _bodyWriter; } } private class OnWriteMessageAsyncResult : AsyncResult { private BodyWriterMessage _message; private XmlDictionaryWriter _writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, BodyWriterMessage message, AsyncCallback callback, object state) : base(callback, state) { _message = message; _writer = writer; if (HandleWriteBodyContents(null)) { this.Complete(true); } } private bool HandleWriteBodyContents(IAsyncResult result) { if (result == null) { result = _message.OnBeginWriteBodyContents(_writer, PrepareAsyncCompletion(HandleWriteBodyContents), this); if (!result.CompletedSynchronously) { return false; } } _message.OnEndWriteBodyContents(result); _message.WriteMessagePostamble(_writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteMessageAsyncResult>(result); } } } internal abstract class ReceivedMessage : Message { private bool _isFault; private bool _isEmpty; public override bool IsEmpty { get { return _isEmpty; } } public override bool IsFault { get { return _isFault; } } protected static bool HasHeaderElement(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion) { return reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { if (!_isEmpty) { using (XmlDictionaryReader bodyReader = OnGetReaderAtBodyContents()) { if (bodyReader.ReadState == ReadState.Error || bodyReader.ReadState == ReadState.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MessageBodyReaderInvalidReadState, bodyReader.ReadState.ToString()))); while (bodyReader.NodeType != XmlNodeType.EndElement && !bodyReader.EOF) { writer.WriteNode(bodyReader, false); } this.ReadFromBodyContentsToEnd(bodyReader); } } } protected bool ReadStartBody(XmlDictionaryReader reader) { return Message.ReadStartBody(reader, this.Version.Envelope, out _isFault, out _isEmpty); } protected static EnvelopeVersion ReadStartEnvelope(XmlDictionaryReader reader) { EnvelopeVersion envelopeVersion; if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message12Dictionary.Namespace)) envelopeVersion = EnvelopeVersion.Soap12; else if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message11Dictionary.Namespace)) envelopeVersion = EnvelopeVersion.Soap11; else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageVersionUnknown)); if (reader.IsEmptyElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageBodyMissing)); reader.Read(); return envelopeVersion; } protected static void VerifyStartBody(XmlDictionaryReader reader, EnvelopeVersion version) { if (!reader.IsStartElement(XD.MessageDictionary.Body, version.DictionaryNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageBodyMissing)); } } internal sealed class StreamedMessage : ReceivedMessage { private MessageHeaders _headers; private XmlAttributeHolder[] _envelopeAttributes; private XmlAttributeHolder[] _headerAttributes; private XmlAttributeHolder[] _bodyAttributes; private string _envelopePrefix; private string _headerPrefix; private string _bodyPrefix; private MessageProperties _properties; private XmlDictionaryReader _reader; private XmlDictionaryReaderQuotas _quotas; public StreamedMessage(XmlDictionaryReader reader, int maxSizeOfHeaders, MessageVersion desiredVersion) { _properties = new MessageProperties(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (desiredVersion.Envelope == EnvelopeVersion.None) { _reader = reader; _headerAttributes = XmlAttributeHolder.emptyArray; _headers = new MessageHeaders(desiredVersion); } else { _envelopeAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); _envelopePrefix = reader.Prefix; EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader); if (desiredVersion.Envelope != envelopeVersion) { Exception versionMismatchException = new ArgumentException(SR.Format(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader"); throw TraceUtility.ThrowHelperError( new CommunicationException(versionMismatchException.Message, versionMismatchException), this); } if (HasHeaderElement(reader, envelopeVersion)) { _headerPrefix = reader.Prefix; _headerAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); _headers = new MessageHeaders(desiredVersion, reader, _envelopeAttributes, _headerAttributes, ref maxSizeOfHeaders); } else { _headerAttributes = XmlAttributeHolder.emptyArray; _headers = new MessageHeaders(desiredVersion); } if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); _bodyPrefix = reader.Prefix; VerifyStartBody(reader, envelopeVersion); _bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); if (ReadStartBody(reader)) { _reader = reader; } else { _quotas = new XmlDictionaryReaderQuotas(); reader.Quotas.CopyTo(_quotas); reader.Dispose(); } } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } public override MessageVersion Version { get { return _headers.MessageVersion; } } public override MessageProperties Properties { get { return _properties; } } protected override void OnBodyToString(XmlDictionaryWriter writer) { writer.WriteString(SR.MessageBodyIsStream); } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { if (_reader != null) { _reader.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader reader = _reader; _reader = null; return reader; } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { if (_reader != null) return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); return OnCreateBufferedCopy(maxBufferSize, _quotas); } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { writer.WriteStartElement(_bodyPrefix, MessageStrings.Body, Version.Envelope.Namespace); XmlAttributeHolder.WriteAttributes(_bodyAttributes, writer); } protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(_envelopePrefix, MessageStrings.Envelope, envelopeVersion.Namespace); XmlAttributeHolder.WriteAttributes(_envelopeAttributes, writer); } protected override void OnWriteStartHeaders(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(_headerPrefix, MessageStrings.Header, envelopeVersion.Namespace); XmlAttributeHolder.WriteAttributes(_headerAttributes, writer); } protected override string OnGetBodyAttribute(string localName, string ns) { return XmlAttributeHolder.GetAttribute(_bodyAttributes, localName, ns); } } internal interface IBufferedMessageData { MessageEncoder MessageEncoder { get; } ArraySegment<byte> Buffer { get; } XmlDictionaryReaderQuotas Quotas { get; } void Close(); void EnableMultipleUsers(); XmlDictionaryReader GetMessageReader(); void Open(); void ReturnMessageState(RecycledMessageState messageState); RecycledMessageState TakeMessageState(); } internal sealed class BufferedMessage : ReceivedMessage { private MessageHeaders _headers; private MessageProperties _properties; private IBufferedMessageData _messageData; private RecycledMessageState _recycledMessageState; private XmlDictionaryReader _reader; private XmlAttributeHolder[] _bodyAttributes; public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState) : this(messageData, recycledMessageState, null, false) { } public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified) { bool throwing = true; try { _recycledMessageState = recycledMessageState; _messageData = messageData; _properties = recycledMessageState.TakeProperties(); if (_properties == null) _properties = new MessageProperties(); XmlDictionaryReader reader = messageData.GetMessageReader(); MessageVersion desiredVersion = messageData.MessageEncoder.MessageVersion; if (desiredVersion.Envelope == EnvelopeVersion.None) { _reader = reader; _headers = new MessageHeaders(desiredVersion); } else { EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader); if (desiredVersion.Envelope != envelopeVersion) { Exception versionMismatchException = new ArgumentException(SR.Format(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader"); throw TraceUtility.ThrowHelperError( new CommunicationException(versionMismatchException.Message, versionMismatchException), this); } if (HasHeaderElement(reader, envelopeVersion)) { _headers = recycledMessageState.TakeHeaders(); if (_headers == null) { _headers = new MessageHeaders(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified); } else { _headers.Init(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified); } } else { _headers = new MessageHeaders(desiredVersion); } VerifyStartBody(reader, envelopeVersion); int maxSizeOfAttributes = int.MaxValue; _bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfAttributes); if (maxSizeOfAttributes < int.MaxValue - 4096) _bodyAttributes = null; if (ReadStartBody(reader)) { _reader = reader; } else { reader.Dispose(); } } throwing = false; } finally { if (throwing && MessageLogger.LoggingEnabled) { MessageLogger.LogMessage(messageData.Buffer, MessageLoggingSource.Malformed); } } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } internal IBufferedMessageData MessageData { get { return _messageData; } } public override MessageProperties Properties { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _properties; } } internal override RecycledMessageState RecycledMessageState { get { return _recycledMessageState; } } public override MessageVersion Version { get { return _headers.MessageVersion; } } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader reader = _reader; _reader = null; return reader; } internal override XmlDictionaryReader GetReaderAtHeader() { if (!_headers.ContainsOnlyBufferedMessageHeaders) return base.GetReaderAtHeader(); XmlDictionaryReader reader = _messageData.GetMessageReader(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); reader.Read(); if (HasHeaderElement(reader, _headers.MessageVersion.Envelope)) return reader; return base.GetReaderAtHeader(); } public XmlDictionaryReader GetBufferedReaderAtBody() { XmlDictionaryReader reader = _messageData.GetMessageReader(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (this.Version.Envelope != EnvelopeVersion.None) { reader.Read(); if (HasHeaderElement(reader, _headers.MessageVersion.Envelope)) reader.Skip(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); } return reader; } public XmlDictionaryReader GetMessageReader() { return _messageData.GetMessageReader(); } protected override void OnBodyToString(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { if (this.Version == MessageVersion.None) { writer.WriteNode(reader, false); } else { if (!reader.IsEmptyElement) { reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) writer.WriteNode(reader, false); } } } } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { if (_reader != null) { _reader.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { _recycledMessageState.ReturnHeaders(_headers); _recycledMessageState.ReturnProperties(_properties); _messageData.ReturnMessageState(_recycledMessageState); _recycledMessageState = null; _messageData.Close(); _messageData = null; } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); } protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetMessageReader()) { reader.MoveToContent(); EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(reader.Prefix, MessageStrings.Envelope, envelopeVersion.Namespace); writer.WriteAttributes(reader, false); } } protected override void OnWriteStartHeaders(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetMessageReader()) { reader.MoveToContent(); EnvelopeVersion envelopeVersion = Version.Envelope; reader.Read(); if (HasHeaderElement(reader, envelopeVersion)) { writer.WriteStartElement(reader.Prefix, MessageStrings.Header, envelopeVersion.Namespace); writer.WriteAttributes(reader, false); } else { writer.WriteStartElement(MessageStrings.Prefix, MessageStrings.Header, envelopeVersion.Namespace); } } } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { writer.WriteStartElement(reader.Prefix, MessageStrings.Body, Version.Envelope.Namespace); writer.WriteAttributes(reader, false); } } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { if (_headers.ContainsOnlyBufferedMessageHeaders) { KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count]; ((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0); _messageData.EnableMultipleUsers(); bool[] understoodHeaders = null; if (_headers.HasMustUnderstandBeenModified) { understoodHeaders = new bool[_headers.Count]; for (int i = 0; i < _headers.Count; i++) { understoodHeaders[i] = _headers.IsUnderstood(i); } } return new BufferedMessageBuffer(_messageData, properties, understoodHeaders, _headers.HasMustUnderstandBeenModified); } else { if (_reader != null) return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max); } } protected override string OnGetBodyAttribute(string localName, string ns) { if (_bodyAttributes != null) return XmlAttributeHolder.GetAttribute(_bodyAttributes, localName, ns); using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { return reader.GetAttribute(localName, ns); } } } internal struct XmlAttributeHolder { private string _prefix; private string _ns; private string _localName; private string _value; public static XmlAttributeHolder[] emptyArray = new XmlAttributeHolder[0]; public XmlAttributeHolder(string prefix, string localName, string ns, string value) { _prefix = prefix; _localName = localName; _ns = ns; _value = value; } public string Prefix { get { return _prefix; } } public string NamespaceUri { get { return _ns; } } public string LocalName { get { return _localName; } } public string Value { get { return _value; } } public void WriteTo(XmlWriter writer) { writer.WriteStartAttribute(_prefix, _localName, _ns); writer.WriteString(_value); writer.WriteEndAttribute(); } public static void WriteAttributes(XmlAttributeHolder[] attributes, XmlWriter writer) { for (int i = 0; i < attributes.Length; i++) attributes[i].WriteTo(writer); } public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader) { int maxSizeOfHeaders = int.MaxValue; return ReadAttributes(reader, ref maxSizeOfHeaders); } public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader, ref int maxSizeOfHeaders) { if (reader.AttributeCount == 0) return emptyArray; XmlAttributeHolder[] attributes = new XmlAttributeHolder[reader.AttributeCount]; reader.MoveToFirstAttribute(); for (int i = 0; i < attributes.Length; i++) { string ns = reader.NamespaceURI; string localName = reader.LocalName; string prefix = reader.Prefix; string value = string.Empty; while (reader.ReadAttributeValue()) { if (value.Length == 0) value = reader.Value; else value += reader.Value; } Deduct(prefix, ref maxSizeOfHeaders); Deduct(localName, ref maxSizeOfHeaders); Deduct(ns, ref maxSizeOfHeaders); Deduct(value, ref maxSizeOfHeaders); attributes[i] = new XmlAttributeHolder(prefix, localName, ns, value); reader.MoveToNextAttribute(); } reader.MoveToElement(); return attributes; } private static void Deduct(string s, ref int maxSizeOfHeaders) { int byteCount = s.Length * sizeof(char); if (byteCount > maxSizeOfHeaders) { string message = SR.XmlBufferQuotaExceeded; Exception inner = new QuotaExceededException(message); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner)); } maxSizeOfHeaders -= byteCount; } public static string GetAttribute(XmlAttributeHolder[] attributes, string localName, string ns) { for (int i = 0; i < attributes.Length; i++) if (attributes[i].LocalName == localName && attributes[i].NamespaceUri == ns) return attributes[i].Value; return null; } } internal class RecycledMessageState { private MessageHeaders _recycledHeaders; private MessageProperties _recycledProperties; private UriCache _uriCache; private HeaderInfoCache _headerInfoCache; public HeaderInfoCache HeaderInfoCache { get { if (_headerInfoCache == null) { _headerInfoCache = new HeaderInfoCache(); } return _headerInfoCache; } } public UriCache UriCache { get { if (_uriCache == null) _uriCache = new UriCache(); return _uriCache; } } public MessageProperties TakeProperties() { MessageProperties taken = _recycledProperties; _recycledProperties = null; return taken; } public void ReturnProperties(MessageProperties properties) { if (properties.CanRecycle) { properties.Recycle(); _recycledProperties = properties; } } public MessageHeaders TakeHeaders() { MessageHeaders taken = _recycledHeaders; _recycledHeaders = null; return taken; } public void ReturnHeaders(MessageHeaders headers) { if (headers.CanRecycle) { headers.Recycle(this.HeaderInfoCache); _recycledHeaders = headers; } } } internal class HeaderInfoCache { private const int maxHeaderInfos = 4; private HeaderInfo[] _headerInfos; private int _index; public MessageHeaderInfo TakeHeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam) { if (_headerInfos != null) { int i = _index; for (; ;) { HeaderInfo headerInfo = _headerInfos[i]; if (headerInfo != null) { if (headerInfo.Matches(reader, actor, mustUnderstand, relay, isRefParam)) { _headerInfos[i] = null; _index = (i + 1) % maxHeaderInfos; return headerInfo; } } i = (i + 1) % maxHeaderInfos; if (i == _index) { break; } } } return new HeaderInfo(reader, actor, mustUnderstand, relay, isRefParam); } public void ReturnHeaderInfo(MessageHeaderInfo headerInfo) { HeaderInfo headerInfoToReturn = headerInfo as HeaderInfo; if (headerInfoToReturn != null) { if (_headerInfos == null) { _headerInfos = new HeaderInfo[maxHeaderInfos]; } int i = _index; for (; ;) { if (_headerInfos[i] == null) { break; } i = (i + 1) % maxHeaderInfos; if (i == _index) { break; } } _headerInfos[i] = headerInfoToReturn; _index = (i + 1) % maxHeaderInfos; } } internal class HeaderInfo : MessageHeaderInfo { private string _name; private string _ns; private string _actor; private bool _isReferenceParameter; private bool _mustUnderstand; private bool _relay; public HeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isReferenceParameter) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; _isReferenceParameter = isReferenceParameter; _name = reader.LocalName; _ns = reader.NamespaceURI; } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool IsReferenceParameter { get { return _isReferenceParameter; } } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public bool Matches(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam) { return reader.IsStartElement(_name, _ns) && _actor == actor && _mustUnderstand == mustUnderstand && _relay == relay && _isReferenceParameter == isRefParam; } } } internal class UriCache { private const int MaxKeyLength = 128; private const int MaxEntries = 8; private Entry[] _entries; private int _count; public UriCache() { _entries = new Entry[MaxEntries]; } public Uri CreateUri(string uriString) { Uri uri = Get(uriString); if (uri == null) { uri = new Uri(uriString); Set(uriString, uri); } return uri; } private Uri Get(string key) { if (key.Length > MaxKeyLength) return null; for (int i = _count - 1; i >= 0; i--) if (_entries[i].Key == key) return _entries[i].Value; return null; } private void Set(string key, Uri value) { if (key.Length > MaxKeyLength) return; if (_count < _entries.Length) { _entries[_count++] = new Entry(key, value); } else { Array.Copy(_entries, 1, _entries, 0, _entries.Length - 1); _entries[_count - 1] = new Entry(key, value); } } internal struct Entry { private string _key; private Uri _value; public Entry(string key, Uri value) { _key = key; _value = value; } public string Key { get { return _key; } } public Uri Value { get { return _value; } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Fundamental; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Demonstration of how to define a universe /// as a combination of use the coarse fundamental data and fine fundamental data /// </summary> /// <meta name="tag" content="using data" /> /// <meta name="tag" content="universes" /> /// <meta name="tag" content="coarse universes" /> /// <meta name="tag" content="regression test" /> public class CoarseFineFundamentalRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private const int NumberOfSymbolsFine = 2; // initialize our changes to nothing private SecurityChanges _changes = SecurityChanges.None; public override void Initialize() { UniverseSettings.Resolution = Resolution.Daily; SetStartDate(2014, 03, 24); SetEndDate(2014, 04, 07); SetCash(50000); // this add universe method accepts two parameters: // - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol> // - fine selection function: accepts an IEnumerable<FineFundamental> and returns an IEnumerable<Symbol> AddUniverse(CoarseSelectionFunction, FineSelectionFunction); } // return a list of three fixed symbol objects public IEnumerable<Symbol> CoarseSelectionFunction(IEnumerable<CoarseFundamental> coarse) { if (Time.Date < new DateTime(2014, 4, 1)) { return new List<Symbol> { QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA), QuantConnect.Symbol.Create("AIG", SecurityType.Equity, Market.USA), QuantConnect.Symbol.Create("IBM", SecurityType.Equity, Market.USA) }; } return new List<Symbol> { QuantConnect.Symbol.Create("BAC", SecurityType.Equity, Market.USA), QuantConnect.Symbol.Create("GOOG", SecurityType.Equity, Market.USA), QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA) }; } // sort the data by market capitalization and take the top 'NumberOfSymbolsFine' public IEnumerable<Symbol> FineSelectionFunction(IEnumerable<FineFundamental> fine) { // sort descending by market capitalization var sortedByMarketCap = fine.OrderByDescending(x => x.MarketCap); // take the top entries from our sorted collection var topFine = sortedByMarketCap.Take(NumberOfSymbolsFine); // we need to return only the symbol objects return topFine.Select(x => x.Symbol); } //Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol. public void OnData(TradeBars data) { // if we have no changes, do nothing if (_changes == SecurityChanges.None) return; // liquidate removed securities foreach (var security in _changes.RemovedSecurities) { if (security.Invested) { Liquidate(security.Symbol); Debug("Liquidated Stock: " + security.Symbol.Value); } } // we want 50% allocation in each security in our universe foreach (var security in _changes.AddedSecurities) { if (security.Fundamentals.EarningRatios.EquityPerShareGrowth.OneYear > 0.25m) { SetHoldings(security.Symbol, 0.5m); Debug("Purchased Stock: " + security.Symbol.Value); } } _changes = SecurityChanges.None; } public override void OnData(Slice data) { // verify we don't receive data for inactive securities var inactiveSymbols = data.Keys .Where(sym => !UniverseManager.ActiveSecurities.ContainsKey(sym)) // on daily data we'll get the last data point and the delisting at the same time .Where(sym => !data.Delistings.ContainsKey(sym) || data.Delistings[sym].Type != DelistingType.Delisted) .ToList(); if (inactiveSymbols.Any()) { var symbols = string.Join(", ", inactiveSymbols); throw new Exception($"Received data for non-active security: {symbols}."); } } // this event fires whenever we have changes to our universe public override void OnSecuritiesChanged(SecurityChanges changes) { _changes = changes; if (changes.AddedSecurities.Count > 0) { Debug("Securities added: " + string.Join(",", changes.AddedSecurities.Select(x => x.Symbol.Value))); } if (changes.RemovedSecurities.Count > 0) { Debug("Securities removed: " + string.Join(",", changes.RemovedSecurities.Select(x => x.Symbol.Value))); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "2"}, {"Average Win", "1.16%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "32.505%"}, {"Drawdown", "1.400%"}, {"Expectancy", "0"}, {"Net Profit", "1.163%"}, {"Sharpe Ratio", "2.876"}, {"Probabilistic Sharpe Ratio", "64.984%"}, {"Loss Rate", "0%"}, {"Win Rate", "100%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.237"}, {"Beta", "-0.188"}, {"Annual Standard Deviation", "0.089"}, {"Annual Variance", "0.008"}, {"Information Ratio", "2.409"}, {"Tracking Error", "0.148"}, {"Treynor Ratio", "-1.358"}, {"Total Fees", "$2.00"}, {"Estimated Strategy Capacity", "$49000000.00"}, {"Lowest Capacity Asset", "IBM R735QTJ8XC9X"}, {"Fitness Score", "0.076"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "27.328"}, {"Return Over Maximum Drawdown", "24.002"}, {"Portfolio Turnover", "0.076"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "159887a90516df8ba8e8d35b9c30b227"} }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace VStorm.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Interfaces { public class UserInfo : IDataTransferable { public Vector3 CurrentLookAt; public Vector3 CurrentPosition; /// <summary> /// The region the user is currently active in /// NOTE: In a grid situation, the agent can be active in more than one region /// as they can be logged in more than once /// </summary> public UUID CurrentRegionID; public Vector3 HomeLookAt; public Vector3 HomePosition; /// <summary> /// The home region of this user /// </summary> public UUID HomeRegionID; /// <summary> /// Any other assorted into about this user /// </summary> public OSDMap Info = new OSDMap(); /// <summary> /// Whether this agent is currently online /// </summary> public bool IsOnline; /// <summary> /// The last login of the user /// </summary> public DateTime LastLogin; /// <summary> /// The last logout of the user /// </summary> public DateTime LastLogout; /// <summary> /// The user that this info is for /// </summary> public string UserID; public override OSDMap ToOSD() { OSDMap retVal = new OSDMap(); retVal["UserID"] = UserID; retVal["CurrentRegionID"] = CurrentRegionID; retVal["CurrentPosition"] = CurrentPosition; retVal["CurrentLookAt"] = CurrentLookAt; retVal["HomeRegionID"] = HomeRegionID; retVal["HomePosition"] = HomePosition; retVal["HomeLookAt"] = HomeLookAt; retVal["IsOnline"] = IsOnline; retVal["LastLogin"] = LastLogin; retVal["LastLogout"] = LastLogout; retVal["Info"] = Info; return retVal; } public override void FromOSD(OSDMap retVal) { UserID = retVal["UserID"].AsString(); CurrentRegionID = retVal["CurrentRegionID"].AsUUID(); CurrentPosition = retVal["CurrentPosition"].AsVector3(); CurrentLookAt = retVal["CurrentLookAt"].AsVector3(); HomeRegionID = retVal["HomeRegionID"].AsUUID(); HomePosition = retVal["HomePosition"].AsVector3(); HomeLookAt = retVal["HomeLookAt"].AsVector3(); IsOnline = retVal["IsOnline"].AsBoolean(); LastLogin = retVal["LastLogin"].AsDate(); LastLogout = retVal["LastLogout"].AsDate(); if (retVal["Info"].Type == OSDType.Map) Info = (OSDMap) retVal["Info"]; } public override Dictionary<string, object> ToKVP() { return Util.OSDToDictionary(ToOSD()); } public override void FromKVP(Dictionary<string, object> KVP) { FromOSD(Util.DictionaryToOSD(KVP)); } } public class AgentInfoHelpers { public static UUID LOGIN_STATUS_LOCKED = UUID.Parse("11111111-2222-3333-4444-555555555555"); } public interface IAgentInfoService { /// <summary> /// The local service (if one exists) /// </summary> IAgentInfoService InnerService { get; } /// <summary> /// Get the user infos for the given user /// </summary> /// <param name = "userID"></param> /// <param name = "regionID"></param> /// <returns></returns> UserInfo GetUserInfo(string userID); /// <summary> /// Get the user infos for the given users /// </summary> /// <param name = "userID"></param> /// <param name = "regionID"></param> /// <returns></returns> List<UserInfo> GetUserInfos(List<string> userIDs); /// <summary> /// Get the HTTP URLs for all root agents of the given users /// </summary> /// <param name = "requestor"></param> /// <param name = "userIDs"></param> /// <returns></returns> List<string> GetAgentsLocations(string requestor, List<string> userIDs); /// <summary> /// Set the home position of the given user /// </summary> /// <param name = "userID"></param> /// <param name = "homeID"></param> /// <param name = "homePosition"></param> /// <param name = "homeLookAt"></param> /// <returns></returns> bool SetHomePosition(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt); /// <summary> /// Set the last known position of the given user /// </summary> /// <param name = "userID"></param> /// <param name = "regionID"></param> /// <param name = "lastPosition"></param> /// <param name = "lastLookAt"></param> void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt); /// <summary> /// Log the agent in or out /// </summary> /// <param name = "userID"></param> /// <param name = "loggingIn">Whether the user is logging in or out</param> /// <param name = "fireLoggedInEvent">Fire the event to log a user in</param> /// <param name = "enteringRegion">The region the user is entering (if logging in)</param> void SetLoggedIn(string userID, bool loggingIn, bool fireLoggedInEvent, UUID enteringRegion); /// <summary> /// This is used in grid mode so that the sim cannot influence the login status /// </summary> /// <param name = "userID"></param> /// <param name = "locked">Whether to lock or unlock the user</param> void LockLoggedInStatus(string userID, bool locked); void Start(IConfigSource config, IRegistryCore registry); void FinishedStartup(); void Initialize(IConfigSource config, IRegistryCore registry); } public interface IAgentInfoConnector : IAuroraDataPlugin { bool Set(UserInfo info); void Update(string userID, Dictionary<string, object> values); void SetLastPosition(string userID, UUID regionID, Vector3 Position, Vector3 LookAt); void SetHomePosition(string userID, UUID regionID, Vector3 Position, Vector3 LookAt); UserInfo Get(string userID, bool checkOnlineStatus, out bool onlineStatusChanged); uint RecentlyOnline(uint secondsAgo, bool stillOnline); List<UserInfo> RecentlyOnline(uint secondsAgo, bool stillOnline, Dictionary<string, bool> sort, uint start, uint count); } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.RDS.Model { /// <summary> /// <para> Contains a list of available options for a DB Instance </para> <para> This data type is used as a response element in the /// DescribeOrderableDBInstanceOptions action. </para> /// </summary> public class OrderableDBInstanceOption { private string engine; private string engineVersion; private string dBInstanceClass; private string licenseModel; private List<AvailabilityZone> availabilityZones = new List<AvailabilityZone>(); private bool? multiAZCapable; private bool? readReplicaCapable; private bool? vpc; /// <summary> /// The engine type of the orderable DB Instance. /// /// </summary> public string Engine { get { return this.engine; } set { this.engine = value; } } /// <summary> /// Sets the Engine property /// </summary> /// <param name="engine">The value to set for the Engine property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithEngine(string engine) { this.engine = engine; return this; } // Check to see if Engine property is set internal bool IsSetEngine() { return this.engine != null; } /// <summary> /// The engine version of the orderable DB Instance. /// /// </summary> public string EngineVersion { get { return this.engineVersion; } set { this.engineVersion = value; } } /// <summary> /// Sets the EngineVersion property /// </summary> /// <param name="engineVersion">The value to set for the EngineVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithEngineVersion(string engineVersion) { this.engineVersion = engineVersion; return this; } // Check to see if EngineVersion property is set internal bool IsSetEngineVersion() { return this.engineVersion != null; } /// <summary> /// The DB Instance Class for the orderable DB Instance /// /// </summary> public string DBInstanceClass { get { return this.dBInstanceClass; } set { this.dBInstanceClass = value; } } /// <summary> /// Sets the DBInstanceClass property /// </summary> /// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithDBInstanceClass(string dBInstanceClass) { this.dBInstanceClass = dBInstanceClass; return this; } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this.dBInstanceClass != null; } /// <summary> /// The license model for the orderable DB Instance. /// /// </summary> public string LicenseModel { get { return this.licenseModel; } set { this.licenseModel = value; } } /// <summary> /// Sets the LicenseModel property /// </summary> /// <param name="licenseModel">The value to set for the LicenseModel property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithLicenseModel(string licenseModel) { this.licenseModel = licenseModel; return this; } // Check to see if LicenseModel property is set internal bool IsSetLicenseModel() { return this.licenseModel != null; } /// <summary> /// A list of availability zones for the orderable DB Instance. /// /// </summary> public List<AvailabilityZone> AvailabilityZones { get { return this.availabilityZones; } set { this.availabilityZones = value; } } /// <summary> /// Adds elements to the AvailabilityZones collection /// </summary> /// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithAvailabilityZones(params AvailabilityZone[] availabilityZones) { foreach (AvailabilityZone element in availabilityZones) { this.availabilityZones.Add(element); } return this; } /// <summary> /// Adds elements to the AvailabilityZones collection /// </summary> /// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithAvailabilityZones(IEnumerable<AvailabilityZone> availabilityZones) { foreach (AvailabilityZone element in availabilityZones) { this.availabilityZones.Add(element); } return this; } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this.availabilityZones.Count > 0; } /// <summary> /// Indicates whether this orderable DB Instance is multi-AZ capable. /// /// </summary> public bool MultiAZCapable { get { return this.multiAZCapable ?? default(bool); } set { this.multiAZCapable = value; } } /// <summary> /// Sets the MultiAZCapable property /// </summary> /// <param name="multiAZCapable">The value to set for the MultiAZCapable property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithMultiAZCapable(bool multiAZCapable) { this.multiAZCapable = multiAZCapable; return this; } // Check to see if MultiAZCapable property is set internal bool IsSetMultiAZCapable() { return this.multiAZCapable.HasValue; } /// <summary> /// Indicates whether this orderable DB Instance can have a read replica. /// /// </summary> public bool ReadReplicaCapable { get { return this.readReplicaCapable ?? default(bool); } set { this.readReplicaCapable = value; } } /// <summary> /// Sets the ReadReplicaCapable property /// </summary> /// <param name="readReplicaCapable">The value to set for the ReadReplicaCapable property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithReadReplicaCapable(bool readReplicaCapable) { this.readReplicaCapable = readReplicaCapable; return this; } // Check to see if ReadReplicaCapable property is set internal bool IsSetReadReplicaCapable() { return this.readReplicaCapable.HasValue; } /// <summary> /// Indicates whether this is a VPC orderable DB Instance. /// /// </summary> public bool Vpc { get { return this.vpc ?? default(bool); } set { this.vpc = value; } } /// <summary> /// Sets the Vpc property /// </summary> /// <param name="vpc">The value to set for the Vpc property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OrderableDBInstanceOption WithVpc(bool vpc) { this.vpc = vpc; return this; } // Check to see if Vpc property is set internal bool IsSetVpc() { return this.vpc.HasValue; } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 452570 $ * $Date: 2006-10-03 11:00:01 -0600 (Tue, 03 Oct 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * 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.Collections; using System.Collections.Specialized; using System.IO; using System.Threading; using IBatisNet.Common.Logging; namespace IBatisNet.Common.Utilities { /// <summary> /// Represents the method that handles calls from Configure. /// </summary> /// <remarks> /// obj is a null object in a DaoManager context. /// obj is the reconfigured sqlMap in a SqlMap context. /// </remarks> public delegate void ConfigureHandler(object obj); /// <summary> /// /// </summary> public struct StateConfig { /// <summary> /// Master Config File name. /// </summary> public string FileName; /// <summary> /// Delegate called when a file is changed, use it to rebuild. /// </summary> public ConfigureHandler ConfigureHandler; } /// <summary> /// Class used to watch config files. /// </summary> /// <remarks> /// Uses the <see cref="FileSystemWatcher"/> to monitor /// changes to a specified file. Because multiple change notifications /// may be raised when the file is modified, a timer is used to /// compress the notifications into a single event. The timer /// waits for the specified time before delivering /// the event notification. If any further <see cref="FileSystemWatcher"/> /// change notifications arrive while the timer is waiting it /// is reset and waits again for the specified time to /// elapse. /// </remarks> public sealed class ConfigWatcherHandler { #region Fields private static readonly ILog _logger = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); /// <summary> /// The timer used to compress the notification events. /// </summary> private Timer _timer = null; /// <summary> /// A list of configuration files to watch. /// </summary> private static ArrayList _filesToWatch = new ArrayList(); /// <summary> /// The list of FileSystemWatcher. /// </summary> private static ArrayList _filesWatcher = new ArrayList(); /// <summary> /// The default amount of time to wait after receiving notification /// before reloading the config file. /// </summary> private const int TIMEOUT_MILLISECONDS = 500; #endregion #region Constructor (s) / Destructor /// <summary> ///- /// </summary> /// <param name="state"> /// Represent the call context of the SqlMap or DaoManager ConfigureAndWatch method call. /// </param> /// <param name="onWhatchedFileChange"></param> public ConfigWatcherHandler(TimerCallback onWhatchedFileChange, StateConfig state) { for(int index = 0; index < _filesToWatch.Count; index++) { FileInfo configFile = (FileInfo)_filesToWatch[index]; AttachWatcher(configFile); // Create the timer that will be used to deliver events. Set as disabled // callback : A TimerCallback delegate representing a method to be executed. // state : An object containing information to be used by the callback method, or a null reference // dueTime : The amount of time to delay before callback is invoked, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately // period : The time interval between invocations of callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling _timer = new Timer(onWhatchedFileChange, state, Timeout.Infinite, Timeout.Infinite); } } #endregion #region Methods private void AttachWatcher(FileInfo configFile) { // Create a new FileSystemWatcher and set its properties. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = configFile.DirectoryName; watcher.Filter = configFile.Name; // Set the notification filters watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs watcher.Changed += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged); watcher.Created += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged); watcher.Deleted += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged); watcher.Renamed += new RenamedEventHandler(ConfigWatcherHandler_OnRenamed); // Begin watching. watcher.EnableRaisingEvents = true; _filesWatcher.Add(watcher); } /// <summary> /// Add a file to be monitored. /// </summary> /// <param name="configFile"></param> public static void AddFileToWatch(FileInfo configFile) { if (_logger.IsDebugEnabled) { // TODO: remove Path.GetFileName? _logger.Debug("Adding file [" + Path.GetFileName(configFile.FullName) + "] to list of watched files."); } _filesToWatch.Add( configFile ); } /// <summary> /// Reset the list of files being monitored. /// </summary> public static void ClearFilesMonitored() { _filesToWatch.Clear(); // Kill all FileSystemWatcher for(int index = 0; index < _filesWatcher.Count; index++) { FileSystemWatcher fileWatcher = (FileSystemWatcher)_filesWatcher[index]; fileWatcher.EnableRaisingEvents = false; fileWatcher.Dispose(); } } /// <summary> /// Event handler used by <see cref="ConfigWatcherHandler"/>. /// </summary> /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param> /// <param name="e">The argument indicates the file that caused the event to be fired.</param> /// <remarks> /// This handler reloads the configuration from the file when the event is fired. /// </remarks> private void ConfigWatcherHandler_OnChanged(object source, FileSystemEventArgs e) { if (_logger.IsDebugEnabled) { _logger.Debug("ConfigWatcherHandler : "+e.ChangeType+" [" + e.Name + "]"); } // timer will fire only once _timer.Change(TIMEOUT_MILLISECONDS, Timeout.Infinite); } /// <summary> /// Event handler used by <see cref="ConfigWatcherHandler"/>. /// </summary> /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param> /// <param name="e">The argument indicates the file that caused the event to be fired.</param> /// <remarks> /// This handler reloads the configuration from the file when the event is fired. /// </remarks> private void ConfigWatcherHandler_OnRenamed(object source, RenamedEventArgs e) { if (_logger.IsDebugEnabled) { _logger.Debug("ConfigWatcherHandler : " + e.ChangeType + " [" + e.OldName + "/" +e.Name +"]"); } // timer will fire only once _timer.Change(TIMEOUT_MILLISECONDS, Timeout.Infinite); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using dotMath.Core; using dotMath.Exceptions; namespace dotMath { /// <summary> /// EquationCompiler is the class that takes the parsed tokens and turns them /// into a network of pre-compiled objects that perform the designated functions. /// </summary> public class EquationCompiler { private string _equation; private CValue _function; private Token _currentToken; private Token _nextToken; private IEnumerator _tokenEnumerator; private Dictionary<string, CVariable> _variables = new Dictionary<string, CVariable>(); private Dictionary<string, COperator> _operators = new Dictionary<string, COperator>(); private Dictionary<string, CFunction> _functions = new Dictionary<string, CFunction>(); /// <summary> /// Creates the compiler object and sets the current function to the string passed /// </summary> /// <param name="equation"></param> public EquationCompiler(string equation = null) { SetFunction(equation); InitOperators(); InitFunctions(); } /// <summary> /// Gets the string variable names parsed by compiling the function. /// </summary> /// <returns>Read-only collection of variable names</returns> public ICollection<string> GetVariableNames() { if (_function == null) Compile(); return _variables.Keys; } /// <summary> /// Sets the object mapped to the string variable name to the double value passed. /// </summary> /// <param name="name">Variable Name</param> /// <param name="value">New Value for variable</param> public void SetVariable(string name, double value) { CVariable variable = GetVariableByName(name); variable.SetValue(value); } /// <summary> /// Sets the current function to a passed string. /// </summary> /// <param name="function">string representing the function being used</param> public void SetFunction(string function) { _currentToken = null; _nextToken = null; _equation = function; _function = null; } /// <summary> /// Kicks off the process to tokenize the function and compile the resulting token set into a runnable form. /// </summary> public void Compile() { var parser = new Parser(_equation); _tokenEnumerator = parser.GetTokenEnumerator(); NextToken(); _function = Or(); } /// <summary> /// Evaluates the function and returns the result. /// </summary> /// <returns>double value evaluation of the function in its current state</returns> public double Calculate() { if (_function == null) Compile(); if (_nextToken != null) throw new InvalidEquationException("Invalid token found in equation: " + _currentToken.ToString()); return _function.GetValue(); } /// <summary> /// Adds a custom function with the given name. /// </summary> /// <param name="name">Name of function.</param> /// <param name="function">Function delegate.</param> public void AddFunction(string name, Func<double, double> function) { _functions.Add(name, new CFunction(function)); } /// <summary> /// Adds a custom function with the given name. /// </summary> /// <param name="name">Name of function.</param> /// <param name="function">Function delegate.</param> public void AddFunction(string name, Func<double, double, double> function) { _functions.Add(name, new CFunction(function)); } /// <summary> /// Adds a custom function with the given name. /// </summary> /// <param name="name">Name of function.</param> /// <param name="function">Function delegate.</param> public void AddFunction(string name, Func<bool, double, double, double> function) { _functions.Add(name, new CFunction(function)); } /// <summary> /// Adds a custom function with the given name. /// </summary> /// <param name="name">Name of function.</param> /// <param name="function">Function delegate.</param> public void AddFunction(string name, Func<double, double, double, double> function) { _functions.Add(name, new CFunction(function)); } #region Operations and Compiling Functions /// <summary> /// Evaluates parenthesis in the equation and insures they are handled properly according to the Order of Operations. /// Because this is last in the chain, it also evaluates Variable and Function names. /// </summary> /// <returns>CValue object that holds an operation.</returns> private CValue Paren() { bool isFunction = false; CValue value = null; if (_currentToken == null) throw new InvalidEquationException("Unexpected end of equation (are you missing an operator argument?)."); if (_currentToken.ToString() == "(") { NextToken(); value = Or(); if (string.Equals(_currentToken, ",")) return value; } else { switch (_currentToken.TokenType) { case TokenType.Number: value = new CNumber(_currentToken.ToString()); break; case TokenType.Letter: if (string.Equals(_nextToken, "(")) { if (!_functions.ContainsKey(_currentToken.ToString())) throw new InvalidFunctionException(_currentToken.ToString()); CFunction function = _functions[_currentToken.ToString()]; var parameters = new List<CValue>(); do { NextToken(); try { value = Paren(); } catch (InvalidEquationException) { throw new ArgumentCountException(parameters.Count); } parameters.Add(value); } while (string.Equals(_currentToken, ",")); isFunction = true; value = function.SetParameters(parameters); if (string.Equals(_currentToken, ")") && parameters.Count > 1) NextToken(); } else value = GetVariableByName(_currentToken.ToString()); break; } } if (!isFunction) NextToken(); return value; } /// <summary> /// Detects the existence of sign operators before a number or variable. /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue Sign() { bool isNegative = false; Token token = null; if (_currentToken == "+" || _currentToken == "-") { token = _currentToken; isNegative = (_currentToken == "-"); NextToken(); } CValue function = Paren(); if (isNegative) function = new CSignNeg(function); return function; } /// <summary> /// Detects the operation to raise one number to the power of another (a^2). /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue Power() { CValue value = Sign(); while (_currentToken == "^") { Token token = _currentToken; NextToken(); CValue nextValue = Sign(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the modulo operator (%) /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue Modulo() { CValue value = Power(); while (_currentToken == "%") { Token token = _currentToken; NextToken(); CValue nextValue = Power(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the operation to perform multiplication or division. /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue MultDiv() { CValue value = Modulo(); while (_currentToken == "*" || _currentToken == "/") { Token token = _currentToken; NextToken(); CValue nextValue = Modulo(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the operation to perform addition or substraction. /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue AddSub() { CValue value = MultDiv(); while (_currentToken == "+" || _currentToken == "-") { Token token = _currentToken; NextToken(); CValue nextValue = MultDiv(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the operation to perform a relational operator (>, <, <=, etc.). /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue Relational() { CValue value = AddSub(); while (_currentToken == "==" || _currentToken == "<" || _currentToken == ">" || _currentToken == "<=" || _currentToken == ">=" || _currentToken == "!=" || _currentToken == "<>") { Token token = _currentToken; NextToken(); CValue nextValue = AddSub(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the operation to perform a logical AND. /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue And() { CValue value = Relational(); while (_currentToken == "&&") { Token token = _currentToken; NextToken(); CValue nextValue = Relational(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Detects the operation to perform a logical OR. /// </summary> /// <returns>CValue object representing an operation.</returns> private CValue Or() { CValue value = And(); while (_currentToken == "||") { Token token = _currentToken; NextToken(); CValue nextValue = Or(); value = GetOperator(token, value, nextValue); } return value; } /// <summary> /// Reads the passed operator, identifies the associated implementation object /// and requests an operation object to be used in evaluating the equation. /// </summary> /// <param name="operatorToken">Token object representing the operator in question.</param> /// <param name="value1">The first value object to be operated on.</param> /// <param name="value2">The second value object to be operated on.</param> /// <returns>CValue object representing an operation.</returns> private CValue GetOperator(Token operatorToken, CValue value1, CValue value2) { if (_operators.ContainsKey(operatorToken.ToString())) { COperator op = _operators[operatorToken.ToString()]; return op.SetParameters(value1, value2); } throw new InvalidEquationException("Invalid operator found in equation: " + operatorToken.ToString()); } #endregion #region Helper Functions /// <summary> /// Creates all operation functions recognized by the compiler. /// </summary> private void InitOperators() { _operators.Add("+", new COperator((x, y) => x + y)); _operators.Add("-", new COperator((x, y) => x - y)); _operators.Add("*", new COperator((x, y) => x * y)); _operators.Add("/", new COperator((x, y) => x / y)); _operators.Add("%", new COperator((x, y) => x % y)); _operators.Add("^", new COperator((x, y) => Math.Pow(x, y))); _operators.Add(">", new COperator((x, y) => { if (x > y) return 1; else return 0; })); _operators.Add(">=", new COperator((x, y) => { if (x >= y) return 1; else return 0; })); _operators.Add("<", new COperator((x, y) => { if (x < y) return 1; else return 0; })); _operators.Add("<=", new COperator((x, y) => { if (x <= y) return 1; else return 0; })); _operators.Add("==", new COperator((x, y) => { if (x == y) return 1; else return 0; })); _operators.Add("<>", new COperator((x, y) => { if (x != y) return 1; else return 0; })); _operators.Add("!=", new COperator((x, y) => { if (x != y) return 1; else return 0; })); _operators.Add("&&", new COperator((x, y) => { if (Convert.ToBoolean(x) && Convert.ToBoolean(y)) return 1; else return 0; })); _operators.Add("||", new COperator((x, y) => { if (Convert.ToBoolean(x) || Convert.ToBoolean(y)) return 1; else return 0; })); } /// <summary> /// Creates all functions recognized by the compiler. /// </summary> private void InitFunctions() { this.AddFunction("abs", x => Math.Abs(x)); this.AddFunction("acos", x => Math.Acos(x)); this.AddFunction("asin", x => Math.Asin(x)); this.AddFunction("atan", x => Math.Atan(x)); this.AddFunction("ceiling", x => Math.Ceiling(x)); this.AddFunction("cos", x => Math.Cos(x)); this.AddFunction("cosh", x => Math.Cosh(x)); this.AddFunction("exp", x => Math.Exp(x)); this.AddFunction("floor", x => Math.Floor(x)); this.AddFunction("log", x => Math.Log(x)); this.AddFunction("log10", x => Math.Log10(x)); this.AddFunction("root", (x, y) => Math.Pow(x, 1.0 / y)); this.AddFunction("round", x => Math.Round(x)); this.AddFunction("sign", x => Math.Sign(x)); this.AddFunction("sin", x => Math.Sin(x)); this.AddFunction("sinh", x => Math.Sinh(x)); this.AddFunction("sqrt", x => Math.Sqrt(x)); this.AddFunction("tan", x => Math.Tan(x)); this.AddFunction("tanh", x => Math.Tanh(x)); this.AddFunction("max", (x, y) => Math.Max(x, y)); this.AddFunction("min", (x, y) => Math.Min(x, y)); this.AddFunction("if", (x, y, z) => { if (x) return y; else return z; }); } /// <summary> /// Manipulates the current Token position forward in the chain of tokens discovered by the parser. /// </summary> private void NextToken() { if (_currentToken == null) { if (!_tokenEnumerator.MoveNext()) throw new InvalidEquationException("Unexpected end of equation."); _nextToken = (Token) _tokenEnumerator.Current; } _currentToken = _nextToken; if (_tokenEnumerator.MoveNext()) _nextToken = (Token) _tokenEnumerator.Current; else _nextToken = null; } /// <summary> /// Returns the variable associated with the provided name string. /// </summary> /// <param name="name">string variable name</param> /// <returns>CVariable object mapped to the passed variable name</returns> private CVariable GetVariableByName(string name) { if (_variables.ContainsKey(name)) return _variables[name]; var variable = new CVariable(); _variables.Add(name, variable); return variable; } #endregion } }
// <copyright file="FirefoxOptions.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Class to manage options specific to <see cref="FirefoxDriver"/> /// </summary> /// <remarks> /// Used with the marionette executable wires.exe. /// </remarks> /// <example> /// <code> /// FirefoxOptions options = new FirefoxOptions(); /// </code> /// <para></para> /// <para>For use with FirefoxDriver:</para> /// <para></para> /// <code> /// FirefoxDriver driver = new FirefoxDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class FirefoxOptions : DriverOptions { private const string BrowserNameValue = "firefox"; private const string IsMarionetteCapability = "marionette"; private const string FirefoxLegacyProfileCapability = "firefox_profile"; private const string FirefoxLegacyBinaryCapability = "firefox_binary"; private const string FirefoxProfileCapability = "profile"; private const string FirefoxBinaryCapability = "binary"; private const string FirefoxArgumentsCapability = "args"; private const string FirefoxLogCapability = "log"; private const string FirefoxPrefsCapability = "prefs"; private const string FirefoxOptionsCapability = "moz:firefoxOptions"; private string browserBinaryLocation; private FirefoxDriverLogLevel logLevel = FirefoxDriverLogLevel.Default; private FirefoxProfile profile; private List<string> firefoxArguments = new List<string>(); private Dictionary<string, object> profilePreferences = new Dictionary<string, object>(); private Dictionary<string, object> additionalFirefoxOptions = new Dictionary<string, object>(); /// <summary> /// Initializes a new instance of the <see cref="FirefoxOptions"/> class. /// </summary> public FirefoxOptions() : base() { this.BrowserName = BrowserNameValue; this.AddKnownCapabilityName(FirefoxOptions.FirefoxOptionsCapability, "current FirefoxOptions class instance"); this.AddKnownCapabilityName(FirefoxOptions.IsMarionetteCapability, "UseLegacyImplementation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxBinaryCapability, "BrowserExecutableLocation property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxArgumentsCapability, "AddArguments method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxPrefsCapability, "SetPreference method"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLogCapability, "LogLevel property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyProfileCapability, "Profile property"); this.AddKnownCapabilityName(FirefoxOptions.FirefoxLegacyBinaryCapability, "BrowserExecutableLocation property"); } /// <summary> /// Gets or sets a value indicating whether to use the legacy driver implementation. /// </summary> [Obsolete(".NET bindings no longer support the legacy driver implementation. Setting this property no longer has any effect. .NET users should always be using geckodriver.")] public bool UseLegacyImplementation { get { return false; } set { } } /// <summary> /// Gets or sets the <see cref="FirefoxProfile"/> object to be used with this instance. /// </summary> public FirefoxProfile Profile { get { return this.profile; } set { this.profile = value; } } /// <summary> /// Gets or sets the path and file name of the Firefox browser executable. /// </summary> public string BrowserExecutableLocation { get { return this.browserBinaryLocation; } set { this.browserBinaryLocation = value; } } /// <summary> /// Gets or sets the logging level of the Firefox driver. /// </summary> public FirefoxDriverLogLevel LogLevel { get { return this.logLevel; } set { this.logLevel = value; } } /// <summary> /// Adds an argument to be used in launching the Firefox browser. /// </summary> /// <param name="argumentName">The argument to add.</param> /// <remarks>Arguments must be preceeded by two dashes ("--").</remarks> public void AddArgument(string argumentName) { if (string.IsNullOrEmpty(argumentName)) { throw new ArgumentException("argumentName must not be null or empty", "argumentName"); } this.AddArguments(argumentName); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> /// <remarks>Each argument must be preceeded by two dashes ("--").</remarks> public void AddArguments(params string[] argumentsToAdd) { this.AddArguments(new List<string>(argumentsToAdd)); } /// <summary> /// Adds a list arguments to be used in launching the Firefox browser. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> public void AddArguments(IEnumerable<string> argumentsToAdd) { if (argumentsToAdd == null) { throw new ArgumentNullException("argumentsToAdd", "argumentsToAdd must not be null"); } this.firefoxArguments.AddRange(argumentsToAdd); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, bool preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, int preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, long preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, double preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Sets a preference in the profile used by Firefox. /// </summary> /// <param name="preferenceName">Name of the preference to set.</param> /// <param name="preferenceValue">Value of the preference to set.</param> public void SetPreference(string preferenceName, string preferenceValue) { this.SetPreferenceValue(preferenceName, preferenceValue); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="optionName">The name of the capability to add.</param> /// <param name="optionValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="optionName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalFirefoxOption(string, object)"/> /// where <paramref name="optionName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="optionValue"/>. /// Calling this method adds capabilities to the Firefox-specific options object passed to /// geckodriver.exe (property name 'moz:firefoxOptions').</remarks> public void AddAdditionalFirefoxOption(string optionName, object optionValue) { this.ValidateCapabilityName(optionName); this.additionalFirefoxOptions[optionName] = optionValue; } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/>. /// Also, by default, calling this method adds capabilities to the options object passed to /// geckodriver.exe.</remarks> [Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalFirefoxOption method for adding additional options")] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { // Add the capability to the FirefoxOptions object by default. This is to handle // the 80% case where the geckodriver team adds a new option in geckodriver.exe // and the bindings have not yet had a type safe option added. this.AddAdditionalFirefoxOption(capabilityName, capabilityValue); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Firefox driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global /// capability for the driver instead of a Firefox-specific option.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/></remarks> [Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalFirefoxOption method for adding additional options")] public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability) { if (isGlobalCapability) { this.AddAdditionalOption(capabilityName, capabilityValue); } else { this.AddAdditionalFirefoxOption(capabilityName, capabilityValue); } } /// <summary> /// Returns DesiredCapabilities for Firefox with these options included as /// capabilities. This does not copy the options. Further changes will be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Firefox with these options.</returns> public override ICapabilities ToCapabilities() { IWritableCapabilities capabilities = GenerateDesiredCapabilities(true); Dictionary<string, object> firefoxOptions = this.GenerateFirefoxOptionsDictionary(); capabilities.SetCapability(FirefoxOptionsCapability, firefoxOptions); return capabilities.AsReadOnly(); } private Dictionary<string, object> GenerateFirefoxOptionsDictionary() { Dictionary<string, object> firefoxOptions = new Dictionary<string, object>(); if (this.profile != null) { firefoxOptions[FirefoxProfileCapability] = this.profile.ToBase64String(); } if (!string.IsNullOrEmpty(this.browserBinaryLocation)) { firefoxOptions[FirefoxBinaryCapability] = this.browserBinaryLocation; } if (this.logLevel != FirefoxDriverLogLevel.Default) { Dictionary<string, object> logObject = new Dictionary<string, object>(); logObject["level"] = this.logLevel.ToString().ToLowerInvariant(); firefoxOptions[FirefoxLogCapability] = logObject; } if (this.firefoxArguments.Count > 0) { List<object> args = new List<object>(); foreach (string argument in this.firefoxArguments) { args.Add(argument); } firefoxOptions[FirefoxArgumentsCapability] = args; } if (this.profilePreferences.Count > 0) { firefoxOptions[FirefoxPrefsCapability] = this.profilePreferences; } foreach (KeyValuePair<string, object> pair in this.additionalFirefoxOptions) { firefoxOptions.Add(pair.Key, pair.Value); } return firefoxOptions; } private void SetPreferenceValue(string preferenceName, object preferenceValue) { if (string.IsNullOrEmpty(preferenceName)) { throw new ArgumentException("Preference name may not be null an empty string.", "preferenceName"); } this.profilePreferences[preferenceName] = preferenceValue; } } }