context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache.Query { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Abstract query cursor implementation. /// </summary> internal abstract class AbstractQueryCursor<T> : PlatformDisposableTarget, IQueryCursor<T>, IEnumerator<T> { /** */ private const int OpGetAll = 1; /** */ private const int OpGetBatch = 2; /** Position before head. */ private const int BatchPosBeforeHead = -1; /** Keep binary flag. */ private readonly bool _keepBinary; /** Wherther "GetAll" was called. */ private bool _getAllCalled; /** Whether "GetEnumerator" was called. */ private bool _iterCalled; /** Batch with entries. */ private T[] _batch; /** Current position in batch. */ private int _batchPos = BatchPosBeforeHead; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Keep binary flag.</param> protected AbstractQueryCursor(IUnmanagedTarget target, Marshaller marsh, bool keepBinary) : base(target, marsh) { _keepBinary = keepBinary; } #region Public methods /** <inheritdoc /> */ public IList<T> GetAll() { ThrowIfDisposed(); if (_iterCalled) throw new InvalidOperationException("Failed to get all entries because GetEnumerator() " + "method has already been called."); if (_getAllCalled) throw new InvalidOperationException("Failed to get all entries because GetAll() " + "method has already been called."); var res = DoInOp<IList<T>>(OpGetAll, ConvertGetAll); _getAllCalled = true; return res; } /** <inheritdoc /> */ protected override void Dispose(bool disposing) { try { UU.QueryCursorClose(Target); } finally { base.Dispose(disposing); } } #endregion #region Public IEnumerable methods /** <inheritdoc /> */ [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public IEnumerator<T> GetEnumerator() { ThrowIfDisposed(); if (_iterCalled) throw new InvalidOperationException("Failed to get enumerator entries because " + "GetEnumeartor() method has already been called."); if (_getAllCalled) throw new InvalidOperationException("Failed to get enumerator entries because " + "GetAll() method has already been called."); UU.QueryCursorIterator(Target); _iterCalled = true; return this; } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Public IEnumerator methods /** <inheritdoc /> */ public T Current { get { ThrowIfDisposed(); if (_batchPos == BatchPosBeforeHead) throw new InvalidOperationException("MoveNext has not been called."); if (_batch == null) throw new InvalidOperationException("Previous call to MoveNext returned false."); return _batch[_batchPos]; } } /** <inheritdoc /> */ object IEnumerator.Current { get { return Current; } } /** <inheritdoc /> */ public bool MoveNext() { ThrowIfDisposed(); if (_batch == null) { if (_batchPos == BatchPosBeforeHead) // Standing before head, let's get batch and advance position. RequestBatch(); } else { _batchPos++; if (_batch.Length == _batchPos) // Reached batch end => request another. RequestBatch(); } return _batch != null; } /** <inheritdoc /> */ public void Reset() { throw new NotSupportedException("Reset is not supported."); } #endregion #region Non-public methods /// <summary> /// Read entry from the reader. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Entry.</returns> protected abstract T Read(BinaryReader reader); /** <inheritdoc /> */ protected override T1 Unmarshal<T1>(IBinaryStream stream) { return Marshaller.Unmarshal<T1>(stream, _keepBinary); } /// <summary> /// Request next batch. /// </summary> private void RequestBatch() { _batch = DoInOp<T[]>(OpGetBatch, ConvertGetBatch); _batchPos = 0; } /// <summary> /// Converter for GET_ALL operation. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Result.</returns> private IList<T> ConvertGetAll(IBinaryStream stream) { var reader = Marshaller.StartUnmarshal(stream, _keepBinary); var size = reader.ReadInt(); var res = new List<T>(size); for (var i = 0; i < size; i++) res.Add(Read(reader)); return res; } /// <summary> /// Converter for GET_BATCH operation. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Result.</returns> private T[] ConvertGetBatch(IBinaryStream stream) { var reader = Marshaller.StartUnmarshal(stream, _keepBinary); var size = reader.ReadInt(); if (size == 0) return null; var res = new T[size]; for (var i = 0; i < size; i++) res[i] = Read(reader); return res; } #endregion } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Globalization; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Web; using System.Web.Security; using log4net; using Subtext.Framework.Configuration; using Subtext.Framework.Logging; using Subtext.Framework.Text; namespace Subtext.Framework.Security { /// <summary> /// Handles blog logins/passwords/tickets /// </summary> public static class SecurityHelper { private readonly static ILog Log = new Log(); /// <summary> /// Gets a value indicating whether the current user is a /// Host Admin for the entire installation. /// </summary> /// <value> /// <c>true</c> if [is host admin]; otherwise, <c>false</c>. /// </value> public static bool IsHostAdministrator(this IPrincipal user) { return user.IsInRole("HostAdmins"); } /// <summary> /// Check to see if the supplied credentials are valid for the current blog. If so, /// Set the user's FormsAuthentication Ticket This method will handle passwords for /// both hashed and non-hashed configurations /// </summary> public static bool Authenticate(this HttpContextBase httpContext, Blog blog, string username, string password, bool persist) { if (!IsValidUser(blog, username, password)) { return false; } httpContext.SetAuthenticationTicket(blog, username, persist, "Admins"); return true; } /// <summary> /// Check to see if the supplied OpenID claim is valid for the current blog. If so, /// Set the user's FormsAuthentication Ticket This method will handle passwords for /// both hashed and non-hashed configurations /// We're comparing URI objects rather than using simple string compare because /// functionally equivalent URI's may not pass string comparaisons, e.g. /// such as http://example.myopenid.com/ and http://example.myopenid.com (trailing /) /// </summary> public static bool Authenticate(string claimedIdentifier, bool persist) { Blog currentBlog = Config.CurrentBlog; if (currentBlog == null) { return false; } //If the current blog doesn't have a valid OpenID URI, must fail if (!Uri.IsWellFormedUriString(currentBlog.OpenIdUrl, UriKind.Absolute)) { return false; } //If the cliamed identifier isn't a valid OpenID URI, must fail if (!Uri.IsWellFormedUriString(claimedIdentifier, UriKind.Absolute)) { return false; } var currentBlogClaimUri = new Uri(currentBlog.OpenIdUrl); var claimedUri = new Uri(claimedIdentifier); if (claimedUri.Host != currentBlogClaimUri.Host || claimedUri.AbsolutePath != currentBlogClaimUri.AbsolutePath || claimedUri.Query != currentBlogClaimUri.Query) { return false; } if (Log.IsDebugEnabled) { Log.Debug("SetAuthenticationTicket-Admins via OpenID for " + currentBlog.UserName); } HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); httpContext.SetAuthenticationTicket(currentBlog, currentBlog.UserName, persist, "Admins"); return true; } public static bool ValidateHostAdminPassword(this HostInfo host, string username, string password) { if (!String.Equals(username, host.HostUserName, StringComparison.OrdinalIgnoreCase)) { return false; } if (Config.Settings.UseHashedPasswords) { password = HashPassword(password, host.Salt); } return String.Equals(host.Password, password, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Authenticates the host admin. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="persist">if set to <c>true</c> [persist].</param> /// <returns></returns> public static bool AuthenticateHostAdmin(this HostInfo host, string username, string password, bool persist) { if (!host.ValidateHostAdminPassword(username, password)) { return false; } if (Log.IsDebugEnabled) { Log.Debug("SetAuthenticationTicket-HostAdmins for " + username); } HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); httpContext.SetAuthenticationTicket(null, username, persist, true, "HostAdmins"); return true; } /// <summary> /// Used to remove a cookie from the client. /// </summary> /// <returns>a correctly named cookie with Expires date set 30 years ago</returns> public static HttpCookie GetExpiredCookie(this HttpRequestBase request, Blog blog) { var expiredCookie = new HttpCookie(request.GetFullCookieName(blog)) { Expires = DateTime.UtcNow.AddYears(-30) }; return expiredCookie; } /// <summary> /// Obtains the correct cookie for the current blog /// </summary> /// <returns>null if correct cookie was not found</returns> public static HttpCookie SelectAuthenticationCookie(this HttpRequestBase request, Blog blog) { HttpCookie authCookie = null; HttpCookie c; int count = request.Cookies.Count; for (int i = 0; i < count; i++) { c = request.Cookies[i]; if (c.Name == request.GetFullCookieName(blog)) { authCookie = c; break; } } return authCookie; } /// <summary> /// Identifies cookies by unique BlogHost names (rather than a single /// name for all cookies in multiblog setups as the old code did). /// </summary> /// <returns></returns> public static string GetFullCookieName(this HttpRequestBase request, Blog blog) { return request.GetFullCookieName(blog, forceHostAdmin: (blog == null || blog.IsAggregateBlog)); } public static string GetFullCookieName(this HttpRequestBase request, Blog blog, bool forceHostAdmin) { var name = new StringBuilder(FormsAuthentication.FormsCookieName); name.Append("."); //See if we need to authenticate the HostAdmin string path = request.Path; string returnUrl = request.QueryString["ReturnURL"]; if (forceHostAdmin || (path + returnUrl).Contains("HostAdmin", StringComparison.OrdinalIgnoreCase)) { name.Append("HA."); } if (!forceHostAdmin && blog != null) { name.Append(blog.Id.ToString(CultureInfo.InvariantCulture)); } else { name.Append("null"); } if (Log.IsDebugEnabled) { Log.Debug("GetFullCookieName selected cookie named " + name); } return name.ToString(); } public static void SetAuthenticationTicket(this HttpContextBase httpContext, Blog blog, string username, bool persist, params string[] roles) { httpContext.SetAuthenticationTicket(blog, username, persist, false, roles); } /// <summary> /// Used by methods in this class plus Install.Step02_ConfigureHost /// </summary> public static void SetAuthenticationTicket(this HttpContextBase httpContext, Blog blog, string username, bool persist, bool forceHostAdmin, params string[] roles) { //Getting a cookie this way and using a temp auth ticket //allows us to access the timeout value from web.config in partial trust. HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, persist); FormsAuthenticationTicket tempTicket = FormsAuthentication.Decrypt(authCookie.Value); string userData = string.Join("|", roles); var authTicket = new FormsAuthenticationTicket( tempTicket.Version, tempTicket.Name, tempTicket.IssueDate, tempTicket.Expiration, //this is how we access the configured timeout value persist, //the configured persistence value in web.config is not used. We use the checkbox value on the login page. userData, //roles tempTicket.CookiePath); authCookie.Value = FormsAuthentication.Encrypt(authTicket); authCookie.Name = httpContext.Request.GetFullCookieName(blog, forceHostAdmin); //prevents login problems with some multiblog setups httpContext.Response.Cookies.Add(authCookie); } /// <summary> /// Get MD5 hashed/encrypted representation of the password and /// returns a Base64 encoded string of the hash. /// This is a one-way hash. /// </summary> /// <remarks> /// Passwords are case sensitive now. Before they weren't. /// </remarks> /// <param name="password">Supplied Password</param> /// <returns>Encrypted (Hashed) value</returns> public static string HashPassword(string password) { Byte[] clearBytes = new UnicodeEncoding().GetBytes(password); Byte[] hashedBytes = new MD5CryptoServiceProvider().ComputeHash(clearBytes); return Convert.ToBase64String(hashedBytes); } /// <summary> /// Get MD5 hashed/encrypted representation of the password and a /// salt value combined in the proper manner. /// Returns a Base64 encoded string of the hash. /// This is a one-way hash. /// </summary> /// <remarks> /// Passwords are case sensitive now. Before they weren't. /// </remarks> public static string HashPassword(string password, string salt) { string preHash = CombinePasswordAndSalt(password, salt); return HashPassword(preHash); } /// <summary> /// Creates a random salt value. /// </summary> /// <returns></returns> public static string CreateRandomSalt() { return Convert.ToBase64String(Guid.NewGuid().ToByteArray()); } /// <summary> /// Returns a string with a password and salt combined. /// </summary> /// <param name="password">Password.</param> /// <param name="salt">Salt.</param> /// <returns></returns> public static string CombinePasswordAndSalt(string password, string salt) { //TODO: return salt + "." + password; //We're not ready to do this yet till we do it to the blog_content table too. return password; } /// <summary> /// Validates if the supplied credentials match the current blog /// </summary> public static bool IsValidUser(this Blog blog, string username, string password) { if (String.Equals(username, blog.UserName, StringComparison.OrdinalIgnoreCase)) { return IsValidPassword(blog, password); } Log.DebugFormat("The supplied username '{0}' does not equal the configured username of '{1}'.", username, blog.UserName); return false; } /// <summary> /// Check to see if the supplied password matches the password /// for the current blog. This method will check the /// BlogConfigurationSettings to see if the password should be /// Encrypted/Hashed /// </summary> public static bool IsValidPassword(Blog blog, string password) { if (blog.IsPasswordHashed) { password = HashPassword(password); } string storedPassword = blog.Password; if (storedPassword.IndexOf('-') > 0) { // NOTE: This is necessary because I want to change how // we store the password. Maybe changing the password // storage is dumb. Let me know. -Phil // This is an old password created from BitConverter // string. Converting to a Base64 hash. string[] hashBytesStrings = storedPassword.Split('-'); var hashedBytes = new byte[hashBytesStrings.Length]; for (int i = 0; i < hashBytesStrings.Length; i++) { hashedBytes[i] = byte.Parse(hashBytesStrings[i].ToString(CultureInfo.InvariantCulture), NumberStyles.HexNumber, CultureInfo.InvariantCulture); storedPassword = Convert.ToBase64String(hashedBytes); } } return String.Equals(password, storedPassword, StringComparison.Ordinal); } public static bool IsAdministrator(this IPrincipal user) { if (user == null) { return false; } return user.IsInRole("Admins"); } /// <summary> /// Returns true if the user is in the specified role. /// It's a wrapper to calling the IsInRole method of /// IPrincipal. /// </summary> /// <param name="role">Role.</param> /// <returns></returns> public static bool IsInRole(string role) { if (HttpContext.Current.User == null) { return false; } return HttpContext.Current.User.IsInRole(role); } /// <summary> /// Generates the symmetric key. /// </summary> /// <returns></returns> public static byte[] GenerateSymmetricKey() { SymmetricAlgorithm rijaendel = Rijndael.Create(); rijaendel.GenerateKey(); return rijaendel.Key; } /// <summary> /// Generates the symmetric key. /// </summary> /// <returns></returns> public static byte[] GenerateInitializationVector() { SymmetricAlgorithm rijaendel = Rijndael.Create(); rijaendel.GenerateIV(); return rijaendel.IV; } /// <summary> /// Generates the symmetric key. /// </summary> /// <param name="clearText">The clear text.</param> /// <param name="encoding">The encoding.</param> /// <param name="key">The key.</param> /// <param name="initializationVendor">The initialization vendor.</param> /// <returns></returns> public static string EncryptString(string clearText, Encoding encoding, byte[] key, byte[] initializationVendor) { SymmetricAlgorithm rijaendel = Rijndael.Create(); ICryptoTransform encryptor = rijaendel.CreateEncryptor(key, initializationVendor); byte[] clearTextBytes = encoding.GetBytes(clearText); byte[] encrypted = encryptor.TransformFinalBlock(clearTextBytes, 0, clearTextBytes.Length); return Convert.ToBase64String(encrypted); } /// <summary> /// Decrypts the string. /// </summary> /// <param name="encryptedBase64EncodedString">The encrypted base64 encoded string.</param> /// <param name="encoding">The encoding.</param> /// <param name="key">The key.</param> /// <param name="initializationVendor">The initialization vendor.</param> /// <returns></returns> public static string DecryptString(string encryptedBase64EncodedString, Encoding encoding, byte[] key, byte[] initializationVendor) { SymmetricAlgorithm rijaendel = Rijndael.Create(); ICryptoTransform decryptor = rijaendel.CreateDecryptor(key, initializationVendor); byte[] encrypted = Convert.FromBase64String(encryptedBase64EncodedString); byte[] decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length); return encoding.GetString(decrypted); } } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; using qx.ui.core; using qx.ui.form; namespace qx.ui.control { /// <summary> /// <para>A date chooser is a small calendar including a navigation bar to switch the shown /// month. It includes a column for the calendar week and shows one month. Selecting /// a date is as easy as clicking on it.</para> /// <para>To be conform with all form widgets, the <see cref="qx.ui.form.IForm"/> interface /// is implemented.</para> /// <para>The following example creates and adds a date chooser to the root element. /// A listener alerts the user if a new date is selected.</para> /// <code> /// var chooser = new qx.ui.control.DateChooser(); /// this.getRoot().add(chooser, { left : 20, top: 20}); /// chooser.addListener("changeValue", function(e) { /// alert(e.getData()); /// }); /// </code> /// <para>Additionally to a selection event an execute event is available which is /// fired by doubleclick or taping the space / enter key. With this event you /// can for example save the selection and close the date chooser.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.control.DateChooser", OmitOptionalParameters = true, Export = false)] public partial class DateChooser : qx.ui.core.Widget, qx.ui.form.IExecutable, qx.ui.form.IForm, qx.ui.form.IDateForm { #region Events /// <summary> /// Fired on change of the property <see cref="ShownMonth"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeShownMonth; /// <summary> /// Fired on change of the property <see cref="ShownYear"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeShownYear; /// <summary> /// <para>Fired when the value was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeValue; /// <summary> /// Fired on change of the property <see cref="Command"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeCommand; /// <summary> /// <para>Fired when the widget is executed. Sets the &#8220;data&#8221; property of the /// event to the object that issued the command.</para> /// </summary> public event Action<qx.eventx.type.Data> OnExecute; /// <summary> /// <para>Fired when the invalidMessage was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeInvalidMessage; /// <summary> /// <para>Fired when the required was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeRequired; /// <summary> /// <para>Fired when the valid state was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeValid; #endregion Events #region Properties /// <summary> /// <para>The appearance ID. This ID is used to identify the appearance theme /// entry to use for this widget. This controls the styling of the element.</para> /// </summary> [JsProperty(Name = "appearance", NativeField = true)] public string Appearance { get; set; } /// <summary> /// <para>The item&#8217;s preferred height.</para> /// <para>The computed height may differ from the given height due to /// stretching. Also take a look at the related properties /// <see cref="MinHeight"/> and <see cref="MaxHeight"/>.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "height", NativeField = true)] public double Height { get; set; } /// <summary> /// <para>The currently shown month. 0 = january, 1 = february, and so on.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "shownMonth", NativeField = true)] public double ShownMonth { get; set; } /// <summary> /// <para>The currently shown year.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "shownYear", NativeField = true)] public double ShownYear { get; set; } /// <summary> /// <para>The date value of the widget.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "value", NativeField = true)] public DateTime Value { get; set; } /// <summary> /// <para>The LayoutItem&#8216;s preferred width.</para> /// <para>The computed width may differ from the given width due to /// stretching. Also take a look at the related properties /// <see cref="MinWidth"/> and <see cref="MaxWidth"/>.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "width", NativeField = true)] public double Width { get; set; } /// <summary> /// <para>A command called if the <see cref="Execute"/> method is called, e.g. on a /// button click.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "command", NativeField = true)] public qx.ui.core.Command Command { get; set; } /// <summary> /// <para>Message which is shown in an invalid tooltip.</para> /// </summary> [JsProperty(Name = "invalidMessage", NativeField = true)] public string InvalidMessage { get; set; } /// <summary> /// <para>Flag signaling if a widget is required.</para> /// </summary> [JsProperty(Name = "required", NativeField = true)] public bool Required { get; set; } /// <summary> /// <para>Message which is shown in an invalid tooltip if the <see cref="Required"/> is /// set to true.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "requiredInvalidMessage", NativeField = true)] public string RequiredInvalidMessage { get; set; } /// <summary> /// <para>Flag signaling if a widget is valid. If a widget is invalid, an invalid /// state will be set.</para> /// </summary> [JsProperty(Name = "valid", NativeField = true)] public bool Valid { get; set; } #endregion Properties #region Methods public DateChooser() { throw new NotImplementedException(); } /// <param name="date">The initial date to show. If null the current day (today) is shown.</param> public DateChooser(DateTime? date = null) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property shownMonth.</para> /// </summary> [JsMethod(Name = "getShownMonth")] public double GetShownMonth() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property shownYear.</para> /// </summary> [JsMethod(Name = "getShownYear")] public double GetShownYear() { throw new NotImplementedException(); } /// <summary> /// <para>The element&#8217;s user set value.</para> /// </summary> /// <returns>The value.</returns> [JsMethod(Name = "getValue")] public DateTime GetValue() { throw new NotImplementedException(); } /// <summary> /// <para>Event handler. Used to handle the key events.</para> /// </summary> /// <param name="e">The event.</param> [JsMethod(Name = "handleKeyPress")] public void HandleKeyPress(qx.eventx.type.Data e) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property shownMonth /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property shownMonth.</param> [JsMethod(Name = "initShownMonth")] public void InitShownMonth(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property shownYear /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property shownYear.</param> [JsMethod(Name = "initShownYear")] public void InitShownYear(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property value /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property value.</param> [JsMethod(Name = "initValue")] public void InitValue(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property shownMonth.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetShownMonth")] public void ResetShownMonth() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property shownYear.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetShownYear")] public void ResetShownYear() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the element&#8217;s value to its initial value.</para> /// </summary> [JsMethod(Name = "resetValue")] public void ResetValue() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property shownMonth.</para> /// </summary> /// <param name="value">New value for property shownMonth.</param> [JsMethod(Name = "setShownMonth")] public void SetShownMonth(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property shownYear.</para> /// </summary> /// <param name="value">New value for property shownYear.</param> [JsMethod(Name = "setShownYear")] public void SetShownYear(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the element&#8217;s value.</para> /// </summary> /// <param name="value">The new value of the element.</param> [JsMethod(Name = "setValue")] public void SetValue(DateTime value) { throw new NotImplementedException(); } /// <summary> /// <para>Shows a certain month.</para> /// </summary> /// <param name="month">the month to show (0 = january). If not set the month will remain the same.</param> /// <param name="year">the year to show. If not set the year will remain the same.</param> [JsMethod(Name = "showMonth")] public void ShowMonth(double? month = null, double? year = null) { throw new NotImplementedException(); } /// <summary> /// <para>Fire the &#8220;execute&#8221; event on the command.</para> /// </summary> [JsMethod(Name = "execute")] public void Execute() { throw new NotImplementedException(); } /// <summary> /// <para>Return the current set command of this executable.</para> /// </summary> /// <returns>The current set command.</returns> [JsMethod(Name = "getCommand")] public qx.ui.core.Command GetCommand() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property command /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property command.</param> [JsMethod(Name = "initCommand")] public void InitCommand(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property command.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetCommand")] public void ResetCommand() { throw new NotImplementedException(); } /// <summary> /// <para>Set the command of this executable.</para> /// </summary> /// <param name="command">The command.</param> [JsMethod(Name = "setCommand")] public void SetCommand(qx.ui.core.Command command) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the invalid message of the widget.</para> /// </summary> /// <returns>The current set message.</returns> [JsMethod(Name = "getInvalidMessage")] public string GetInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Return the current required state of the widget.</para> /// </summary> /// <returns>True, if the widget is required.</returns> [JsMethod(Name = "getRequired")] public bool GetRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the invalid message if required of the widget.</para> /// </summary> /// <returns>The current set message.</returns> [JsMethod(Name = "getRequiredInvalidMessage")] public string GetRequiredInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the valid state of the widget.</para> /// </summary> /// <returns>If the state of the widget is valid.</returns> [JsMethod(Name = "getValid")] public bool GetValid() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property invalidMessage /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property invalidMessage.</param> [JsMethod(Name = "initInvalidMessage")] public void InitInvalidMessage(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property required /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property required.</param> [JsMethod(Name = "initRequired")] public void InitRequired(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property requiredInvalidMessage /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property requiredInvalidMessage.</param> [JsMethod(Name = "initRequiredInvalidMessage")] public void InitRequiredInvalidMessage(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property valid /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property valid.</param> [JsMethod(Name = "initValid")] public void InitValid(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property required equals true.</para> /// </summary> [JsMethod(Name = "isRequired")] public void IsRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property valid equals true.</para> /// </summary> [JsMethod(Name = "isValid")] public void IsValid() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property invalidMessage.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetInvalidMessage")] public void ResetInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property required.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetRequired")] public void ResetRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property requiredInvalidMessage.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetRequiredInvalidMessage")] public void ResetRequiredInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property valid.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetValid")] public void ResetValid() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the invalid message of the widget.</para> /// </summary> /// <param name="message">The invalid message.</param> [JsMethod(Name = "setInvalidMessage")] public void SetInvalidMessage(string message) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the required state of a widget.</para> /// </summary> /// <param name="required">A flag signaling if the widget is required.</param> [JsMethod(Name = "setRequired")] public void SetRequired(bool required) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the invalid message if required of the widget.</para> /// </summary> /// <param name="message">The invalid message.</param> [JsMethod(Name = "setRequiredInvalidMessage")] public void SetRequiredInvalidMessage(string message) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the valid state of the widget.</para> /// </summary> /// <param name="valid">The valid state of the widget.</param> [JsMethod(Name = "setValid")] public void SetValid(bool valid) { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property required.</para> /// </summary> [JsMethod(Name = "toggleRequired")] public void ToggleRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property valid.</para> /// </summary> [JsMethod(Name = "toggleValid")] public void ToggleValid() { throw new NotImplementedException(); } #endregion Methods } }
// 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.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class JoinTests { private const int KeyFactor = 8; public static IEnumerable<object[]> JoinUnorderedData(int[] counts) { foreach (int leftCount in counts) { foreach (int rightCount in counts) { yield return new object[] { leftCount, rightCount }; } } } public static IEnumerable<object[]> JoinData(int[] counts) { // When dealing with joins, if there aren't multiple matches the ordering of the second operand is immaterial. foreach (object[] parms in Sources.Ranges(counts, i => counts)) { yield return parms; } } public static IEnumerable<object[]> JoinMultipleData(int[] counts) { foreach (object[] parms in UnorderedSources.BinaryRanges(counts, counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } public static IEnumerable<object[]> JoinOrderedLeftUnorderedRightData(int[] counts) { foreach (object[] parms in UnorderedSources.BinaryRanges(counts, counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]), parms[3] }; } } // // Join // [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_Longrunning() { Join_Unordered(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); int seen = 0; foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); } Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join(left, leftCount, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_NotPipelined(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_NotPipelined_Longrunning() { Join_Unordered_NotPipelined(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); int seen = 0; Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); }); Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join_NotPipelined(left, leftCount, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_Multiple(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor)); IntegerRangeSet seenInner = new IntegerRangeSet(0, Math.Min(leftCount * KeyFactor, rightCount)); Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { Assert.Equal(p.Key, p.Value / KeyFactor); seenInner.Add(p.Value); if (p.Value % KeyFactor == 0) seenOuter.Add(p.Key); }); seenOuter.AssertComplete(); seenInner.AssertComplete(); } [Fact] [OuterLoop] public static void Join_Unordered_Multiple_Longrunning() { Join_Unordered_Multiple(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { Assert.Equal(p.Key, p.Value / KeyFactor); Assert.Equal(seen++, p.Value); }); Assert.Equal(Math.Min(leftCount * KeyFactor, rightCount), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithOrderedRight : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y % KeyFactor, (x, y) => KeyValuePair.Create(x, y)); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left, right % KeyFactor); Assert.Equal(left + seenRightCount * KeyFactor, right); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { return Math.Min(KeyFactor, Math.Min(rightCount, leftCount)); } } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_Multiple_LeftWithOrderingColisions(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithOrderedRight validator = new LeftOrderingCollisionTestWithOrderedRight(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_Multiple_LeftWithOrderingColisions_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple_LeftWithOrderingColisions(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithUnorderedRight : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y % KeyFactor, (x, y) => KeyValuePair.Create(x, y)).Distinct(); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left, right % KeyFactor); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { return Math.Min(KeyFactor, Math.Min(rightCount, leftCount)); } } [Theory] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve grouping of order-identical left keys through repartitioning (see https://github.com/dotnet/corefx/pull/27930#issuecomment-372084741)")] public static void Join_Multiple_LeftWithOrderingColisions_UnorderedRight(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithUnorderedRight validator = new LeftOrderingCollisionTestWithUnorderedRight(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 256, 512 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve grouping of order-identical left keys through repartitioning (see https://github.com/dotnet/corefx/pull/27930#issuecomment-372084741)")] public static void Join_Multiple_LeftWithOrderingColisions_UnorderedRight_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_Multiple_LeftWithOrderingColisions_UnorderedRight(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(JoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_Unordered_CustomComparator(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); IntegerRangeCounter seenOuter = new IntegerRangeCounter(0, leftCount); IntegerRangeCounter seenInner = new IntegerRangeCounter(0, rightCount); Assert.All(leftQuery.Join(rightQuery, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor); seenOuter.Add(p.Key); seenInner.Add(p.Value); }); if (leftCount == 0 || rightCount == 0) { seenOuter.AssertEncountered(0); seenInner.AssertEncountered(0); } else { Func<int, int, int> cartesian = (key, other) => (other + (KeyFactor - 1) - key % KeyFactor) / KeyFactor; Assert.All(seenOuter, kv => Assert.Equal(cartesian(kv.Key, rightCount), kv.Value)); Assert.All(seenInner, kv => Assert.Equal(cartesian(kv.Key, leftCount), kv.Value)); } } [Fact] [OuterLoop] public static void Join_Unordered_CustomComparator_Longrunning() { Join_Unordered_CustomComparator(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seenOuter = 0; int previousOuter = -1; int seenInner = Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor); Assert.All(leftQuery.Join(rightQuery, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { if (p.Key != previousOuter) { Assert.Equal(seenOuter, p.Key); Assert.Equal(p.Key % 8, p.Value); // If there aren't sufficient elements in the RHS (< 8), the LHS skips an entry at the end of the mod cycle. seenOuter = Math.Min(leftCount, seenOuter + (p.Key % KeyFactor + 1 == rightCount ? KeyFactor - p.Key % KeyFactor : 1)); Assert.Equal(Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor), seenInner); previousOuter = p.Key; seenInner = (p.Key % KeyFactor) - KeyFactor; } Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor); Assert.Equal(seenInner += KeyFactor, p.Value); }); Assert.Equal(rightCount == 0 ? 0 : leftCount, seenOuter); Assert.Equal(Math.Max(previousOuter % KeyFactor, rightCount - KeyFactor + previousOuter % KeyFactor), seenInner); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithOrderedRightAndCustomComparator : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left % KeyFactor, right % KeyFactor); Assert.Equal(left % KeyFactor + seenRightCount * KeyFactor, right); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { if (rightCount >= KeyFactor) { return leftCount; } else { return leftCount / KeyFactor * rightCount + Math.Min(leftCount % KeyFactor, rightCount); } } } [Theory] [MemberData(nameof(JoinMultipleData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_CustomComparator_LeftWithOrderingColisions(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithOrderedRightAndCustomComparator validator = new LeftOrderingCollisionTestWithOrderedRightAndCustomComparator(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinMultipleData), new[] { 512, 1024 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve the right collection order (.NET core bug fix https://github.com/dotnet/corefx/pull/27930)")] public static void Join_CustomComparator_LeftWithOrderingColisions_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator_LeftWithOrderingColisions(left, leftCount, right, rightCount); } private class LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator : LeftOrderingCollisionTest { protected override ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right) { return ReorderLeft(left).Join(right, x => x, y => y, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)).Distinct(); } protected override void ValidateRightValue(int left, int right, int seenRightCount) { Assert.Equal(left % KeyFactor, right % KeyFactor); } protected override int GetExpectedSeenLeftCount(int leftCount, int rightCount) { if (rightCount >= KeyFactor) { return leftCount; } else { return leftCount / KeyFactor * rightCount + Math.Min(leftCount % KeyFactor, rightCount); } } } [Theory] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 2, KeyFactor - 1, KeyFactor, KeyFactor + 1, KeyFactor * 2 - 1, KeyFactor * 2, KeyFactor * 2 + 1 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve grouping of order-identical left keys through repartitioning (see https://github.com/dotnet/corefx/pull/27930#issuecomment-372084741)")] public static void Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator validator = new LeftOrderingCollisionTestWithUnorderedRightAndCustomComparator(); validator.Validate(left.Item, leftCount, right.Item, rightCount); } [Theory] [OuterLoop] [MemberData(nameof(JoinOrderedLeftUnorderedRightData), new[] { 256 })] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework doesn't preserve grouping of order-identical left keys through repartitioning (see https://github.com/dotnet/corefx/pull/27930#issuecomment-372084741)")] public static void Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Join_CustomComparator_LeftWithOrderingColisions_UnorderedRight(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(JoinData), new[] { 0, 1, 2, KeyFactor * 2 })] public static void Join_InnerJoin_Ordered(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount); ParallelQuery<int> middleQuery = ParallelEnumerable.Range(0, leftCount).AsOrdered(); int seen = 0; Assert.All(leftQuery.Join(middleQuery.Join(rightQuery, x => x * KeyFactor / 2, y => y, (x, y) => KeyValuePair.Create(x, y)), z => z * 2, p => p.Key, (x, p) => KeyValuePair.Create(x, p)), pOuter => { KeyValuePair<int, int> pInner = pOuter.Value; Assert.Equal(seen++, pOuter.Key); Assert.Equal(pOuter.Key * 2, pInner.Key); Assert.Equal(pOuter.Key * KeyFactor, pInner.Value); }); Assert.Equal(Math.Min((leftCount + 1) / 2, (rightCount + (KeyFactor - 1)) / KeyFactor), seen); } [Theory] [OuterLoop] [MemberData(nameof(JoinData), new[] { 512, 1024 })] public static void Join_InnerJoin_Ordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount) { Join_InnerJoin_Ordered(left, leftCount, rightCount); } [Fact] public static void Join_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i)); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Join_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Join(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Join(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Join(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (l, r) => l)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Join(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (l, r) => l)); } [Fact] public static void Join_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null)); AssertExtensions.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null, EqualityComparer<int>.Default)); } private abstract class LeftOrderingCollisionTest { protected ParallelQuery<int> ReorderLeft(ParallelQuery<int> left) { return left.AsUnordered().OrderBy(x => x % 2); } protected abstract ParallelQuery<KeyValuePair<int, int>> Join(ParallelQuery<int> left, ParallelQuery<int> right); protected abstract void ValidateRightValue(int left, int right, int seenRightCount); protected abstract int GetExpectedSeenLeftCount(int leftCount, int rightCount); public void Validate(ParallelQuery<int> left, int leftCount, ParallelQuery<int> right, int rightCount) { HashSet<int> seenLeft = new HashSet<int>(); HashSet<int> seenRight = new HashSet<int>(); int currentLeft = -1; bool seenOdd = false; Assert.All(Join(left, right), p => { try { if (currentLeft != p.Key) { try { if (p.Key % 2 == 1) { seenOdd = true; } else { Assert.False(seenOdd, "Key out of order! " + p.Key.ToString()); } Assert.True(seenLeft.Add(p.Key), "Key already seen! " + p.Key.ToString()); if (currentLeft != -1) { Assert.Equal((rightCount / KeyFactor) + (((rightCount % KeyFactor) > (currentLeft % KeyFactor)) ? 1 : 0), seenRight.Count); } } finally { currentLeft = p.Key; seenRight.Clear(); } } ValidateRightValue(p.Key, p.Value, seenRight.Count); Assert.True(seenRight.Add(p.Value), "Value already seen! " + p.Value.ToString()); } catch (Exception ex) { throw new Exception(string.Format("Key: {0}, Value: {1}", p.Key, p.Value), ex); } finally { seenRight.Add(p.Value); } }); Assert.Equal((rightCount / KeyFactor) + (((rightCount % KeyFactor) > (currentLeft % KeyFactor)) ? 1 : 0), seenRight.Count); Assert.Equal(GetExpectedSeenLeftCount(leftCount, rightCount), seenLeft.Count); } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Globalization; namespace Avalonia.Controls.Utils { internal static class StringUtils { private enum CharClass { CharClassUnknown, CharClassWhitespace, CharClassAlphaNumeric, } public static bool IsEol(char c) { return c == '\r' || c == '\n'; } public static bool IsStartOfWord(string text, int index) { if (index >= text.Length) { return false; } // A 'word' starts with an AlphaNumeric or some punctuation symbols immediately // preceeded by lwsp. if (index > 0 && !char.IsWhiteSpace(text[index - 1])) { return false; } switch (CharUnicodeInfo.GetUnicodeCategory(text[index])) { case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.UppercaseLetter: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.LetterNumber: case UnicodeCategory.OtherNumber: case UnicodeCategory.DashPunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.CurrencySymbol: case UnicodeCategory.MathSymbol: return true; // TODO: How do you do this in .NET? // case UnicodeCategory.OtherPunctuation: // // words cannot start with '.', but they can start with '&' or '*' (for example) // return g_unichar_break_type(buffer->text[index]) == G_UNICODE_BREAK_ALPHABETIC; default: return false; } } public static int PreviousWord(string text, int cursor, bool gtkMode) { int begin; int i; int cr; int lf; lf = LineBegin(text, cursor) - 1; if (lf > 0 && text[lf] == '\n' && text[lf - 1] == '\r') { cr = lf - 1; } else { cr = lf; } // if the cursor is at the beginning of the line, return the end of the prev line if (cursor - 1 == lf) { return (cr > 0) ? cr : 0; } if (gtkMode) { CharClass cc = GetCharClass(text[cursor - 1]); begin = lf + 1; i = cursor; // skip over the word, punctuation, or run of whitespace while (i > begin && GetCharClass(text[i - 1]) == cc) { i--; } // if the cursor was at whitespace, skip back a word too if (cc == CharClass.CharClassWhitespace && i > begin) { cc = GetCharClass(text[i - 1]); while (i > begin && GetCharClass(text[i - 1]) == cc) { i--; } } } else { begin = lf + 1; i = cursor; if (cursor < text.Length) { // skip to the beginning of this word while (i > begin && !char.IsWhiteSpace(text[i - 1])) { i--; } if (i < cursor && IsStartOfWord(text, i)) { return i; } } // skip to the start of the lwsp while (i > begin && char.IsWhiteSpace(text[i - 1])) { i--; } if (i > begin) { i--; } // skip to the beginning of the word while (i > begin && !IsStartOfWord(text, i)) { i--; } } return i; } public static int NextWord(string text, int cursor, bool gtkMode) { int i, lf, cr; cr = LineEnd(text, cursor); if (cr < text.Length && text[cr] == '\r' && text[cr + 1] == '\n') { lf = cr + 1; } else { lf = cr; } // if the cursor is at the end of the line, return the starting offset of the next line if (cursor == cr || cursor == lf) { if (lf < text.Length) { return lf + 1; } return cursor; } if (gtkMode) { CharClass cc = GetCharClass(text[cursor]); i = cursor; // skip over the word, punctuation, or run of whitespace while (i < cr && GetCharClass(text[i]) == cc) { i++; } // skip any whitespace after the word/punct while (i < cr && char.IsWhiteSpace(text[i])) { i++; } } else { i = cursor; // skip to the end of the current word while (i < cr && !char.IsWhiteSpace(text[i])) { i++; } // skip any whitespace after the word while (i < cr && char.IsWhiteSpace(text[i])) { i++; } // find the start of the next word while (i < cr && !IsStartOfWord(text, i)) { i++; } } return i; } private static CharClass GetCharClass(char c) { if (char.IsWhiteSpace(c)) { return CharClass.CharClassWhitespace; } else if (char.IsLetterOrDigit(c)) { return CharClass.CharClassAlphaNumeric; } else { return CharClass.CharClassUnknown; } } private static int LineBegin(string text, int pos) { while (pos > 0 && !IsEol(text[pos - 1])) { pos--; } return pos; } private static int LineEnd(string text, int cursor, bool include = false) { while (cursor < text.Length && !IsEol(text[cursor])) { cursor++; } if (include && cursor < text.Length) { if (text[cursor] == '\r' && text[cursor + 1] == '\n') { cursor += 2; } else { cursor++; } } return cursor; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedExperimentsClientSnippets { /// <summary>Snippet for ListExperiments</summary> public void ListExperimentsRequestObject() { // Snippet: ListExperiments(ListExperimentsRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ListExperimentsRequest request = new ListExperimentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(request); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsRequestObjectAsync() { // Snippet: ListExperimentsAsync(ListExperimentsRequest, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ListExperimentsRequest request = new ListExperimentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperiments</summary> public void ListExperiments() { // Snippet: ListExperiments(string, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsAsync() { // Snippet: ListExperimentsAsync(string, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperiments</summary> public void ListExperimentsResourceNames() { // Snippet: ListExperiments(EnvironmentName, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperiments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Experiment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExperimentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExperimentsAsync</summary> public async Task ListExperimentsResourceNamesAsync() { // Snippet: ListExperimentsAsync(EnvironmentName, string, int?, CallSettings) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedAsyncEnumerable<ListExperimentsResponse, Experiment> response = experimentsClient.ListExperimentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Experiment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExperimentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Experiment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Experiment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Experiment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperimentRequestObject() { // Snippet: GetExperiment(GetExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) GetExperimentRequest request = new GetExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.GetExperiment(request); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentRequestObjectAsync() { // Snippet: GetExperimentAsync(GetExperimentRequest, CallSettings) // Additional: GetExperimentAsync(GetExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) GetExperimentRequest request = new GetExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.GetExperimentAsync(request); // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperiment() { // Snippet: GetExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.GetExperiment(name); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentAsync() { // Snippet: GetExperimentAsync(string, CallSettings) // Additional: GetExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.GetExperimentAsync(name); // End snippet } /// <summary>Snippet for GetExperiment</summary> public void GetExperimentResourceNames() { // Snippet: GetExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.GetExperiment(name); // End snippet } /// <summary>Snippet for GetExperimentAsync</summary> public async Task GetExperimentResourceNamesAsync() { // Snippet: GetExperimentAsync(ExperimentName, CallSettings) // Additional: GetExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.GetExperimentAsync(name); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperimentRequestObject() { // Snippet: CreateExperiment(CreateExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) CreateExperimentRequest request = new CreateExperimentRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), Experiment = new Experiment(), }; // Make the request Experiment response = experimentsClient.CreateExperiment(request); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentRequestObjectAsync() { // Snippet: CreateExperimentAsync(CreateExperimentRequest, CallSettings) // Additional: CreateExperimentAsync(CreateExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) CreateExperimentRequest request = new CreateExperimentRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), Experiment = new Experiment(), }; // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(request); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperiment() { // Snippet: CreateExperiment(string, Experiment, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; Experiment experiment = new Experiment(); // Make the request Experiment response = experimentsClient.CreateExperiment(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentAsync() { // Snippet: CreateExperimentAsync(string, Experiment, CallSettings) // Additional: CreateExperimentAsync(string, Experiment, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; Experiment experiment = new Experiment(); // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperiment</summary> public void CreateExperimentResourceNames() { // Snippet: CreateExperiment(EnvironmentName, Experiment, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); Experiment experiment = new Experiment(); // Make the request Experiment response = experimentsClient.CreateExperiment(parent, experiment); // End snippet } /// <summary>Snippet for CreateExperimentAsync</summary> public async Task CreateExperimentResourceNamesAsync() { // Snippet: CreateExperimentAsync(EnvironmentName, Experiment, CallSettings) // Additional: CreateExperimentAsync(EnvironmentName, Experiment, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); Experiment experiment = new Experiment(); // Make the request Experiment response = await experimentsClient.CreateExperimentAsync(parent, experiment); // End snippet } /// <summary>Snippet for UpdateExperiment</summary> public void UpdateExperimentRequestObject() { // Snippet: UpdateExperiment(UpdateExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) UpdateExperimentRequest request = new UpdateExperimentRequest { Experiment = new Experiment(), UpdateMask = new FieldMask(), }; // Make the request Experiment response = experimentsClient.UpdateExperiment(request); // End snippet } /// <summary>Snippet for UpdateExperimentAsync</summary> public async Task UpdateExperimentRequestObjectAsync() { // Snippet: UpdateExperimentAsync(UpdateExperimentRequest, CallSettings) // Additional: UpdateExperimentAsync(UpdateExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) UpdateExperimentRequest request = new UpdateExperimentRequest { Experiment = new Experiment(), UpdateMask = new FieldMask(), }; // Make the request Experiment response = await experimentsClient.UpdateExperimentAsync(request); // End snippet } /// <summary>Snippet for UpdateExperiment</summary> public void UpdateExperiment() { // Snippet: UpdateExperiment(Experiment, FieldMask, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) Experiment experiment = new Experiment(); FieldMask updateMask = new FieldMask(); // Make the request Experiment response = experimentsClient.UpdateExperiment(experiment, updateMask); // End snippet } /// <summary>Snippet for UpdateExperimentAsync</summary> public async Task UpdateExperimentAsync() { // Snippet: UpdateExperimentAsync(Experiment, FieldMask, CallSettings) // Additional: UpdateExperimentAsync(Experiment, FieldMask, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) Experiment experiment = new Experiment(); FieldMask updateMask = new FieldMask(); // Make the request Experiment response = await experimentsClient.UpdateExperimentAsync(experiment, updateMask); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperimentRequestObject() { // Snippet: DeleteExperiment(DeleteExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) DeleteExperimentRequest request = new DeleteExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request experimentsClient.DeleteExperiment(request); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentRequestObjectAsync() { // Snippet: DeleteExperimentAsync(DeleteExperimentRequest, CallSettings) // Additional: DeleteExperimentAsync(DeleteExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) DeleteExperimentRequest request = new DeleteExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request await experimentsClient.DeleteExperimentAsync(request); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperiment() { // Snippet: DeleteExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request experimentsClient.DeleteExperiment(name); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentAsync() { // Snippet: DeleteExperimentAsync(string, CallSettings) // Additional: DeleteExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request await experimentsClient.DeleteExperimentAsync(name); // End snippet } /// <summary>Snippet for DeleteExperiment</summary> public void DeleteExperimentResourceNames() { // Snippet: DeleteExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request experimentsClient.DeleteExperiment(name); // End snippet } /// <summary>Snippet for DeleteExperimentAsync</summary> public async Task DeleteExperimentResourceNamesAsync() { // Snippet: DeleteExperimentAsync(ExperimentName, CallSettings) // Additional: DeleteExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request await experimentsClient.DeleteExperimentAsync(name); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperimentRequestObject() { // Snippet: StartExperiment(StartExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) StartExperimentRequest request = new StartExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.StartExperiment(request); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentRequestObjectAsync() { // Snippet: StartExperimentAsync(StartExperimentRequest, CallSettings) // Additional: StartExperimentAsync(StartExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) StartExperimentRequest request = new StartExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.StartExperimentAsync(request); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperiment() { // Snippet: StartExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.StartExperiment(name); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentAsync() { // Snippet: StartExperimentAsync(string, CallSettings) // Additional: StartExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.StartExperimentAsync(name); // End snippet } /// <summary>Snippet for StartExperiment</summary> public void StartExperimentResourceNames() { // Snippet: StartExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.StartExperiment(name); // End snippet } /// <summary>Snippet for StartExperimentAsync</summary> public async Task StartExperimentResourceNamesAsync() { // Snippet: StartExperimentAsync(ExperimentName, CallSettings) // Additional: StartExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.StartExperimentAsync(name); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperimentRequestObject() { // Snippet: StopExperiment(StopExperimentRequest, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) StopExperimentRequest request = new StopExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = experimentsClient.StopExperiment(request); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentRequestObjectAsync() { // Snippet: StopExperimentAsync(StopExperimentRequest, CallSettings) // Additional: StopExperimentAsync(StopExperimentRequest, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) StopExperimentRequest request = new StopExperimentRequest { ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"), }; // Make the request Experiment response = await experimentsClient.StopExperimentAsync(request); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperiment() { // Snippet: StopExperiment(string, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = experimentsClient.StopExperiment(name); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentAsync() { // Snippet: StopExperimentAsync(string, CallSettings) // Additional: StopExperimentAsync(string, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/experiments/[EXPERIMENT]"; // Make the request Experiment response = await experimentsClient.StopExperimentAsync(name); // End snippet } /// <summary>Snippet for StopExperiment</summary> public void StopExperimentResourceNames() { // Snippet: StopExperiment(ExperimentName, CallSettings) // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = experimentsClient.StopExperiment(name); // End snippet } /// <summary>Snippet for StopExperimentAsync</summary> public async Task StopExperimentResourceNamesAsync() { // Snippet: StopExperimentAsync(ExperimentName, CallSettings) // Additional: StopExperimentAsync(ExperimentName, CancellationToken) // Create client ExperimentsClient experimentsClient = await ExperimentsClient.CreateAsync(); // Initialize request argument(s) ExperimentName name = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"); // Make the request Experiment response = await experimentsClient.StopExperimentAsync(name); // End snippet } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security; [SecuritySafeCritical] public struct TestStruct { public int TestInt; } [SecuritySafeCritical] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TestUnicodeStringStruct { public string TestString; } [SecuritySafeCritical] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct TestAnsiStringStruct { public string TestString; } [SecuritySafeCritical] public struct TestMultiMemberStruct1 { public double TestDouble; public int TestInt; } [SecuritySafeCritical] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TestMultiMemberStruct2 { public int TestInt; public string TestString; } [SecuritySafeCritical] public struct TestMultiStructs1 { public float TestFloat; public TestUnicodeStringStruct TestUnicodeStringStruct; } [SecuritySafeCritical] public struct TestMultiStructs2 { public float TestFloat; public TestMultiMemberStruct2 TestMultiMemberStruct2; } [SecuritySafeCritical] public enum TestEnum { ENUM_VALUE1, ENUM_VALUE2 } [SecuritySafeCritical] public struct TestGenericStruct<T> { public T TestVal; } /// <summary> /// SizeOf(System.Object) /// </summary> [SecuritySafeCritical] public class MarshalSizeOf1 { #region Private Fields private const int c_STRING_MIN_LENGTH = 1; private const int c_STRING_MAX_LENGTH = 1024; #endregion private int NextHighestMultipleOf(int n, int k) { return k * ((int)Math.Ceiling( ((double)n) / ((double)k))); } #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Get size of an instance of struct contains one field"); try { TestStruct obj = new TestStruct(); obj.TestInt = TestLibrary.Generator.GetInt32(-55); int expectedSize = 4; int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("001.1", "Get size of an instance of struct contains one field returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Get size of an instance of struct contains unicode string field"); try { TestUnicodeStringStruct obj = new TestUnicodeStringStruct(); string randValue = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH); obj.TestString = randValue; int expectedSize = IntPtr.Size; int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("002.1", "Get size of an instance of struct contains unicode string field returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", randValue = " + randValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Get size of an instance of struct contains ansi string field"); try { TestAnsiStringStruct obj = new TestAnsiStringStruct(); string randValue = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH); obj.TestString = randValue; int expectedSize = IntPtr.Size; int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("003.1", "Get size of an instance of struct contains ansi string field returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", randValue = " + randValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Get size of an instance of struct contains multiple fields"); try { TestMultiMemberStruct1 obj = new TestMultiMemberStruct1(); obj.TestInt = TestLibrary.Generator.GetInt32(-55); obj.TestDouble = TestLibrary.Generator.GetDouble(-55); int expectedSize = 16; // sizeof(double) + sizeof(int) + padding int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("004.1", "Get size of an instance of struct contains multiple fields returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt + ", obj.TestDouble = " + obj.TestDouble); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Get size of an instance of struct contains value type and reference type fields"); try { TestMultiMemberStruct2 obj = new TestMultiMemberStruct2(); obj.TestInt = TestLibrary.Generator.GetInt32(-55); obj.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH); int expectedSize = NextHighestMultipleOf(Marshal.SizeOf(typeof(int)) + IntPtr.Size , TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(object) + sizeof(int) int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("005.1", "Get size of an instance of struct contains value type and reference type fields returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestInt = " + obj.TestInt + ", obj.TestString = " + obj.TestString); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Get size of an instance of struct contains nested one field struct"); try { TestMultiStructs1 obj = new TestMultiStructs1(); obj.TestFloat = TestLibrary.Generator.GetSingle(-55); obj.TestUnicodeStringStruct.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH); int expectedSize = NextHighestMultipleOf(IntPtr.Size + Marshal.SizeOf(typeof(int)), TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(string) + sizeof(int) int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("006.1", "Get size of an instance of struct contains nested one field struct returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestFloat = " + obj.TestFloat + ", obj.TestUnicodeStringStruct.TestString = " + obj.TestUnicodeStringStruct.TestString); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Get size of an instance of struct contains nested multiple fields struct"); try { TestMultiStructs2 obj = new TestMultiStructs2(); obj.TestFloat = TestLibrary.Generator.GetSingle(-55); obj.TestMultiMemberStruct2.TestInt = TestLibrary.Generator.GetInt32(-55); obj.TestMultiMemberStruct2.TestString = TestLibrary.Generator.GetString(-55, false, c_STRING_MIN_LENGTH, c_STRING_MAX_LENGTH); int expectedSize = NextHighestMultipleOf(Marshal.SizeOf(typeof(TestMultiMemberStruct2)) + Marshal.SizeOf(typeof(float)), TestLibrary.Utilities.Is64 ? 8 : 4); // sizeof(int) + sizeof(float) + sizeof(string) int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("007.1", "Get size of an instance of struct contains nested multiple fields struct returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestFloat = " + obj.TestFloat + ", obj.TestMultiMemberStruct2.TestInt = " + obj.TestMultiMemberStruct2.TestInt + ", obj.TestMultiMemberStruct2.TestString = " + obj.TestMultiMemberStruct2.TestString); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("007.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8: Get size of an instance of value type"); try { int obj = TestLibrary.Generator.GetInt32(-55); int expectedSize = 4; int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("008.1", "Get size of an instance of value type returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj = " + obj); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest9: Get size of an instance of generic struct type"); try { TestGenericStruct<int> obj = new TestGenericStruct<int>(); obj.TestVal = TestLibrary.Generator.GetInt32(-55); int expectedSize = 4; int actualSize = Marshal.SizeOf(obj); if (expectedSize != actualSize) { TestLibrary.TestFramework.LogError("009.1", "Get size of an instance of generic struct type returns wrong size"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expectedSize = " + expectedSize + ", actualSize = " + actualSize + ", obj.TestVal = " + obj.TestVal); retVal = false; } } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("009.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException should be thrown when The structure parameter is a null reference."); try { int size = Marshal.SizeOf(null); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when The structure parameter is a null reference."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentException should be thrown when the value is a enum type"); try { TestEnum obj = TestEnum.ENUM_VALUE1; int size = Marshal.SizeOf(obj); TestLibrary.TestFramework.LogError("102.1", "ArgumentException is not thrown when the value is a enum type"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when the value is a reference type"); try { Object obj = new Object(); int size = Marshal.SizeOf(obj); TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown when the value is a reference type"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { MarshalSizeOf1 test = new MarshalSizeOf1(); TestLibrary.TestFramework.BeginTestCase("MarshalSizeOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaDivideNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableFloat(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableLong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableShort(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableULong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaDivideNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private enum ResultType { Success, DivideByZero, Overflow } #region Verify decimal? private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { bool divideByZero; decimal? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a / b; } ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1"); // verify with parameters supplied Expression<Func<decimal?>> e1 = Expression.Lambda<Func<decimal?>>( Expression.Invoke( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 = Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>( Expression.Lambda<Func<decimal?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 = Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<decimal?, decimal?>>> e6 = Expression.Lambda<Func<Func<decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify double? private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter) { double? expected = a / b; ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1"); // verify with parameters supplied Expression<Func<double?>> e1 = Expression.Lambda<Func<double?>>( Expression.Invoke( Expression.Lambda<Func<double?, double?, double?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<double?, double?, Func<double?>>> e2 = Expression.Lambda<Func<double?, double?, Func<double?>>>( Expression.Lambda<Func<double?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<double?, double?, double?>>> e3 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<double?, double?, double?>>> e4 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<double?, Func<double?, double?>>> e5 = Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<double?, double?>>> e6 = Expression.Lambda<Func<Func<double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?, double?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify float? private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter) { float? expected = a / b; ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1"); // verify with parameters supplied Expression<Func<float?>> e1 = Expression.Lambda<Func<float?>>( Expression.Invoke( Expression.Lambda<Func<float?, float?, float?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<float?, float?, Func<float?>>> e2 = Expression.Lambda<Func<float?, float?, Func<float?>>>( Expression.Lambda<Func<float?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<float?, float?, float?>>> e3 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<float?, float?, float?>>> e4 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<float?, Func<float?, float?>>> e5 = Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<float?, float?>>> e6 = Expression.Lambda<Func<Func<float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?, float?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify int? private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter) { ResultType outcome; int? expected = null; if (a.HasValue && b == 0) { outcome = ResultType.DivideByZero; } else if (a == int.MinValue && b == -1) { outcome = ResultType.Overflow; } else { expected = a / b; outcome = ResultType.Success; } ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1"); // verify with parameters supplied Expression<Func<int?>> e1 = Expression.Lambda<Func<int?>>( Expression.Invoke( Expression.Lambda<Func<int?, int?, int?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?> f1 = e1.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f1()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f1()); break; default: Assert.Equal(expected, f1()); break; } // verify with values passed to make parameters Expression<Func<int?, int?, Func<int?>>> e2 = Expression.Lambda<Func<int?, int?, Func<int?>>>( Expression.Lambda<Func<int?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f2(a, b)()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f2(a, b)()); break; default: Assert.Equal(expected, f2(a, b)()); break; } // verify with values directly passed Expression<Func<Func<int?, int?, int?>>> e3 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f3(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f3(a, b)); break; default: Assert.Equal(expected, f3(a, b)); break; } // verify as a function generator Expression<Func<Func<int?, int?, int?>>> e4 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f4()(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f4()(a, b)); break; default: Assert.Equal(expected, f4()(a, b)); break; } // verify with currying Expression<Func<int?, Func<int?, int?>>> e5 = Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f5(a)(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f5(a)(b)); break; default: Assert.Equal(expected, f5(a)(b)); break; } // verify with one parameter Expression<Func<Func<int?, int?>>> e6 = Expression.Lambda<Func<Func<int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?, int?> f6 = e6.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f6(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f6(b)); break; default: Assert.Equal(expected, f6(b)); break; } } #endregion #region Verify long? private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter) { ResultType outcome; long? expected = null; if (a.HasValue && b == 0) { outcome = ResultType.DivideByZero; } else if (a == long.MinValue && b == -1) { outcome = ResultType.Overflow; } else { expected = a / b; outcome = ResultType.Success; } ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1"); // verify with parameters supplied Expression<Func<long?>> e1 = Expression.Lambda<Func<long?>>( Expression.Invoke( Expression.Lambda<Func<long?, long?, long?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?> f1 = e1.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f1()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f1()); break; default: Assert.Equal(expected, f1()); break; } // verify with values passed to make parameters Expression<Func<long?, long?, Func<long?>>> e2 = Expression.Lambda<Func<long?, long?, Func<long?>>>( Expression.Lambda<Func<long?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f2(a, b)()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f2(a, b)()); break; default: Assert.Equal(expected, f2(a, b)()); break; } // verify with values directly passed Expression<Func<Func<long?, long?, long?>>> e3 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f3(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f3(a, b)); break; default: Assert.Equal(expected, f3(a, b)); break; } // verify as a function generator Expression<Func<Func<long?, long?, long?>>> e4 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f4()(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f4()(a, b)); break; default: Assert.Equal(expected, f4()(a, b)); break; } // verify with currying Expression<Func<long?, Func<long?, long?>>> e5 = Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f5(a)(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f5(a)(b)); break; default: Assert.Equal(expected, f5(a)(b)); break; } // verify with one parameter Expression<Func<Func<long?, long?>>> e6 = Expression.Lambda<Func<Func<long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?, long?> f6 = e6.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f6(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f6(b)); break; default: Assert.Equal(expected, f6(b)); break; } } #endregion #region Verify short? private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter) { bool divideByZero; short? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = unchecked((short?)(a / b)); } ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1"); // verify with parameters supplied Expression<Func<short?>> e1 = Expression.Lambda<Func<short?>>( Expression.Invoke( Expression.Lambda<Func<short?, short?, short?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<short?, short?, Func<short?>>> e2 = Expression.Lambda<Func<short?, short?, Func<short?>>>( Expression.Lambda<Func<short?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<short?, short?, short?>>> e3 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<short?, short?, short?>>> e4 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<short?, Func<short?, short?>>> e5 = Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<short?, short?>>> e6 = Expression.Lambda<Func<Func<short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?, short?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify uint? private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter) { bool divideByZero; uint? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a / b; } ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1"); // verify with parameters supplied Expression<Func<uint?>> e1 = Expression.Lambda<Func<uint?>>( Expression.Invoke( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<uint?, uint?, Func<uint?>>> e2 = Expression.Lambda<Func<uint?, uint?, Func<uint?>>>( Expression.Lambda<Func<uint?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<uint?, uint?, uint?>>> e3 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<uint?, uint?, uint?>>> e4 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<uint?, Func<uint?, uint?>>> e5 = Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<uint?, uint?>>> e6 = Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify ulong? private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter) { bool divideByZero; ulong? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a / b; } ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1"); // verify with parameters supplied Expression<Func<ulong?>> e1 = Expression.Lambda<Func<ulong?>>( Expression.Invoke( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 = Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>( Expression.Lambda<Func<ulong?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 = Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<ulong?, ulong?>>> e6 = Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify ushort? private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter) { bool divideByZero; ushort? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = (ushort?)(a / b); } ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1"); // verify with parameters supplied Expression<Func<ushort?>> e1 = Expression.Lambda<Func<ushort?>>( Expression.Invoke( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 = Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>( Expression.Lambda<Func<ushort?>>( Expression.Divide(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 = Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<ushort?, ushort?>>> e6 = Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Divide(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #endregion } }
// // Copyright (C) DataStax 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. // using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Cassandra.IntegrationTests.SimulacronAPI; using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement.Simulacron; using Cassandra.Tests; using Newtonsoft.Json; using NUnit.Framework; namespace Cassandra.IntegrationTests.Policies.Tests { [TestFixture, Category(TestCategory.Short)] public class RetryPolicyShortTests : TestGlobals { public static object[] RetryPolicyExtendedData = { new object[] { ServerError.IsBootstrapping, typeof(IsBootstrappingException) }, new object[] { ServerError.Overloaded, typeof(OverloadedException) } }; [TestCaseSource(nameof(RetryPolicyShortTests.RetryPolicyExtendedData))] public void RetryPolicy_Extended(ServerError resultError, Type exceptionType) { using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions())) { var contactPoint = simulacronCluster.InitialContactPoint; var extendedRetryPolicy = new TestExtendedRetryPolicy(); var builder = ClusterBuilder() .AddContactPoint(contactPoint) .WithRetryPolicy(extendedRetryPolicy) .WithReconnectionPolicy(new ConstantReconnectionPolicy(long.MaxValue)); using (var cluster = builder.Build()) { var session = (Session)cluster.Connect(); const string cql = "select * from table1"; simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenServerError(resultError, resultError.Value)); Exception throwedException = null; try { session.Execute(cql); } catch (Exception ex) { throwedException = ex; } finally { Assert.NotNull(throwedException); Assert.AreEqual(throwedException.GetType(), exceptionType); Assert.AreEqual(1, Interlocked.Read(ref extendedRetryPolicy.RequestErrorConter)); Assert.AreEqual(0, Interlocked.Read(ref extendedRetryPolicy.ReadTimeoutCounter)); Assert.AreEqual(0, Interlocked.Read(ref extendedRetryPolicy.WriteTimeoutCounter)); Assert.AreEqual(0, Interlocked.Read(ref extendedRetryPolicy.UnavailableCounter)); } } } } [TestCase(true)] [TestCase(false)] [Test] public async Task Should_RetryOnNextHost_When_SendFailsOnCurrentHostRetryPolicy(bool async) { using (var simulacronCluster = SimulacronCluster.CreateNew(3)) { var contactPoint = simulacronCluster.InitialContactPoint; var nodes = simulacronCluster.GetNodes().ToArray(); var queryPlan = new List<SimulacronNode> { nodes[1], nodes[2], nodes[0] }; await queryPlan[0].Stop().ConfigureAwait(false); var currentHostRetryPolicy = new CurrentHostRetryPolicy(10, null); var loadBalancingPolicy = new CustomLoadBalancingPolicy( queryPlan.Select(n => n.ContactPoint).ToArray()); var builder = ClusterBuilder() .AddContactPoint(contactPoint) .WithSocketOptions(new SocketOptions() .SetConnectTimeoutMillis(10000) .SetReadTimeoutMillis(5000)) .WithLoadBalancingPolicy(loadBalancingPolicy) .WithRetryPolicy(currentHostRetryPolicy); using (var cluster = builder.Build()) { var session = (Session)cluster.Connect(); const string cql = "select * from table2"; queryPlan[1].PrimeFluent( b => b.WhenQuery(cql). ThenRowsSuccess(new[] { ("text", DataType.Ascii) }, rows => rows.WithRow("test1").WithRow("test2"))); if (async) { await session.ExecuteAsync( new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.One)).ConfigureAwait(false); } else { session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.One)); } var queriesFirstNode = await queryPlan[0].GetQueriesAsync(cql).ConfigureAwait(false); var queriesFirstNodeString = string.Join(Environment.NewLine, queriesFirstNode.Select<dynamic, string>(obj => JsonConvert.SerializeObject(obj))); var queriesSecondNode = await queryPlan[1].GetQueriesAsync(cql).ConfigureAwait(false); var queriesSecondNodeString = string.Join(Environment.NewLine, queriesSecondNode.Select<dynamic, string>(obj => JsonConvert.SerializeObject(obj))); var queriesThirdNode = await queryPlan[2].GetQueriesAsync(cql).ConfigureAwait(false); var queriesThirdNodeString = string.Join(Environment.NewLine, queriesThirdNode.Select<dynamic, string>(obj => JsonConvert.SerializeObject(obj))); var allQueries = new { First = queriesFirstNodeString, Second = queriesSecondNodeString, Third = queriesThirdNodeString }; var allQueriesString = JsonConvert.SerializeObject(allQueries); Assert.AreEqual(0, currentHostRetryPolicy.RequestErrorCounter, allQueriesString); Assert.AreEqual(0, queriesFirstNode.Count, allQueriesString); Assert.AreEqual(1, queriesSecondNode.Count, allQueriesString); Assert.AreEqual(0, queriesThirdNode.Count, allQueriesString); } } } [TestCase(true)] [TestCase(false)] [Test] public async Task Should_KeepRetryingOnSameHost_When_CurrentHostRetryPolicyIsSetAndSendSucceeds(bool async) { using (var simulacronCluster = SimulacronCluster.CreateNew(3)) { var contactPoint = simulacronCluster.InitialContactPoint; var nodes = simulacronCluster.GetNodes().ToArray(); var currentHostRetryPolicy = new CurrentHostRetryPolicy(10, null); var loadBalancingPolicy = new CustomLoadBalancingPolicy( nodes.Select(n => n.ContactPoint).ToArray()); var builder = ClusterBuilder() .AddContactPoint(contactPoint) .WithSocketOptions(new SocketOptions() .SetConnectTimeoutMillis(10000) .SetReadTimeoutMillis(5000)) .WithLoadBalancingPolicy(loadBalancingPolicy) .WithRetryPolicy(currentHostRetryPolicy); using (var cluster = builder.Build()) { var session = (Session)cluster.Connect(); const string cql = "select * from table2"; nodes[0].PrimeFluent( b => b.WhenQuery(cql). ThenOverloaded("overloaded")); nodes[1].PrimeFluent( b => b.WhenQuery(cql). ThenRowsSuccess(new[] { ("text", DataType.Ascii) }, rows => rows.WithRow("test1").WithRow("test2"))); if (async) { Assert.ThrowsAsync<OverloadedException>(() => session.ExecuteAsync(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.One))); } else { Assert.Throws<OverloadedException>(() => session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.One))); } Assert.AreEqual(11, currentHostRetryPolicy.RequestErrorCounter); Assert.AreEqual(12, (await nodes[0].GetQueriesAsync(cql).ConfigureAwait(false)).Count); Assert.AreEqual(0, (await nodes[1].GetQueriesAsync(cql).ConfigureAwait(false)).Count); Assert.AreEqual(0, (await nodes[2].GetQueriesAsync(cql).ConfigureAwait(false)).Count); } } } private class TestExtendedRetryPolicy : IExtendedRetryPolicy { public long ReadTimeoutCounter; public long WriteTimeoutCounter; public long UnavailableCounter; public long RequestErrorConter; public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { Interlocked.Increment(ref ReadTimeoutCounter); return RetryDecision.Rethrow(); } public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry) { Interlocked.Increment(ref WriteTimeoutCounter); return RetryDecision.Rethrow(); } public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { Interlocked.Increment(ref UnavailableCounter); return RetryDecision.Rethrow(); } public RetryDecision OnRequestError(IStatement statement, Configuration config, Exception ex, int nbRetry) { Interlocked.Increment(ref RequestErrorConter); return RetryDecision.Rethrow(); } } private class CurrentHostRetryPolicy : IExtendedRetryPolicy { private readonly int _maxRetries; private readonly Func<int, Task> _action; public long RequestErrorCounter; public CurrentHostRetryPolicy(int maxRetries, Func<int, Task> action) { _maxRetries = maxRetries; _action = action; } public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { return RetryDecision.Rethrow(); } public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry) { return RetryDecision.Rethrow(); } public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { return RetryDecision.Rethrow(); } public RetryDecision OnRequestError(IStatement statement, Configuration config, Exception ex, int nbRetry) { _action?.Invoke(nbRetry).GetAwaiter().GetResult(); if (nbRetry > _maxRetries) { return RetryDecision.Rethrow(); } Interlocked.Increment(ref RequestErrorCounter); return RetryDecision.Retry(null, true); } } private class CustomLoadBalancingPolicy : ILoadBalancingPolicy { private ICluster _cluster; private readonly string[] _hosts; public CustomLoadBalancingPolicy(string[] hosts) { _hosts = hosts; } public void Initialize(ICluster cluster) { _cluster = cluster; } public HostDistance Distance(Host host) { return HostDistance.Local; } public IEnumerable<Host> NewQueryPlan(string keyspace, IStatement query) { var queryPlan = new List<Host>(); var allHosts = _cluster.AllHosts(); foreach (var host in _hosts) { queryPlan.Add(allHosts.Single(h => h.Address.ToString() == host)); } return queryPlan; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; public class Interpolate { public enum EaseType { Linear, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInSine, EaseOutSine, EaseInOutSine, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc } public delegate Vector3 ToVector3<T>(T v); public delegate float Function(float a, float b, float c, float d); private static Vector3 Identity(Vector3 v) { return v; } private static Vector3 TransformDotPosition(Transform t) { return t.position; } [DebuggerHidden] private static IEnumerable<float> NewTimer(float duration) { Interpolate.<NewTimer>c__Iterator11 <NewTimer>c__Iterator = new Interpolate.<NewTimer>c__Iterator11(); <NewTimer>c__Iterator.duration = duration; <NewTimer>c__Iterator.<$>duration = duration; Interpolate.<NewTimer>c__Iterator11 expr_15 = <NewTimer>c__Iterator; expr_15.$PC = -2; return expr_15; } [DebuggerHidden] private static IEnumerable<float> NewCounter(int start, int end, int step) { Interpolate.<NewCounter>c__Iterator12 <NewCounter>c__Iterator = new Interpolate.<NewCounter>c__Iterator12(); <NewCounter>c__Iterator.start = start; <NewCounter>c__Iterator.end = end; <NewCounter>c__Iterator.step = step; <NewCounter>c__Iterator.<$>start = start; <NewCounter>c__Iterator.<$>end = end; <NewCounter>c__Iterator.<$>step = step; Interpolate.<NewCounter>c__Iterator12 expr_31 = <NewCounter>c__Iterator; expr_31.$PC = -2; return expr_31; } public static IEnumerator NewEase(Interpolate.Function ease, Vector3 start, Vector3 end, float duration) { IEnumerable<float> driver = Interpolate.NewTimer(duration); return Interpolate.NewEase(ease, start, end, duration, driver); } public static IEnumerator NewEase(Interpolate.Function ease, Vector3 start, Vector3 end, int slices) { IEnumerable<float> driver = Interpolate.NewCounter(0, slices + 1, 1); return Interpolate.NewEase(ease, start, end, (float)(slices + 1), driver); } [DebuggerHidden] private static IEnumerator NewEase(Interpolate.Function ease, Vector3 start, Vector3 end, float total, IEnumerable<float> driver) { Interpolate.<NewEase>c__Iterator13 <NewEase>c__Iterator = new Interpolate.<NewEase>c__Iterator13(); <NewEase>c__Iterator.end = end; <NewEase>c__Iterator.start = start; <NewEase>c__Iterator.driver = driver; <NewEase>c__Iterator.ease = ease; <NewEase>c__Iterator.total = total; <NewEase>c__Iterator.<$>end = end; <NewEase>c__Iterator.<$>start = start; <NewEase>c__Iterator.<$>driver = driver; <NewEase>c__Iterator.<$>ease = ease; <NewEase>c__Iterator.<$>total = total; return <NewEase>c__Iterator; } private static Vector3 Ease(Interpolate.Function ease, Vector3 start, Vector3 distance, float elapsedTime, float duration) { start.x = ease(start.x, distance.x, elapsedTime, duration); start.y = ease(start.y, distance.y, elapsedTime, duration); start.z = ease(start.z, distance.z, elapsedTime, duration); return start; } public static Interpolate.Function Ease(Interpolate.EaseType type) { Interpolate.Function result = null; switch (type) { case Interpolate.EaseType.Linear: result = new Interpolate.Function(Interpolate.Linear); break; case Interpolate.EaseType.EaseInQuad: result = new Interpolate.Function(Interpolate.EaseInQuad); break; case Interpolate.EaseType.EaseOutQuad: result = new Interpolate.Function(Interpolate.EaseOutQuad); break; case Interpolate.EaseType.EaseInOutQuad: result = new Interpolate.Function(Interpolate.EaseInOutQuad); break; case Interpolate.EaseType.EaseInCubic: result = new Interpolate.Function(Interpolate.EaseInCubic); break; case Interpolate.EaseType.EaseOutCubic: result = new Interpolate.Function(Interpolate.EaseOutCubic); break; case Interpolate.EaseType.EaseInOutCubic: result = new Interpolate.Function(Interpolate.EaseInOutCubic); break; case Interpolate.EaseType.EaseInQuart: result = new Interpolate.Function(Interpolate.EaseInQuart); break; case Interpolate.EaseType.EaseOutQuart: result = new Interpolate.Function(Interpolate.EaseOutQuart); break; case Interpolate.EaseType.EaseInOutQuart: result = new Interpolate.Function(Interpolate.EaseInOutQuart); break; case Interpolate.EaseType.EaseInQuint: result = new Interpolate.Function(Interpolate.EaseInQuint); break; case Interpolate.EaseType.EaseOutQuint: result = new Interpolate.Function(Interpolate.EaseOutQuint); break; case Interpolate.EaseType.EaseInOutQuint: result = new Interpolate.Function(Interpolate.EaseInOutQuint); break; case Interpolate.EaseType.EaseInSine: result = new Interpolate.Function(Interpolate.EaseInSine); break; case Interpolate.EaseType.EaseOutSine: result = new Interpolate.Function(Interpolate.EaseOutSine); break; case Interpolate.EaseType.EaseInOutSine: result = new Interpolate.Function(Interpolate.EaseInOutSine); break; case Interpolate.EaseType.EaseInExpo: result = new Interpolate.Function(Interpolate.EaseInExpo); break; case Interpolate.EaseType.EaseOutExpo: result = new Interpolate.Function(Interpolate.EaseOutExpo); break; case Interpolate.EaseType.EaseInOutExpo: result = new Interpolate.Function(Interpolate.EaseInOutExpo); break; case Interpolate.EaseType.EaseInCirc: result = new Interpolate.Function(Interpolate.EaseInCirc); break; case Interpolate.EaseType.EaseOutCirc: result = new Interpolate.Function(Interpolate.EaseOutCirc); break; case Interpolate.EaseType.EaseInOutCirc: result = new Interpolate.Function(Interpolate.EaseInOutCirc); break; } return result; } public static IEnumerable<Vector3> NewBezier(Interpolate.Function ease, Transform[] nodes, float duration) { IEnumerable<float> steps = Interpolate.NewTimer(duration); return Interpolate.NewBezier<Transform>(ease, nodes, new Interpolate.ToVector3<Transform>(Interpolate.TransformDotPosition), duration, steps); } public static IEnumerable<Vector3> NewBezier(Interpolate.Function ease, Transform[] nodes, int slices) { IEnumerable<float> steps = Interpolate.NewCounter(0, slices + 1, 1); return Interpolate.NewBezier<Transform>(ease, nodes, new Interpolate.ToVector3<Transform>(Interpolate.TransformDotPosition), (float)(slices + 1), steps); } public static IEnumerable<Vector3> NewBezier(Interpolate.Function ease, Vector3[] points, float duration) { IEnumerable<float> steps = Interpolate.NewTimer(duration); return Interpolate.NewBezier<Vector3>(ease, points, new Interpolate.ToVector3<Vector3>(Interpolate.Identity), duration, steps); } public static IEnumerable<Vector3> NewBezier(Interpolate.Function ease, Vector3[] points, int slices) { IEnumerable<float> steps = Interpolate.NewCounter(0, slices + 1, 1); return Interpolate.NewBezier<Vector3>(ease, points, new Interpolate.ToVector3<Vector3>(Interpolate.Identity), (float)(slices + 1), steps); } [DebuggerHidden] private static IEnumerable<Vector3> NewBezier<T>(Interpolate.Function ease, IList nodes, Interpolate.ToVector3<T> toVector3, float maxStep, IEnumerable<float> steps) { Interpolate.<NewBezier>c__Iterator14<T> <NewBezier>c__Iterator = new Interpolate.<NewBezier>c__Iterator14<T>(); <NewBezier>c__Iterator.nodes = nodes; <NewBezier>c__Iterator.steps = steps; <NewBezier>c__Iterator.toVector3 = toVector3; <NewBezier>c__Iterator.ease = ease; <NewBezier>c__Iterator.maxStep = maxStep; <NewBezier>c__Iterator.<$>nodes = nodes; <NewBezier>c__Iterator.<$>steps = steps; <NewBezier>c__Iterator.<$>toVector3 = toVector3; <NewBezier>c__Iterator.<$>ease = ease; <NewBezier>c__Iterator.<$>maxStep = maxStep; Interpolate.<NewBezier>c__Iterator14<T> expr_4F = <NewBezier>c__Iterator; expr_4F.$PC = -2; return expr_4F; } private static Vector3 Bezier(Interpolate.Function ease, Vector3[] points, float elapsedTime, float duration) { for (int i = points.Length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { points[j].x = ease(points[j].x, points[j + 1].x - points[j].x, elapsedTime, duration); points[j].y = ease(points[j].y, points[j + 1].y - points[j].y, elapsedTime, duration); points[j].z = ease(points[j].z, points[j + 1].z - points[j].z, elapsedTime, duration); } } return points[0]; } public static IEnumerable<Vector3> NewCatmullRom(Transform[] nodes, int slices, bool loop) { return Interpolate.NewCatmullRom<Transform>(nodes, new Interpolate.ToVector3<Transform>(Interpolate.TransformDotPosition), slices, loop); } public static IEnumerable<Vector3> NewCatmullRom(Vector3[] points, int slices, bool loop) { return Interpolate.NewCatmullRom<Vector3>(points, new Interpolate.ToVector3<Vector3>(Interpolate.Identity), slices, loop); } [DebuggerHidden] private static IEnumerable<Vector3> NewCatmullRom<T>(IList nodes, Interpolate.ToVector3<T> toVector3, int slices, bool loop) { Interpolate.<NewCatmullRom>c__Iterator15<T> <NewCatmullRom>c__Iterator = new Interpolate.<NewCatmullRom>c__Iterator15<T>(); <NewCatmullRom>c__Iterator.nodes = nodes; <NewCatmullRom>c__Iterator.toVector3 = toVector3; <NewCatmullRom>c__Iterator.loop = loop; <NewCatmullRom>c__Iterator.slices = slices; <NewCatmullRom>c__Iterator.<$>nodes = nodes; <NewCatmullRom>c__Iterator.<$>toVector3 = toVector3; <NewCatmullRom>c__Iterator.<$>loop = loop; <NewCatmullRom>c__Iterator.<$>slices = slices; Interpolate.<NewCatmullRom>c__Iterator15<T> expr_3F = <NewCatmullRom>c__Iterator; expr_3F.$PC = -2; return expr_3F; } private static Vector3 CatmullRom(Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime, float duration) { float num = elapsedTime / duration; float num2 = num * num; float num3 = num2 * num; return previous * (-0.5f * num3 + num2 - 0.5f * num) + start * (1.5f * num3 + -2.5f * num2 + 1f) + end * (-1.5f * num3 + 2f * num2 + 0.5f * num) + next * (0.5f * num3 - 0.5f * num2); } private static float Linear(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * (elapsedTime / duration) + start; } private static float EaseInQuad(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return distance * elapsedTime * elapsedTime + start; } private static float EaseOutQuad(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return -distance * elapsedTime * (elapsedTime - 2f) + start; } private static float EaseInOutQuad(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return distance / 2f * elapsedTime * elapsedTime + start; } elapsedTime -= 1f; return -distance / 2f * (elapsedTime * (elapsedTime - 2f) - 1f) + start; } private static float EaseInCubic(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return distance * elapsedTime * elapsedTime * elapsedTime + start; } private static float EaseOutCubic(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); elapsedTime -= 1f; return distance * (elapsedTime * elapsedTime * elapsedTime + 1f) + start; } private static float EaseInOutCubic(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return distance / 2f * elapsedTime * elapsedTime * elapsedTime + start; } elapsedTime -= 2f; return distance / 2f * (elapsedTime * elapsedTime * elapsedTime + 2f) + start; } private static float EaseInQuart(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } private static float EaseOutQuart(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); elapsedTime -= 1f; return -distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 1f) + start; } private static float EaseInOutQuart(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return distance / 2f * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } elapsedTime -= 2f; return -distance / 2f * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 2f) + start; } private static float EaseInQuint(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } private static float EaseOutQuint(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); elapsedTime -= 1f; return distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 1f) + start; } private static float EaseInOutQuint(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return distance / 2f * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } elapsedTime -= 2f; return distance / 2f * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 2f) + start; } private static float EaseInSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return -distance * Mathf.Cos(elapsedTime / duration * 1.57079637f) + distance + start; } private static float EaseOutSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Sin(elapsedTime / duration * 1.57079637f) + start; } private static float EaseInOutSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return -distance / 2f * (Mathf.Cos(3.14159274f * elapsedTime / duration) - 1f) + start; } private static float EaseInExpo(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Pow(2f, 10f * (elapsedTime / duration - 1f)) + start; } private static float EaseOutExpo(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * (-Mathf.Pow(2f, -10f * elapsedTime / duration) + 1f) + start; } private static float EaseInOutExpo(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return distance / 2f * Mathf.Pow(2f, 10f * (elapsedTime - 1f)) + start; } elapsedTime -= 1f; return distance / 2f * (-Mathf.Pow(2f, -10f * elapsedTime) + 2f) + start; } private static float EaseInCirc(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); return -distance * (Mathf.Sqrt(1f - elapsedTime * elapsedTime) - 1f) + start; } private static float EaseOutCirc(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / duration) : 1f); elapsedTime -= 1f; return distance * Mathf.Sqrt(1f - elapsedTime * elapsedTime) + start; } private static float EaseInOutCirc(float start, float distance, float elapsedTime, float duration) { elapsedTime = ((elapsedTime <= duration) ? (elapsedTime / (duration / 2f)) : 2f); if (elapsedTime < 1f) { return -distance / 2f * (Mathf.Sqrt(1f - elapsedTime * elapsedTime) - 1f) + start; } elapsedTime -= 2f; return distance / 2f * (Mathf.Sqrt(1f - elapsedTime * elapsedTime) + 1f) + start; } }
// 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\General\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt320() { var test = new VectorGetAndWithElement__GetAndWithElementUInt320(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt320 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector64<UInt32> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { UInt32 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { Vector64<UInt32> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector64<UInt32> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt32)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<UInt32>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt32 result, UInt32[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<UInt32> result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt32[] result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #pragma warning disable xUnit2004 //assert.True can't be used with Object parameter namespace NLog.UnitTests.Conditions { using System; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using NLog.Conditions; using NLog.Config; using Xunit; public class ConditionEvaluatorTests : NLogTestBase { [Fact] public void BooleanOperatorTest() { AssertEvaluationResult(false, "false or false"); AssertEvaluationResult(true, "false or true"); AssertEvaluationResult(true, "true or false"); AssertEvaluationResult(true, "true or true"); AssertEvaluationResult(false, "false and false"); AssertEvaluationResult(false, "false and true"); AssertEvaluationResult(false, "true and false"); AssertEvaluationResult(true, "true and true"); AssertEvaluationResult(false, "not true"); AssertEvaluationResult(true, "not false"); AssertEvaluationResult(false, "not not false"); AssertEvaluationResult(true, "not not true"); } [Fact] public void ConditionMethodsTest() { AssertEvaluationResult(true, "starts-with('foobar','foo')"); AssertEvaluationResult(false, "starts-with('foobar','bar')"); AssertEvaluationResult(true, "ends-with('foobar','bar')"); AssertEvaluationResult(false, "ends-with('foobar','foo')"); AssertEvaluationResult(0, "length('')"); AssertEvaluationResult(4, "length('${level}')"); AssertEvaluationResult(false, "equals(1, 2)"); AssertEvaluationResult(true, "equals(3.14, 3.14)"); AssertEvaluationResult(true, "contains('foobar','ooba')"); AssertEvaluationResult(false, "contains('foobar','oobe')"); AssertEvaluationResult(false, "contains('','foo')"); AssertEvaluationResult(true, "contains('foo','')"); } [Fact] public void ConditionMethodNegativeTest1() { try { AssertEvaluationResult(true, "starts-with('foobar')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires between 2 and 3 parameters, but passed 1.", ex.InnerException.Message); } } [Fact] public void ConditionMethodNegativeTest2() { try { AssertEvaluationResult(true, "starts-with('foobar','baz','qux','zzz')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires between 2 and 3 parameters, but passed 4.", ex.InnerException.Message); } } [Fact] public void LiteralTest() { AssertEvaluationResult(null, "null"); AssertEvaluationResult(0, "0"); AssertEvaluationResult(3, "3"); AssertEvaluationResult(3.1415, "3.1415"); AssertEvaluationResult(-1, "-1"); AssertEvaluationResult(-3.1415, "-3.1415"); AssertEvaluationResult(true, "true"); AssertEvaluationResult(false, "false"); AssertEvaluationResult(string.Empty, "''"); AssertEvaluationResult("x", "'x'"); AssertEvaluationResult("d'Artagnan", "'d''Artagnan'"); } [Fact] public void LogEventInfoPropertiesTest() { AssertEvaluationResult(LogLevel.Warn, "level"); AssertEvaluationResult("some message", "message"); AssertEvaluationResult("MyCompany.Product.Class", "logger"); } [Fact] public void RelationalOperatorTest() { AssertEvaluationResult(true, "1 < 2"); AssertEvaluationResult(false, "1 < 1"); AssertEvaluationResult(true, "2 > 1"); AssertEvaluationResult(false, "1 > 1"); AssertEvaluationResult(true, "1 <= 2"); AssertEvaluationResult(false, "1 <= 0"); AssertEvaluationResult(true, "2 >= 1"); AssertEvaluationResult(false, "0 >= 1"); AssertEvaluationResult(true, "2 == 2"); AssertEvaluationResult(false, "2 == 3"); AssertEvaluationResult(true, "2 != 3"); AssertEvaluationResult(false, "2 != 2"); AssertEvaluationResult(false, "1 < null"); AssertEvaluationResult(true, "1 > null"); AssertEvaluationResult(true, "null < 1"); AssertEvaluationResult(false, "null > 1"); AssertEvaluationResult(true, "null == null"); AssertEvaluationResult(false, "null != null"); AssertEvaluationResult(false, "null == 1"); AssertEvaluationResult(false, "1 == null"); AssertEvaluationResult(true, "null != 1"); AssertEvaluationResult(true, "1 != null"); } [Fact] public void UnsupportedRelationalOperatorTest() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<ConditionEvaluationException>(() => cond.Evaluate(LogEventInfo.CreateNullEvent())); } [Fact] public void UnsupportedRelationalOperatorTest2() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<NotSupportedException>(() => cond.ToString()); } [Fact] public void MethodWithLogEventInfoTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("IsValid()", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/01'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("'42' == 42", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("42 == '42'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDouble(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDouble(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToSingle(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToSingle(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDecimal(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDecimal(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("true == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(1) == true", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/02'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(2)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("'42' == 43", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("42 == '43'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDouble(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDouble(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToSingle(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToSingle(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDecimal(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDecimal(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("false == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(1) == false", factories).Evaluate(CreateWellKnownContext())); //this is doing string comparision as thats the common type which works in this case. Assert.Equal(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '20xx/01/01'", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionNegativeTest2() { var factories = SetupConditionMethods(); Assert.Throws<ConditionEvaluationException>(() => ConditionParser.ParseExpression("GetGuid() == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void ExceptionTest1() { var ex1 = new ConditionEvaluationException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest2() { var ex1 = new ConditionEvaluationException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest3() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if NETSTANDARD [Fact(Skip = "NetStandard does not mark InvalidOperationException as Serializable")] #else [Fact] #endif public void ExceptionTest4() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } [Fact] public void ExceptionTest11() { var ex1 = new ConditionParseException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest12() { var ex1 = new ConditionParseException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest13() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if NETSTANDARD [Fact(Skip = "NetStandard does not mark InvalidOperationException as Serializable")] #else [Fact] #endif public void ExceptionTest14() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } private static ConfigurationItemFactory SetupConditionMethods() { var factories = new ConfigurationItemFactory(); factories.ConditionMethods.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid")); factories.ConditionMethods.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16")); factories.ConditionMethods.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32")); factories.ConditionMethods.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64")); factories.ConditionMethods.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble")); factories.ConditionMethods.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle")); factories.ConditionMethods.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime")); factories.ConditionMethods.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal")); factories.ConditionMethods.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid")); return factories; } private static void AssertEvaluationResult(object expectedResult, string conditionText) { ConditionExpression condition = ConditionParser.ParseExpression(conditionText); LogEventInfo context = CreateWellKnownContext(); object actualResult = condition.Evaluate(context); Assert.Equal(expectedResult, actualResult); } private static LogEventInfo CreateWellKnownContext() { var context = new LogEventInfo { Level = LogLevel.Warn, Message = "some message", LoggerName = "MyCompany.Product.Class" }; return context; } /// <summary> /// Conversion methods helpful in covering type promotion logic /// </summary> public class MyConditionMethods { public static Guid GetGuid() { return new Guid("{40190B01-C9C0-4F78-AA5A-615E413742E1}"); } public static short ToInt16(object v) { return Convert.ToInt16(v, CultureInfo.InvariantCulture); } public static int ToInt32(object v) { return Convert.ToInt32(v, CultureInfo.InvariantCulture); } public static long ToInt64(object v) { return Convert.ToInt64(v, CultureInfo.InvariantCulture); } public static float ToSingle(object v) { return Convert.ToSingle(v, CultureInfo.InvariantCulture); } public static decimal ToDecimal(object v) { return Convert.ToDecimal(v, CultureInfo.InvariantCulture); } public static double ToDouble(object v) { return Convert.ToDouble(v, CultureInfo.InvariantCulture); } public static DateTime ToDateTime(object v) { return Convert.ToDateTime(v, CultureInfo.InvariantCulture); } public static bool IsValid(LogEventInfo context) { return true; } } } }
using System; using System.ComponentModel; using System.Windows.Forms; namespace GuruComponents.CodeEditor.CodeEditor { /// <summary> /// Summary description for FindReplace. /// </summary> public class FindReplaceForm : Form { private Panel pnlButtons; private Panel pnlFind; private Panel pnlReplace; private Panel pnlSettings; private Label lblFindWhat; private Button btnRegex1; private Button button1; private Label lblReplaceWith; private Panel panel1; private Panel panel3; private Panel pnlReplaceButtons; private GroupBox groupBox1; private ComboBox cboFind; private ComboBox cboReplace; private Button btnReplace; /// <summary> /// Required designer variable. /// </summary> private Container components = null; private Button btnFind; private Button btnClose; private CheckBox chkWholeWord; private CheckBox chkMatchCase; private Button btnReplaceAll; private CheckBox chkRegEx; private Button btnMarkAll; private WeakReference _Control = null; private EditViewControl mOwner { get { if (_Control != null) return (EditViewControl) _Control.Target; else return null; } set { _Control = new WeakReference(value); } } private Button btnDoReplace; private string _Last = ""; /// <summary> /// Default constructor for the FindReplaceForm. /// </summary> public FindReplaceForm() { // // Required for Windows Form Designer support // InitializeComponent(); btnFind.Text = Localizations.FindNextButtonText; btnReplace.Text = Localizations.FindReplaceButtonText; btnMarkAll.Text = Localizations.FindMarkAllButtonText; btnReplaceAll.Text = Localizations.FindReplaceAllButtonText; btnClose.Text = Localizations.FindCloseButtonText; lblFindWhat.Text = Localizations.FindWhatLabelText; lblReplaceWith.Text = Localizations.FindReplaceWithLabelText; chkMatchCase.Text = Localizations.FindMatchCaseLabel; chkWholeWord.Text = Localizations.FindMatchWholeWordLabel; chkRegEx.Text = Localizations.FindUseRegExLabel; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; // unchecked // { // int i= (int)0x80000000; // cp.Style |=i; // } return cp; } } /// <summary> /// Creates a FindReplaceForm that will be assigned to a specific Owner control. /// </summary> /// <param name="Owner">The SyntaxBox that will use the FindReplaceForm</param> public FindReplaceForm(EditViewControl Owner) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // mOwner = Owner; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// Displays the FindReplaceForm and sets it in "Find" mode. /// </summary> public void ShowFind() { pnlReplace.Visible = false; pnlReplaceButtons.Visible = false; this.Text = Localizations.FindDialogText; this.Show(); this.Height = 160; btnDoReplace.Visible = false; btnReplace.Visible = true; _Last = ""; cboFind.Focus(); } /// <summary> /// Displays the FindReplaceForm and sets it in "Replace" mode. /// </summary> public void ShowReplace() { pnlReplace.Visible = true; pnlReplaceButtons.Visible = true; this.Text = Localizations.ReplaceDialogText; this.Show(); this.Height = 200; btnDoReplace.Visible = true; btnReplace.Visible = false; _Last = ""; cboFind.Focus(); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FindReplaceForm)); this.pnlButtons = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.btnClose = new System.Windows.Forms.Button(); this.btnMarkAll = new System.Windows.Forms.Button(); this.pnlReplaceButtons = new System.Windows.Forms.Panel(); this.btnReplaceAll = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.btnDoReplace = new System.Windows.Forms.Button(); this.btnReplace = new System.Windows.Forms.Button(); this.btnFind = new System.Windows.Forms.Button(); this.pnlFind = new System.Windows.Forms.Panel(); this.cboFind = new System.Windows.Forms.ComboBox(); this.lblFindWhat = new System.Windows.Forms.Label(); this.btnRegex1 = new System.Windows.Forms.Button(); this.pnlReplace = new System.Windows.Forms.Panel(); this.cboReplace = new System.Windows.Forms.ComboBox(); this.lblReplaceWith = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.pnlSettings = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkRegEx = new System.Windows.Forms.CheckBox(); this.chkWholeWord = new System.Windows.Forms.CheckBox(); this.chkMatchCase = new System.Windows.Forms.CheckBox(); this.pnlButtons.SuspendLayout(); this.panel3.SuspendLayout(); this.pnlReplaceButtons.SuspendLayout(); this.panel1.SuspendLayout(); this.pnlFind.SuspendLayout(); this.pnlReplace.SuspendLayout(); this.pnlSettings.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // pnlButtons // this.pnlButtons.Controls.Add(this.panel3); this.pnlButtons.Controls.Add(this.pnlReplaceButtons); this.pnlButtons.Controls.Add(this.panel1); this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Right; this.pnlButtons.Location = new System.Drawing.Point(400, 0); this.pnlButtons.Name = "pnlButtons"; this.pnlButtons.Size = new System.Drawing.Size(96, 178); this.pnlButtons.TabIndex = 0; // // panel3 // this.panel3.Controls.Add(this.btnClose); this.panel3.Controls.Add(this.btnMarkAll); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(0, 96); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(96, 82); this.panel3.TabIndex = 4; // // btnClose // this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnClose.Location = new System.Drawing.Point(8, 40); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(80, 24); this.btnClose.TabIndex = 3; this.btnClose.Text = "Close"; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnMarkAll // this.btnMarkAll.Location = new System.Drawing.Point(8, 8); this.btnMarkAll.Name = "btnMarkAll"; this.btnMarkAll.Size = new System.Drawing.Size(80, 24); this.btnMarkAll.TabIndex = 2; this.btnMarkAll.Text = "Mark all"; this.btnMarkAll.Click += new System.EventHandler(this.btnMarkAll_Click); // // pnlReplaceButtons // this.pnlReplaceButtons.Controls.Add(this.btnReplaceAll); this.pnlReplaceButtons.Dock = System.Windows.Forms.DockStyle.Top; this.pnlReplaceButtons.Location = new System.Drawing.Point(0, 64); this.pnlReplaceButtons.Name = "pnlReplaceButtons"; this.pnlReplaceButtons.Size = new System.Drawing.Size(96, 32); this.pnlReplaceButtons.TabIndex = 3; this.pnlReplaceButtons.Visible = false; // // btnReplaceAll // this.btnReplaceAll.Location = new System.Drawing.Point(8, 8); this.btnReplaceAll.Name = "btnReplaceAll"; this.btnReplaceAll.Size = new System.Drawing.Size(80, 24); this.btnReplaceAll.TabIndex = 2; this.btnReplaceAll.Text = "Replace All"; this.btnReplaceAll.Click += new System.EventHandler(this.btnReplaceAll_Click); // // panel1 // this.panel1.Controls.Add(this.btnDoReplace); this.panel1.Controls.Add(this.btnReplace); this.panel1.Controls.Add(this.btnFind); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(96, 64); this.panel1.TabIndex = 2; // // btnDoReplace // this.btnDoReplace.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnDoReplace.Location = new System.Drawing.Point(8, 40); this.btnDoReplace.Name = "btnDoReplace"; this.btnDoReplace.Size = new System.Drawing.Size(80, 24); this.btnDoReplace.TabIndex = 4; this.btnDoReplace.Text = "Replace"; this.btnDoReplace.Click += new System.EventHandler(this.btnDoReplace_Click); // // btnReplace // this.btnReplace.Image = ((System.Drawing.Image)(resources.GetObject("btnReplace.Image"))); this.btnReplace.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnReplace.Location = new System.Drawing.Point(8, 40); this.btnReplace.Name = "btnReplace"; this.btnReplace.Size = new System.Drawing.Size(80, 24); this.btnReplace.TabIndex = 3; this.btnReplace.Text = "Replace"; this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click); // // btnFind // this.btnFind.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnFind.Location = new System.Drawing.Point(8, 8); this.btnFind.Name = "btnFind"; this.btnFind.Size = new System.Drawing.Size(80, 24); this.btnFind.TabIndex = 2; this.btnFind.Text = "&FindNext"; this.btnFind.Click += new System.EventHandler(this.btnFind_Click); // // pnlFind // this.pnlFind.Controls.Add(this.cboFind); this.pnlFind.Controls.Add(this.lblFindWhat); this.pnlFind.Controls.Add(this.btnRegex1); this.pnlFind.Dock = System.Windows.Forms.DockStyle.Top; this.pnlFind.Location = new System.Drawing.Point(0, 0); this.pnlFind.Name = "pnlFind"; this.pnlFind.Size = new System.Drawing.Size(400, 40); this.pnlFind.TabIndex = 1; // // cboFind // this.cboFind.Location = new System.Drawing.Point(104, 8); this.cboFind.Name = "cboFind"; this.cboFind.Size = new System.Drawing.Size(288, 21); this.cboFind.TabIndex = 1; // // lblFindWhat // this.lblFindWhat.Location = new System.Drawing.Point(8, 8); this.lblFindWhat.Name = "lblFindWhat"; this.lblFindWhat.Size = new System.Drawing.Size(96, 24); this.lblFindWhat.TabIndex = 0; this.lblFindWhat.Text = "Fi&nd what:"; // // btnRegex1 // this.btnRegex1.Image = ((System.Drawing.Image)(resources.GetObject("btnRegex1.Image"))); this.btnRegex1.Location = new System.Drawing.Point(368, 8); this.btnRegex1.Name = "btnRegex1"; this.btnRegex1.Size = new System.Drawing.Size(21, 21); this.btnRegex1.TabIndex = 2; this.btnRegex1.Visible = false; // // pnlReplace // this.pnlReplace.Controls.Add(this.cboReplace); this.pnlReplace.Controls.Add(this.lblReplaceWith); this.pnlReplace.Controls.Add(this.button1); this.pnlReplace.Dock = System.Windows.Forms.DockStyle.Top; this.pnlReplace.Location = new System.Drawing.Point(0, 40); this.pnlReplace.Name = "pnlReplace"; this.pnlReplace.Size = new System.Drawing.Size(400, 40); this.pnlReplace.TabIndex = 2; this.pnlReplace.Visible = false; // // cboReplace // this.cboReplace.Location = new System.Drawing.Point(106, 8); this.cboReplace.Name = "cboReplace"; this.cboReplace.Size = new System.Drawing.Size(286, 21); this.cboReplace.TabIndex = 4; // // lblReplaceWith // this.lblReplaceWith.Location = new System.Drawing.Point(10, 8); this.lblReplaceWith.Name = "lblReplaceWith"; this.lblReplaceWith.Size = new System.Drawing.Size(96, 24); this.lblReplaceWith.TabIndex = 3; this.lblReplaceWith.Text = "Re&place with:"; // // button1 // this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.Location = new System.Drawing.Point(368, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(21, 21); this.button1.TabIndex = 5; this.button1.Visible = false; // // pnlSettings // this.pnlSettings.Controls.Add(this.groupBox1); this.pnlSettings.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlSettings.Location = new System.Drawing.Point(0, 80); this.pnlSettings.Name = "pnlSettings"; this.pnlSettings.Size = new System.Drawing.Size(400, 98); this.pnlSettings.TabIndex = 3; // // groupBox1 // this.groupBox1.Controls.Add(this.chkRegEx); this.groupBox1.Controls.Add(this.chkWholeWord); this.groupBox1.Controls.Add(this.chkMatchCase); this.groupBox1.Location = new System.Drawing.Point(8, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(384, 88); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search"; // // chkRegEx // this.chkRegEx.Location = new System.Drawing.Point(8, 64); this.chkRegEx.Name = "chkRegEx"; this.chkRegEx.Size = new System.Drawing.Size(144, 16); this.chkRegEx.TabIndex = 2; this.chkRegEx.Text = "Use Regular expressions"; this.chkRegEx.Visible = false; // // chkWholeWord // this.chkWholeWord.Location = new System.Drawing.Point(8, 40); this.chkWholeWord.Name = "chkWholeWord"; this.chkWholeWord.Size = new System.Drawing.Size(144, 16); this.chkWholeWord.TabIndex = 1; this.chkWholeWord.Text = "Match &whole word"; // // chkMatchCase // this.chkMatchCase.Location = new System.Drawing.Point(8, 16); this.chkMatchCase.Name = "chkMatchCase"; this.chkMatchCase.Size = new System.Drawing.Size(144, 16); this.chkMatchCase.TabIndex = 0; this.chkMatchCase.Text = "Match &case"; // // FindReplaceForm // this.AcceptButton = this.btnFind; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnClose; this.ClientSize = new System.Drawing.Size(496, 178); this.Controls.Add(this.pnlSettings); this.Controls.Add(this.pnlReplace); this.Controls.Add(this.pnlFind); this.Controls.Add(this.pnlButtons); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "FindReplaceForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Find"; this.Closing += new System.ComponentModel.CancelEventHandler(this.FindReplace_Closing); this.pnlButtons.ResumeLayout(false); this.panel3.ResumeLayout(false); this.pnlReplaceButtons.ResumeLayout(false); this.panel1.ResumeLayout(false); this.pnlFind.ResumeLayout(false); this.pnlReplace.ResumeLayout(false); this.pnlSettings.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void btnReplace_Click(object sender, EventArgs e) { ShowReplace(); } private void FindReplace_Closing(object sender, CancelEventArgs e) { e.Cancel = true; this.Hide(); } private void btnFind_Click(object sender, EventArgs e) { this.FindNext(); cboFind.Focus(); } private void btnClose_Click(object sender, EventArgs e) { mOwner.Focus(); this.Hide(); } private void btnDoReplace_Click(object sender, EventArgs e) { this.mOwner.ReplaceSelection(cboReplace.Text); btnFind_Click(null, null); } private void btnReplaceAll_Click(object sender, EventArgs e) { string text = cboFind.Text; if (text == "") return; bool found = false; foreach (string s in cboFind.Items) { if (s == text) { found = true; break; } } if (!found) cboFind.Items.Add(text); int x = mOwner.Caret.Position.X; int y = mOwner.Caret.Position.Y; mOwner.Caret.Position.X = 0; mOwner.Caret.Position.Y = 0; while (mOwner.SelectNext(cboFind.Text, chkMatchCase.Checked, chkWholeWord.Checked, chkRegEx.Checked)) { this.mOwner.ReplaceSelection(cboReplace.Text); } mOwner.Selection.ClearSelection(); // mOwner.Caret.Position.X=x; // mOwner.Caret.Position.Y=y; // mOwner.ScrollIntoView (); cboFind.Focus(); } private void btnMarkAll_Click(object sender, EventArgs e) { string text = cboFind.Text; if (text == "") return; bool found = false; foreach (string s in cboFind.Items) { if (s == text) { found = true; break; } } if (!found) cboFind.Items.Add(text); int x = mOwner.Caret.Position.X; int y = mOwner.Caret.Position.Y; mOwner.Caret.Position.X = 0; mOwner.Caret.Position.Y = 0; while (mOwner.SelectNext(cboFind.Text, chkMatchCase.Checked, chkWholeWord.Checked, chkRegEx.Checked)) { this.mOwner.Caret.CurrentRow.Bookmarked = true; } mOwner.Selection.ClearSelection(); // mOwner.Caret.Position.X=x; // mOwner.Caret.Position.Y=y; // mOwner.ScrollIntoView (); cboFind.Focus(); } public void FindNext() { string text = cboFind.Text; if (_Last != "" && _Last != text) { this.mOwner.Caret.Position.X = 0; this.mOwner.Caret.Position.Y = 0; this.mOwner.ScrollIntoView(); } _Last = text; if (text == "") return; bool found = false; foreach (string s in cboFind.Items) { if (s == text) { found = true; break; } } if (!found) cboFind.Items.Add(text); mOwner.SelectNext(cboFind.Text, chkMatchCase.Checked, chkWholeWord.Checked, chkRegEx.Checked); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Baseline.Dates; using Marten.Exceptions; using Marten.Internal; using Marten.Internal.Storage; using Marten.Schema; using Marten.Schema.Identity.Sequences; using Marten.Services; using Marten.Util; using Npgsql; using Weasel.Core; using Weasel.Postgresql; using Weasel.Postgresql.Functions; using Weasel.Postgresql.Tables; namespace Marten.Storage { internal class Tenant: ITenant { private readonly ConcurrentDictionary<Type, bool> _checks = new(); private readonly IConnectionFactory _factory; private readonly StorageFeatures _features; private readonly ConcurrentDictionary<Type, object> _identityAssignments = new(); private readonly StoreOptions _options; private Lazy<SequenceFactory> _sequences; public Tenant(StorageFeatures features, StoreOptions options, IConnectionFactory factory, string tenantId) { TenantId = tenantId; _features = features; _options = options; _factory = factory; resetSequences(); Providers = options.AutoCreateSchemaObjects == AutoCreate.None ? options.Providers : new StorageCheckingProviderGraph(this, options.Providers); } public string TenantId { get; } public IFeatureSchema FindFeature(Type storageType) { return _options.Storage.FindFeature(storageType); } public void ResetSchemaExistenceChecks() { _checks.Clear(); resetSequences(); if (Providers is StorageCheckingProviderGraph) { Providers = new StorageCheckingProviderGraph(this, _options.Providers); } } public void EnsureStorageExists(Type featureType) { if (_options.AutoCreateSchemaObjects == AutoCreate.None) { return; } ensureStorageExists(new List<Type>(), featureType).GetAwaiter().GetResult(); } public Task EnsureStorageExistsAsync(Type featureType, CancellationToken token) { return _options.AutoCreateSchemaObjects == AutoCreate.None ? Task.CompletedTask : ensureStorageExists(new List<Type>(), featureType, token); } public IDocumentStorage<T> StorageFor<T>() { var documentProvider = Providers.StorageFor<T>(); return documentProvider.QueryOnly; } public ISequences Sequences => _sequences.Value; public void MarkAllFeaturesAsChecked() { foreach (var feature in _features.AllActiveFeatures(this)) _checks[feature.StorageType] = true; } /// <summary> /// Directly open a managed connection to the underlying Postgresql database /// </summary> /// <param name="mode"></param> /// <param name="isolationLevel"></param> /// <param name="timeout"></param> /// <returns></returns> public IManagedConnection OpenConnection(CommandRunnerMode mode = CommandRunnerMode.AutoCommit, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? timeout = null) { return new ManagedConnection(_factory, mode, _options.RetryPolicy(), isolationLevel, timeout); } /// <summary> /// Fetch a connection to the tenant database /// </summary> /// <returns></returns> public NpgsqlConnection CreateConnection() { return _factory.Create(); } public IProviderGraph Providers { get; private set; } /// <summary> /// Set the minimum sequence number for a Hilo sequence for a specific document type /// to the specified floor. Useful for migrating data between databases /// </summary> /// <typeparam name="T"></typeparam> /// <param name="floor"></param> public Task ResetHiloSequenceFloor<T>(long floor) { var sequence = Sequences.SequenceFor(typeof(T)); return sequence.SetFloor(floor); } private void resetSequences() { _sequences = new Lazy<SequenceFactory>(() => { var sequences = new SequenceFactory(_options, this); generateOrUpdateFeature(typeof(SequenceFactory), sequences, default).GetAwaiter().GetResult(); return sequences; }); } private async Task ensureStorageExists(IList<Type> types, Type featureType, CancellationToken token = default) { if (_checks.ContainsKey(featureType)) { return; } var feature = _features.FindFeature(featureType); if (feature == null) { throw new ArgumentOutOfRangeException(nameof(featureType), $"Unknown feature type {featureType.FullName}"); } if (_checks.ContainsKey(feature.StorageType)) { _checks[featureType] = true; return; } // Preventing cyclic dependency problems if (types.Contains(featureType)) { return; } types.Fill(featureType); foreach (var dependentType in feature.DependentTypes()) { await ensureStorageExists(types, dependentType, token).ConfigureAwait(false); } await generateOrUpdateFeature(featureType, feature, token).ConfigureAwait(false); } private readonly TimedLock _migrateLocker = new TimedLock(); private async Task generateOrUpdateFeature(Type featureType, IFeatureSchema feature, CancellationToken token) { if (_checks.ContainsKey(featureType)) { RegisterCheck(featureType, feature); return; } var schemaObjects = feature.Objects; schemaObjects.AssertValidNames(_options); using (await _migrateLocker.Lock(5.Seconds()).ConfigureAwait(false)) { if (_checks.ContainsKey(featureType)) { RegisterCheck(featureType, feature); return; } await executeMigration(schemaObjects, token).ConfigureAwait(false); RegisterCheck(featureType, feature); } } private async Task executeMigration(ISchemaObject[] schemaObjects, CancellationToken token = default) { using var conn = _factory.Create(); await conn.OpenAsync(token).ConfigureAwait(false); var migration = await SchemaMigration.Determine(conn, schemaObjects).ConfigureAwait(false); if (migration.Difference == SchemaPatchDifference.None) return; migration.AssertPatchingIsValid(_options.AutoCreateSchemaObjects); await migration.ApplyAll( conn, _options.Advanced.DdlRules, _options.AutoCreateSchemaObjects, sql => _options.Logger().SchemaChange(sql), MartenExceptionTransformer.WrapAndThrow) .ConfigureAwait(false); } private void RegisterCheck(Type featureType, IFeatureSchema feature) { _checks[featureType] = true; if (feature.StorageType != featureType) { _checks[feature.StorageType] = true; } } public async Task<IReadOnlyList<DbObjectName>> SchemaTables() { var schemaNames = _features.AllSchemaNames(); using var conn = CreateConnection(); await conn.OpenAsync().ConfigureAwait(false); return await conn.ExistingTables(schemas: schemaNames).ConfigureAwait(false); } public async Task<IReadOnlyList<DbObjectName>> DocumentTables() { var tables = await SchemaTables().ConfigureAwait(false); return tables.Where(x => x.Name.StartsWith(SchemaConstants.TablePrefix)).ToList(); } public async Task<IReadOnlyList<DbObjectName>> Functions() { using var conn = CreateConnection(); await conn.OpenAsync().ConfigureAwait(false); var schemaNames = _features.AllSchemaNames(); return await conn.ExistingFunctions(namePattern:"mt_%", schemas:schemaNames).ConfigureAwait(false); } public async Task<Function> DefinitionForFunction(DbObjectName function) { using var conn = CreateConnection(); await conn.OpenAsync().ConfigureAwait(false); return await conn.FindExistingFunction(function).ConfigureAwait(false); } public async Task<Table> ExistingTableFor(Type type) { var mapping = _features.MappingFor(type).As<DocumentMapping>(); var expected = mapping.Schema.Table; using var conn = CreateConnection(); await conn.OpenAsync().ConfigureAwait(false); return await expected.FetchExisting(conn).ConfigureAwait(false); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Globalization; using Avalonia.Animation.Animators; using Avalonia.Utilities; namespace Avalonia { /// <summary> /// Defines a rectangle. /// </summary> public readonly struct Rect { static Rect() { Animation.Animation.RegisterAnimator<RectAnimator>(prop => typeof(Rect).IsAssignableFrom(prop.PropertyType)); } /// <summary> /// An empty rectangle. /// </summary> public static readonly Rect Empty = default(Rect); /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// The width. /// </summary> private readonly double _width; /// <summary> /// The height. /// </summary> private readonly double _height; /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect(double x, double y, double width, double height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="size">The size of the rectangle.</param> public Rect(Size size) { _x = 0; _y = 0; _width = size.Width; _height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="position">The position of the rectangle.</param> /// <param name="size">The size of the rectangle.</param> public Rect(Point position, Size size) { _x = position.X; _y = position.Y; _width = size.Width; _height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="topLeft">The top left position of the rectangle.</param> /// <param name="bottomRight">The bottom right position of the rectangle.</param> public Rect(Point topLeft, Point bottomRight) { _x = topLeft.X; _y = topLeft.Y; _width = bottomRight.X - topLeft.X; _height = bottomRight.Y - topLeft.Y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Gets the width. /// </summary> public double Width => _width; /// <summary> /// Gets the height. /// </summary> public double Height => _height; /// <summary> /// Gets the position of the rectangle. /// </summary> public Point Position => new Point(_x, _y); /// <summary> /// Gets the size of the rectangle. /// </summary> public Size Size => new Size(_width, _height); /// <summary> /// Gets the right position of the rectangle. /// </summary> public double Right => _x + _width; /// <summary> /// Gets the bottom position of the rectangle. /// </summary> public double Bottom => _y + _height; /// <summary> /// Gets the top left point of the rectangle. /// </summary> public Point TopLeft => new Point(_x, _y); /// <summary> /// Gets the top right point of the rectangle. /// </summary> public Point TopRight => new Point(Right, _y); /// <summary> /// Gets the bottom left point of the rectangle. /// </summary> public Point BottomLeft => new Point(_x, Bottom); /// <summary> /// Gets the bottom right point of the rectangle. /// </summary> public Point BottomRight => new Point(Right, Bottom); /// <summary> /// Gets the center point of the rectangle. /// </summary> public Point Center => new Point(_x + (_width / 2), _y + (_height / 2)); /// <summary> /// Gets a value that indicates whether the rectangle is empty. /// </summary> public bool IsEmpty => _width == 0 && _height == 0; /// <summary> /// Checks for equality between two <see cref="Rect"/>s. /// </summary> /// <param name="left">The first rect.</param> /// <param name="right">The second rect.</param> /// <returns>True if the rects are equal; otherwise false.</returns> public static bool operator ==(Rect left, Rect right) { return left.Position == right.Position && left.Size == right.Size; } /// <summary> /// Checks for inequality between two <see cref="Rect"/>s. /// </summary> /// <param name="left">The first rect.</param> /// <param name="right">The second rect.</param> /// <returns>True if the rects are unequal; otherwise false.</returns> public static bool operator !=(Rect left, Rect right) { return !(left == right); } /// <summary> /// Multiplies a rectangle by a scaling vector. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="scale">The vector scale.</param> /// <returns>The scaled rectangle.</returns> public static Rect operator *(Rect rect, Vector scale) { return new Rect( rect.X * scale.X, rect.Y * scale.Y, rect.Width * scale.X, rect.Height * scale.Y); } /// <summary> /// Divides a rectangle by a vector. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="scale">The vector scale.</param> /// <returns>The scaled rectangle.</returns> public static Rect operator /(Rect rect, Vector scale) { return new Rect( rect.X / scale.X, rect.Y / scale.Y, rect.Width / scale.X, rect.Height / scale.Y); } /// <summary> /// Determines whether a point in in the bounds of the rectangle. /// </summary> /// <param name="p">The point.</param> /// <returns>true if the point is in the bounds of the rectangle; otherwise false.</returns> public bool Contains(Point p) { return p.X >= _x && p.X <= _x + _width && p.Y >= _y && p.Y <= _y + _height; } /// <summary> /// Determines whether the rectangle fully contains another rectangle. /// </summary> /// <param name="r">The rectangle.</param> /// <returns>true if the rectangle is fully contained; otherwise false.</returns> public bool Contains(Rect r) { return Contains(r.TopLeft) && Contains(r.BottomRight); } /// <summary> /// Centers another rectangle in this rectangle. /// </summary> /// <param name="rect">The rectangle to center.</param> /// <returns>The centered rectangle.</returns> public Rect CenterRect(Rect rect) { return new Rect( _x + ((_width - rect._width) / 2), _y + ((_height - rect._height) / 2), rect._width, rect._height); } /// <summary> /// Inflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The inflated rectangle.</returns> public Rect Inflate(double thickness) { return Inflate(new Thickness(thickness)); } /// <summary> /// Inflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The inflated rectangle.</returns> public Rect Inflate(Thickness thickness) { return new Rect( new Point(_x - thickness.Left, _y - thickness.Top), Size.Inflate(thickness)); } /// <summary> /// Deflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The deflated rectangle.</returns> /// <remarks>The deflated rectangle size cannot be less than 0.</remarks> public Rect Deflate(double thickness) { return Deflate(new Thickness(thickness / 2)); } /// <summary> /// Deflates the rectangle by a <see cref="Thickness"/>. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The deflated rectangle.</returns> /// <remarks>The deflated rectangle size cannot be less than 0.</remarks> public Rect Deflate(Thickness thickness) { return new Rect( new Point(_x + thickness.Left, _y + thickness.Top), Size.Deflate(thickness)); } /// <summary> /// Returns a boolean indicating whether the given object is equal to this rectangle. /// </summary> /// <param name="obj">The object to compare against.</param> /// <returns>True if the object is equal to this rectangle; false otherwise.</returns> public override bool Equals(object obj) { if (obj is Rect) { var other = (Rect)obj; return Position == other.Position && Size == other.Size; } return false; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + X.GetHashCode(); hash = (hash * 23) + Y.GetHashCode(); hash = (hash * 23) + Width.GetHashCode(); hash = (hash * 23) + Height.GetHashCode(); return hash; } } /// <summary> /// Gets the intersection of two rectangles. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns>The intersection.</returns> public Rect Intersect(Rect rect) { var newLeft = (rect.X > X) ? rect.X : X; var newTop = (rect.Y > Y) ? rect.Y : Y; var newRight = (rect.Right < Right) ? rect.Right : Right; var newBottom = (rect.Bottom < Bottom) ? rect.Bottom : Bottom; if ((newRight > newLeft) && (newBottom > newTop)) { return new Rect(newLeft, newTop, newRight - newLeft, newBottom - newTop); } else { return Empty; } } /// <summary> /// Determines whether a rectangle intersects with this rectangle. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns> /// True if the specified rectangle intersects with this one; otherwise false. /// </returns> public bool Intersects(Rect rect) { return (rect.X < Right) && (X < rect.Right) && (rect.Y < Bottom) && (Y < rect.Bottom); } /// <summary> /// Returns the axis-aligned bounding box of a transformed rectangle. /// </summary> /// <param name="matrix">The transform.</param> /// <returns>The bounding box</returns> public Rect TransformToAABB(Matrix matrix) { var points = new[] { TopLeft.Transform(matrix), TopRight.Transform(matrix), BottomRight.Transform(matrix), BottomLeft.Transform(matrix), }; var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { if (p.X < left) left = p.X; if (p.X > right) right = p.X; if (p.Y < top) top = p.Y; if (p.Y > bottom) bottom = p.Y; } return new Rect(new Point(left, top), new Point(right, bottom)); } /// <summary> /// Translates the rectangle by an offset. /// </summary> /// <param name="offset">The offset.</param> /// <returns>The translated rectangle.</returns> public Rect Translate(Vector offset) { return new Rect(Position + offset, Size); } /// <summary> /// Gets the union of two rectangles. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns>The union.</returns> public Rect Union(Rect rect) { if (IsEmpty) { return rect; } else if (rect.IsEmpty) { return this; } else { var x1 = Math.Min(this.X, rect.X); var x2 = Math.Max(this.Right, rect.Right); var y1 = Math.Min(this.Y, rect.Y); var y2 = Math.Max(this.Bottom, rect.Bottom); return new Rect(new Point(x1, y1), new Point(x2, y2)); } } /// <summary> /// Returns a new <see cref="Rect"/> with the specified X position. /// </summary> /// <param name="x">The x position.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithX(double x) { return new Rect(x, _y, _width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified Y position. /// </summary> /// <param name="y">The y position.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithY(double y) { return new Rect(_x, y, _width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified width. /// </summary> /// <param name="width">The width.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithWidth(double width) { return new Rect(_x, _y, width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified height. /// </summary> /// <param name="height">The height.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithHeight(double height) { return new Rect(_x, _y, _width, height); } /// <summary> /// Returns the string representation of the rectangle. /// </summary> /// <returns>The string representation of the rectangle.</returns> public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "{0}, {1}, {2}, {3}", _x, _y, _width, _height); } /// <summary> /// Parses a <see cref="Rect"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The parsed <see cref="Rect"/>.</returns> public static Rect Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Rect")) { return new Rect( tokenizer.ReadDouble(), tokenizer.ReadDouble(), tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } } }
using UnityEngine; using System; using System.Collections.Generic; using Delaunay.Geo; using Delaunay.LR; namespace Delaunay { public sealed class Site: ICoord, IComparable { private static Stack<Site> _pool = new Stack<Site> (); public static Site Create (Vector2 p, uint index, float weight, uint color) { if (_pool.Count > 0) { return _pool.Pop ().Init (p, index, weight, color); } else { return new Site (p, index, weight, color); } } internal static void SortSites (List<Site> sites) { // sites.sort(Site.compare); sites.Sort (); // XXX: Check if this works } /** * sort sites on y, then x, coord * also change each site's _siteIndex to match its new position in the list * so the _siteIndex can be used to identify the site for nearest-neighbor queries * * haha "also" - means more than one responsibility... * */ public int CompareTo (System.Object obj) // XXX: Really, really worried about this because it depends on how sorting works in AS3 impl - Julian { Site s2 = (Site)obj; int returnValue = Voronoi.CompareByYThenX (this, s2); // swap _siteIndex values if necessary to match new ordering: uint tempIndex; if (returnValue == -1) { if (this._siteIndex > s2._siteIndex) { tempIndex = this._siteIndex; this._siteIndex = s2._siteIndex; s2._siteIndex = tempIndex; } } else if (returnValue == 1) { if (s2._siteIndex > this._siteIndex) { tempIndex = s2._siteIndex; s2._siteIndex = this._siteIndex; this._siteIndex = tempIndex; } } return returnValue; } private static readonly float EPSILON = .005f; private static bool CloseEnough (Vector2 p0, Vector2 p1) { return Vector2.Distance (p0, p1) < EPSILON; } private Vector2 _coord; public Vector2 Coord { get { return _coord;} } public uint color; public float weight; private uint _siteIndex; // the edges that define this Site's Voronoi region: private List<Edge> _edges; internal List<Edge> edges { get { return _edges;} } // which end of each edge hooks up with the previous edge in _edges: private List<Side> _edgeOrientations; // ordered list of points that define the region clipped to bounds: private List<Vector2> _region; private Site (Vector2 p, uint index, float weight, uint color) { // if (lock != PrivateConstructorEnforcer) // { // throw new Error("Site constructor is private"); // } Init (p, index, weight, color); } private Site Init (Vector2 p, uint index, float weight, uint color) { _coord = p; _siteIndex = index; this.weight = weight; this.color = color; _edges = new List<Edge> (); _region = null; return this; } public override string ToString () { return "Site " + _siteIndex.ToString () + ": " + Coord.ToString (); } private void Move (Vector2 p) { Clear (); _coord = p; } public void Dispose () { // _coord = null; Clear (); _pool.Push (this); } private void Clear () { if (_edges != null) { _edges.Clear (); _edges = null; } if (_edgeOrientations != null) { _edgeOrientations.Clear (); _edgeOrientations = null; } if (_region != null) { _region.Clear (); _region = null; } } public void AddEdge (Edge edge) { _edges.Add (edge); } public Edge NearestEdge () { _edges.Sort (delegate (Edge a, Edge b) { return Edge.CompareSitesDistances (a, b); }); return _edges [0]; } public List<Site> NeighborSites () { if (_edges == null || _edges.Count == 0) { return new List<Site> (); } if (_edgeOrientations == null) { ReorderEdges (); } List<Site> list = new List<Site> (); Edge edge; for (int i = 0; i < _edges.Count; i++) { edge = _edges [i]; list.Add (NeighborSite (edge)); } return list; } private Site NeighborSite (Edge edge) { if (this == edge.leftSite) { return edge.rightSite; } if (this == edge.rightSite) { return edge.leftSite; } return null; } internal List<Vector2> Region (Rect clippingBounds) { if (_edges == null || _edges.Count == 0) { return new List<Vector2> (); } if (_edgeOrientations == null) { ReorderEdges (); _region = ClipToBounds (clippingBounds); if ((new Polygon (_region)).Winding () == Winding.CLOCKWISE) { _region.Reverse (); } } return _region; } private void ReorderEdges () { //trace("_edges:", _edges); EdgeReorderer reorderer = new EdgeReorderer (_edges, VertexOrSite.VERTEX); _edges = reorderer.edges; //trace("reordered:", _edges); _edgeOrientations = reorderer.edgeOrientations; reorderer.Dispose (); } private List<Vector2> ClipToBounds (Rect bounds) { List<Vector2> points = new List<Vector2> (); int n = _edges.Count; int i = 0; Edge edge; while (i < n && ((_edges[i] as Edge).visible == false)) { ++i; } if (i == n) { // no edges visible return new List<Vector2> (); } edge = _edges [i]; Side orientation = _edgeOrientations [i]; if (edge.clippedEnds [orientation] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } if (edge.clippedEnds [SideHelper.Other (orientation)] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } points.Add ((Vector2)edge.clippedEnds [orientation]); points.Add ((Vector2)edge.clippedEnds [SideHelper.Other (orientation)]); for (int j = i + 1; j < n; ++j) { edge = _edges [j]; if (edge.visible == false) { continue; } Connect (points, j, bounds); } // close up the polygon by adding another corner point of the bounds if needed: Connect (points, i, bounds, true); return points; } private void Connect (List<Vector2> points, int j, Rect bounds, bool closingUp = false) { Vector2 rightPoint = points [points.Count - 1]; Edge newEdge = _edges [j] as Edge; Side newOrientation = _edgeOrientations [j]; // the point that must be connected to rightPoint: if (newEdge.clippedEnds [newOrientation] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } Vector2 newPoint = (Vector2)newEdge.clippedEnds [newOrientation]; if (!CloseEnough (rightPoint, newPoint)) { // The points do not coincide, so they must have been clipped at the bounds; // see if they are on the same border of the bounds: if (rightPoint.x != newPoint.x && rightPoint.y != newPoint.y) { // They are on different borders of the bounds; // insert one or two corners of bounds as needed to hook them up: // (NOTE this will not be correct if the region should take up more than // half of the bounds rect, for then we will have gone the wrong way // around the bounds and included the smaller part rather than the larger) int rightCheck = BoundsCheck.Check (rightPoint, bounds); int newCheck = BoundsCheck.Check (newPoint, bounds); float px, py; if ((rightCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; if ((newCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { if (rightPoint.y - bounds.y + newPoint.y - bounds.y < bounds.height) { py = bounds.yMin; } else { py = bounds.yMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (bounds.xMin, py)); } } else if ((rightCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; if ((newCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.RIGHT) != 0) { if (rightPoint.y - bounds.y + newPoint.y - bounds.y < bounds.height) { py = bounds.yMin; } else { py = bounds.yMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (bounds.xMax, py)); } } else if ((rightCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; if ((newCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.BOTTOM) != 0) { if (rightPoint.x - bounds.x + newPoint.x - bounds.x < bounds.width) { px = bounds.xMin; } else { px = bounds.xMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (px, bounds.yMax)); } } else if ((rightCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; if ((newCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { if (rightPoint.x - bounds.x + newPoint.x - bounds.x < bounds.width) { px = bounds.xMin; } else { px = bounds.xMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (px, bounds.yMin)); } } } if (closingUp) { // newEdge's ends have already been added return; } points.Add (newPoint); } if (newEdge.clippedEnds [SideHelper.Other (newOrientation)] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } Vector2 newRightPoint = (Vector2)newEdge.clippedEnds [SideHelper.Other (newOrientation)]; if (!CloseEnough (points [0], newRightPoint)) { points.Add (newRightPoint); } } public float x { get { return _coord.x;} } internal float y { get { return _coord.y;} } public float Dist (ICoord p) { return Vector2.Distance (p.Coord, this._coord); } } } // class PrivateConstructorEnforcer {} // import flash.geom.Point; // import flash.geom.Rectangle; static class BoundsCheck { public static readonly int TOP = 1; public static readonly int BOTTOM = 2; public static readonly int LEFT = 4; public static readonly int RIGHT = 8; /** * * @param point * @param bounds * @return an int with the appropriate bits set if the Point lies on the corresponding bounds lines * */ public static int Check (Vector2 point, Rect bounds) { int value = 0; if (point.x == bounds.xMin) { value |= LEFT; } if (point.x == bounds.xMax) { value |= RIGHT; } if (point.y == bounds.yMin) { value |= TOP; } if (point.y == bounds.yMax) { value |= BOTTOM; } return value; } }
// 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. // File System.Windows.Controls.FlowDocumentScrollViewer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class FlowDocumentScrollViewer : Control, System.Windows.Markup.IAddChild, IServiceProvider, MS.Internal.AppModel.IJournalState { #region Methods and constructors public void CancelPrint() { } public void DecreaseZoom() { } public void Find() { } public FlowDocumentScrollViewer() { } public void IncreaseZoom() { } public override void OnApplyTemplate() { } protected virtual new void OnCancelPrintCommand() { } protected override void OnContextMenuOpening(ContextMenuEventArgs e) { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnDecreaseZoomCommand() { } protected virtual new void OnFindCommand() { } protected virtual new void OnIncreaseZoomCommand() { } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected override void OnMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected virtual new void OnPrintCommand() { } protected virtual new void OnPrintCompleted() { } public void Print() { } Object System.IServiceProvider.GetService(Type serviceType) { return default(Object); } void System.Windows.Markup.IAddChild.AddChild(Object value) { } void System.Windows.Markup.IAddChild.AddText(string text) { } #endregion #region Properties and indexers public bool CanDecreaseZoom { get { return default(bool); } } public bool CanIncreaseZoom { get { return default(bool); } } public System.Windows.Documents.FlowDocument Document { get { return default(System.Windows.Documents.FlowDocument); } set { } } public ScrollBarVisibility HorizontalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } public bool IsSelectionEnabled { get { return default(bool); } set { } } public bool IsToolBarVisible { get { return default(bool); } set { } } internal protected override System.Collections.IEnumerator LogicalChildren { get { return default(System.Collections.IEnumerator); } } public double MaxZoom { get { return default(double); } set { } } public double MinZoom { get { return default(double); } set { } } public System.Windows.Documents.TextSelection Selection { get { return default(System.Windows.Documents.TextSelection); } } public System.Windows.Media.Brush SelectionBrush { get { return default(System.Windows.Media.Brush); } set { } } public double SelectionOpacity { get { return default(double); } set { } } public ScrollBarVisibility VerticalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } public double Zoom { get { return default(double); } set { } } public double ZoomIncrement { get { return default(double); } set { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty CanDecreaseZoomProperty; public readonly static System.Windows.DependencyProperty CanIncreaseZoomProperty; public readonly static System.Windows.DependencyProperty DocumentProperty; public readonly static System.Windows.DependencyProperty HorizontalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty IsSelectionEnabledProperty; public readonly static System.Windows.DependencyProperty IsToolBarVisibleProperty; public readonly static System.Windows.DependencyProperty MaxZoomProperty; public readonly static System.Windows.DependencyProperty MinZoomProperty; public readonly static System.Windows.DependencyProperty SelectionBrushProperty; public readonly static System.Windows.DependencyProperty SelectionOpacityProperty; public readonly static System.Windows.DependencyProperty VerticalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty ZoomIncrementProperty; public readonly static System.Windows.DependencyProperty ZoomProperty; #endregion } }
using NBitcoin; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Text; using WalletWasabi.Blockchain.Analysis.Clustering; using WalletWasabi.Helpers; using WalletWasabi.JsonConverters; using WalletWasabi.Logging; using WalletWasabi.Models; using WalletWasabi.Wallets; namespace WalletWasabi.Blockchain.Keys { [JsonObject(MemberSerialization.OptIn)] public class KeyManager { public const int AbsoluteMinGapLimit = 21; public const int MaxGapLimit = 10_000; // BIP84-ish derivation scheme // m / purpose' / coin_type' / account' / change / address_index // https://github.com/bitcoin/bips/blob/master/bip-0084.mediawiki public static readonly KeyPath DefaultAccountKeyPath = new KeyPath("m/84h/0h/0h"); [JsonConstructor] public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, HDFingerprint? masterFingerprint, ExtPubKey extPubKey, bool? passwordVerified, int? minGapLimit, BlockchainState blockchainState, string? filePath = null, KeyPath? accountKeyPath = null) { HdPubKeys = new List<HdPubKey>(); HdPubKeyScriptBytes = new List<byte[]>(); ScriptHdPubKeyMap = new Dictionary<Script, HdPubKey>(); HdPubKeysLock = new object(); HdPubKeyScriptBytesLock = new object(); ScriptHdPubKeyMapLock = new object(); BlockchainStateLock = new object(); EncryptedSecret = encryptedSecret; ChainCode = chainCode; MasterFingerprint = masterFingerprint; ExtPubKey = Guard.NotNull(nameof(extPubKey), extPubKey); PasswordVerified = passwordVerified; SetMinGapLimit(minGapLimit); BlockchainState = blockchainState ?? new BlockchainState(); AccountKeyPath = accountKeyPath ?? DefaultAccountKeyPath; SetFilePath(filePath); ToFileLock = new object(); ToFile(); } public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, string password, int minGapLimit = AbsoluteMinGapLimit, string? filePath = null, KeyPath? accountKeyPath = null) { HdPubKeys = new List<HdPubKey>(); HdPubKeyScriptBytes = new List<byte[]>(); ScriptHdPubKeyMap = new Dictionary<Script, HdPubKey>(); HdPubKeysLock = new object(); HdPubKeyScriptBytesLock = new object(); ScriptHdPubKeyMapLock = new object(); BlockchainState = new BlockchainState(); BlockchainStateLock = new object(); password ??= ""; SetMinGapLimit(minGapLimit); EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret); ChainCode = Guard.NotNull(nameof(chainCode), chainCode); var extKey = new ExtKey(encryptedSecret.GetKey(password), chainCode); MasterFingerprint = extKey.Neuter().PubKey.GetHDFingerPrint(); AccountKeyPath = accountKeyPath ?? DefaultAccountKeyPath; ExtPubKey = extKey.Derive(AccountKeyPath).Neuter(); SetFilePath(filePath); ToFileLock = new object(); ToFile(); } [JsonProperty(Order = 1)] [JsonConverter(typeof(BitcoinEncryptedSecretNoECJsonConverter))] public BitcoinEncryptedSecretNoEC EncryptedSecret { get; } [JsonProperty(Order = 2)] [JsonConverter(typeof(ByteArrayJsonConverter))] public byte[] ChainCode { get; } [JsonProperty(Order = 3)] [JsonConverter(typeof(HDFingerprintJsonConverter))] public HDFingerprint? MasterFingerprint { get; private set; } [JsonProperty(Order = 4)] [JsonConverter(typeof(ExtPubKeyJsonConverter))] public ExtPubKey ExtPubKey { get; } [JsonProperty(Order = 5)] public bool? PasswordVerified { get; private set; } [JsonProperty(Order = 6)] public int? MinGapLimit { get; private set; } [JsonProperty(Order = 7)] [JsonConverter(typeof(KeyPathJsonConverter))] public KeyPath AccountKeyPath { get; private set; } public string FilePath { get; private set; } public bool IsWatchOnly => EncryptedSecret is null; public bool IsHardwareWallet => EncryptedSecret is null && MasterFingerprint is { }; [JsonProperty(Order = 8)] private BlockchainState BlockchainState { get; } [JsonProperty(Order = 9)] private List<HdPubKey> HdPubKeys { get; } [JsonProperty(Order = 10, PropertyName = "Icon")] public string? Icon { get; private set; } private object BlockchainStateLock { get; } private object HdPubKeysLock { get; } private List<byte[]> HdPubKeyScriptBytes { get; } private object HdPubKeyScriptBytesLock { get; } private Dictionary<Script, HdPubKey> ScriptHdPubKeyMap { get; } private object ScriptHdPubKeyMapLock { get; } private object ToFileLock { get; } public string WalletName => string.IsNullOrWhiteSpace(FilePath) ? "" : Path.GetFileNameWithoutExtension(FilePath); public static KeyManager CreateNew(out Mnemonic mnemonic, string password, string? filePath = null) { password ??= ""; mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve); ExtKey extKey = mnemonic.DeriveExtKey(password); var encryptedSecret = extKey.PrivateKey.GetEncryptedBitcoinSecret(password, Network.Main); HDFingerprint masterFingerprint = extKey.Neuter().PubKey.GetHDFingerPrint(); KeyPath keyPath = DefaultAccountKeyPath; ExtPubKey extPubKey = extKey.Derive(keyPath).Neuter(); return new KeyManager(encryptedSecret, extKey.ChainCode, masterFingerprint, extPubKey, false, AbsoluteMinGapLimit, new BlockchainState(), filePath, keyPath); } public static KeyManager CreateNewWatchOnly(ExtPubKey extPubKey, string? filePath = null) { return new KeyManager(null, null, null, extPubKey, null, AbsoluteMinGapLimit, new BlockchainState(), filePath); } public static KeyManager CreateNewHardwareWalletWatchOnly(HDFingerprint masterFingerprint, ExtPubKey extPubKey, string? filePath = null) { return new KeyManager(null, null, masterFingerprint, extPubKey, null, AbsoluteMinGapLimit, new BlockchainState(), filePath); } public static KeyManager Recover(Mnemonic mnemonic, string password, string? filePath = null, KeyPath? accountKeyPath = null, int minGapLimit = AbsoluteMinGapLimit) { Guard.NotNull(nameof(mnemonic), mnemonic); password ??= ""; ExtKey extKey = mnemonic.DeriveExtKey(password); var encryptedSecret = extKey.PrivateKey.GetEncryptedBitcoinSecret(password, Network.Main); HDFingerprint masterFingerprint = extKey.Neuter().PubKey.GetHDFingerPrint(); KeyPath keyPath = accountKeyPath ?? DefaultAccountKeyPath; ExtPubKey extPubKey = extKey.Derive(keyPath).Neuter(); return new KeyManager(encryptedSecret, extKey.ChainCode, masterFingerprint, extPubKey, true, minGapLimit, new BlockchainState(), filePath, keyPath); } public static KeyManager FromFile(string filePath) { filePath = Guard.NotNullOrEmptyOrWhitespace(nameof(filePath), filePath); if (!File.Exists(filePath)) { throw new FileNotFoundException($"Wallet file not found at: `{filePath}`."); } string jsonString = File.ReadAllText(filePath, Encoding.UTF8); var km = JsonConvert.DeserializeObject<KeyManager>(jsonString); km.SetFilePath(filePath); lock (km.HdPubKeyScriptBytesLock) { km.HdPubKeyScriptBytes.AddRange(km.GetKeys(x => true).Select(x => x.P2wpkhScript.ToCompressedBytes())); } lock (km.ScriptHdPubKeyMapLock) { foreach (var key in km.GetKeys()) { km.ScriptHdPubKeyMap.Add(key.P2wpkhScript, key); } } // Backwards compatibility: km.PasswordVerified ??= true; return km; } public void SetFilePath(string filePath) { FilePath = string.IsNullOrWhiteSpace(filePath) ? null : filePath; if (FilePath is null) { return; } IoHelpers.EnsureContainingDirectoryExists(FilePath); } public void ToFile() { lock (HdPubKeysLock) { lock (BlockchainStateLock) { lock (ToFileLock) { ToFileNoLock(); } } } } public void ToFile(string filePath) { lock (HdPubKeysLock) { lock (BlockchainStateLock) { lock (ToFileLock) { ToFileNoLock(filePath); } } } } public HdPubKey GenerateNewKey(SmartLabel label, KeyState keyState, bool isInternal, bool toFile = true) { // BIP44-ish derivation scheme // m / purpose' / coin_type' / account' / change / address_index var change = isInternal ? 1 : 0; lock (HdPubKeysLock) { HdPubKey[] relevantHdPubKeys = HdPubKeys.Where(x => x.IsInternal == isInternal).ToArray(); KeyPath path = new KeyPath($"{change}/0"); if (relevantHdPubKeys.Any()) { int largestIndex = relevantHdPubKeys.Max(x => x.Index); var smallestMissingIndex = largestIndex; var present = new bool[largestIndex + 1]; for (int i = 0; i < relevantHdPubKeys.Length; ++i) { present[relevantHdPubKeys[i].Index] = true; } for (int i = 1; i < present.Length; ++i) { if (!present[i]) { smallestMissingIndex = i - 1; break; } } path = relevantHdPubKeys[smallestMissingIndex].NonHardenedKeyPath.Increment(); } var fullPath = AccountKeyPath.Derive(path); var pubKey = ExtPubKey.Derive(path).PubKey; var hdPubKey = new HdPubKey(pubKey, fullPath, label, keyState); HdPubKeys.Add(hdPubKey); lock (HdPubKeyScriptBytesLock) { HdPubKeyScriptBytes.Add(hdPubKey.P2wpkhScript.ToCompressedBytes()); } lock (ScriptHdPubKeyMapLock) { ScriptHdPubKeyMap.Add(hdPubKey.P2wpkhScript, hdPubKey); } if (toFile) { ToFile(); } return hdPubKey; } } public HdPubKey GetNextReceiveKey(SmartLabel label, out bool minGapLimitIncreased) { if (label.IsEmpty) { throw new InvalidOperationException("Label is required."); } minGapLimitIncreased = false; AssertCleanKeysIndexed(isInternal: false); // Find the next clean external key with empty label. var newKey = GetKeys(x => x.IsInternal == false && x.KeyState == KeyState.Clean && x.Label.IsEmpty).FirstOrDefault(); // If not found, generate a new. if (newKey is null) { SetMinGapLimit(MinGapLimit.Value + 1); newKey = AssertCleanKeysIndexed(isInternal: false).First(); // If the new is over the MinGapLimit, set minGapLimitIncreased to true. minGapLimitIncreased = true; } newKey.SetLabel(label, kmToFile: this); return newKey; } public IEnumerable<HdPubKey> GetKeys(Func<HdPubKey, bool> wherePredicate) { // BIP44-ish derivation scheme // m / purpose' / coin_type' / account' / change / address_index lock (HdPubKeysLock) { if (wherePredicate is null) { return HdPubKeys.ToList(); } else { return HdPubKeys.Where(wherePredicate).ToList(); } } } public void SetPasswordVerified() { PasswordVerified = true; ToFile(); } public IEnumerable<HdPubKey> GetKeys(KeyState? keyState = null, bool? isInternal = null) { if (keyState is null) { if (isInternal is null) { return GetKeys(x => true); } else { return GetKeys(x => x.IsInternal == isInternal); } } else { if (isInternal is null) { return GetKeys(x => x.KeyState == keyState); } else { return GetKeys(x => x.IsInternal == isInternal && x.KeyState == keyState); } } } public int CountConsecutiveUnusedKeys(bool isInternal) { var keyIndexes = GetKeys(x => x.IsInternal == isInternal && x.KeyState != KeyState.Used).Select(x => x.Index).ToArray(); var hs = keyIndexes.ToHashSet(); int largerConsecutiveSequence = 0; for (int i = 0; i < keyIndexes.Length; ++i) { if (!hs.Contains(keyIndexes[i] - 1)) { int j = keyIndexes[i]; while (hs.Contains(j)) { j++; } var sequenceLength = j - keyIndexes[i]; if (largerConsecutiveSequence < sequenceLength) { largerConsecutiveSequence = sequenceLength; } } } return largerConsecutiveSequence; } public IEnumerable<byte[]> GetPubKeyScriptBytes() { lock (HdPubKeyScriptBytesLock) { return HdPubKeyScriptBytes; } } public HdPubKey GetKeyForScriptPubKey(Script scriptPubKey) { lock (ScriptHdPubKeyMapLock) { if (ScriptHdPubKeyMap.TryGetValue(scriptPubKey, out var key)) { return key; } return default; } } public IEnumerable<ExtKey> GetSecrets(string password, params Script[] scripts) { return GetSecretsAndPubKeyPairs(password, scripts).Select(x => x.secret); } public IEnumerable<(ExtKey secret, HdPubKey pubKey)> GetSecretsAndPubKeyPairs(string password, params Script[] scripts) { ExtKey extKey = GetMasterExtKey(password); var extKeysAndPubs = new List<(ExtKey secret, HdPubKey pubKey)>(); lock (HdPubKeysLock) { foreach (HdPubKey key in HdPubKeys.Where(x => scripts.Contains(x.P2wpkhScript) || scripts.Contains(x.P2shOverP2wpkhScript) || scripts.Contains(x.P2pkhScript) || scripts.Contains(x.P2pkScript))) { ExtKey ek = extKey.Derive(key.FullKeyPath); extKeysAndPubs.Add((ek, key)); } } return extKeysAndPubs; } public IEnumerable<SmartLabel> GetLabels() => GetKeys().Select(x => x.Label); public ExtKey GetMasterExtKey(string password) { password ??= ""; if (IsWatchOnly) { throw new SecurityException("This is a watchonly wallet."); } try { Key secret = EncryptedSecret.GetKey(password); var extKey = new ExtKey(secret, ChainCode); // Backwards compatibility: MasterFingerprint ??= secret.PubKey.GetHDFingerPrint(); return extKey; } catch (SecurityException ex) { throw new SecurityException("Invalid password.", ex); } } /// <summary> /// Make sure there's always clean keys generated and indexed. /// Call SetMinGapLimit() to set how many keys should be asserted. /// </summary> public IEnumerable<HdPubKey> AssertCleanKeysIndexed(bool? isInternal = null) { var newKeys = new List<HdPubKey>(); if (isInternal.HasValue) { while (CountConsecutiveUnusedKeys(isInternal.Value) < MinGapLimit) { newKeys.Add(GenerateNewKey(SmartLabel.Empty, KeyState.Clean, isInternal.Value, toFile: false)); } } else { while (CountConsecutiveUnusedKeys(true) < MinGapLimit) { newKeys.Add(GenerateNewKey(SmartLabel.Empty, KeyState.Clean, true, toFile: false)); } while (CountConsecutiveUnusedKeys(false) < MinGapLimit) { newKeys.Add(GenerateNewKey(SmartLabel.Empty, KeyState.Clean, false, toFile: false)); } } if (newKeys.Any()) { ToFile(); } return newKeys; } /// <summary> /// Make sure there's always locked internal keys generated and indexed. /// </summary> public bool AssertLockedInternalKeysIndexed(int howMany = 14) { var generated = false; while (GetKeys(KeyState.Locked, true).Count() < howMany) { GenerateNewKey(SmartLabel.Empty, KeyState.Locked, true, toFile: false); generated = true; } if (generated) { ToFile(); } return generated; } private void SetMinGapLimit(int? minGapLimit) { MinGapLimit = minGapLimit is int val ? Math.Max(AbsoluteMinGapLimit, val) : AbsoluteMinGapLimit; // AssertCleanKeysIndexed(); Do not do this. Wallet file is null yet. } private void ToFileNoBlockchainStateLock() { lock (HdPubKeysLock) { lock (ToFileLock) { ToFileNoLock(); } } } private void ToFileNoLock() { if (FilePath is null) { return; } ToFileNoLock(FilePath); } private void ToFileNoLock(string filePath) { IoHelpers.EnsureContainingDirectoryExists(filePath); // Remove the last 100 blocks to ensure verification on the next run. This is needed of reorg. int maturity = 101; Height prevHeight = BlockchainState.Height; int matureHeight = Math.Max(0, prevHeight.Value - maturity); BlockchainState.Height = new Height(matureHeight); string jsonString = JsonConvert.SerializeObject(this, Formatting.Indented); File.WriteAllText(filePath, jsonString, Encoding.UTF8); // Re-add removed items for further operations. BlockchainState.Height = prevHeight; } public void SetLastAccessTimeForNow() { if (FilePath is { }) { // Set the LastAccessTime. new FileInfo(FilePath) { LastAccessTimeUtc = DateTime.UtcNow }; } } public DateTime GetLastAccessTime() { if (FilePath is { }) { // Set the LastAccessTime. return new FileInfo(FilePath).LastAccessTimeUtc; } else { return DateTime.UtcNow; } } #region BlockchainState public Height GetBestHeight() { Height res; lock (BlockchainStateLock) { res = BlockchainState.Height; } return res; } public void SetNetwork(Network network) { lock (BlockchainStateLock) { BlockchainState.Network = network; ToFileNoBlockchainStateLock(); } } public Network GetNetwork() { lock (BlockchainStateLock) { return BlockchainState.Network; } } public void SetBestHeight(Height height) { lock (BlockchainStateLock) { BlockchainState.Height = height; ToFileNoBlockchainStateLock(); } } public void SetMaxBestHeight(Height height) { lock (BlockchainStateLock) { var prevHeight = BlockchainState.Height; var newHeight = Math.Min(prevHeight, height); if (prevHeight != newHeight) { BlockchainState.Height = newHeight; ToFileNoBlockchainStateLock(); Logger.LogWarning($"Wallet ({WalletName}) height has been set back by {prevHeight - newHeight}. From {prevHeight} to {newHeight}."); } } } public void SetIcon(string icon) { Icon = icon; ToFile(); } public void SetIcon(WalletType type) { SetIcon(type.ToString()); } public void AssertNetworkOrClearBlockState(Network expectedNetwork) { lock (BlockchainStateLock) { var lastNetwork = BlockchainState.Network; if (lastNetwork is null || lastNetwork != expectedNetwork) { BlockchainState.Network = expectedNetwork; BlockchainState.Height = 0; ToFileNoBlockchainStateLock(); if (lastNetwork is { }) { Logger.LogWarning($"Wallet is opened on {expectedNetwork}. Last time it was opened on {lastNetwork}."); } Logger.LogInfo("Blockchain cache is cleared."); } } } #endregion BlockchainState } }
using System; using System.Collections; using System.Collections.Generic; namespace Eto.Forms { /// <summary> /// Translates an <see cref="IDataStore{T}"/> to a read-only <see cref="IList{T}"/> /// </summary> /// <remarks> /// This is typically used to pass the data store to controls that require a standard collection /// </remarks> public class DataStoreVirtualCollection<T> : IList<T>, IList { const string ReadOnlyErrorMsg = "DataStoreVirtualCollection is a read-only collection."; readonly IDataStore<T> store; /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.DataStoreVirtualCollection{T}"/> class. /// </summary> /// <param name="store">Store.</param> public DataStoreVirtualCollection(IDataStore<T> store) { this.store = store; } #region IList<T> Members /// <summary> /// Determines the index of a specific item in the collection. /// </summary> /// <returns>The index of the item if found, or -1 if not found</returns> /// <param name="item">Item to find the index</param> public int IndexOf(T item) { return IndexOf(item); } /// <summary> /// Inserts an item at the specified index. This collection is read-only so this throws an exception. /// </summary> /// <param name="index">Index to add the item</param> /// <param name="item">Item to add</param> public void Insert(int index, T item) { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <summary> /// Removes the item at the specified index. This collection is read-only so this throws an exception. /// </summary> /// <param name="index">Index of the item to remove</param> public void RemoveAt(int index) { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <summary> /// Gets or sets the item at the specified index. This collection is read-only so setting the item throws an exception. /// </summary> /// <param name="index">Index.</param> public T this [int index] { get { return store[index]; } set { throw new NotSupportedException(ReadOnlyErrorMsg); } } #endregion #region ICollection<T> Members /// <summary> /// Adds an item to the current collection. This collection is read-only so this throws an exception. /// </summary> /// <param name="item">The item to add to the current collection.</param> public void Add(T item) { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <summary> /// Clears all items from the collection. This collection is read-only so this throws an exception. /// </summary> public void Clear() { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <Docs>The object to locate in the current collection.</Docs> /// <para>Determines whether the current collection contains a specific value.</para> /// <summary> /// Determines whether the current collection contains a specific value. /// </summary> /// <param name="item">The object to locate in the current collection.</param> public bool Contains(T item) { return (IndexOf(item) != -1); } /// <summary> /// Copies the contents of the collection to the specified array starting at the specified index /// </summary> /// <param name="array">Array to copy to</param> /// <param name="arrayIndex">Index in the array to start copying to</param> public void CopyTo(T[] array, int arrayIndex) { for (int i = 0; i < Count; i++) { array[arrayIndex + i] = this[i]; } } /// <summary> /// Gets the count of items in this collection /// </summary> /// <value>The count.</value> public int Count { get { return store == null ? 0 : store.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return true; } } /// <summary> /// Remove the specified item. This collection is read-only so this throws an exception. /// </summary> /// <param name="item">Item to remove</param> public bool Remove(T item) { throw new NotSupportedException(ReadOnlyErrorMsg); } #endregion #region IEnumerable<T> Members /// <summary> /// Gets the enumerator for the collection /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<T> GetEnumerator() { return new DataStoreEnumerator(this); } #endregion #region IList Members /// <summary> /// Adds an item to the current collection. /// </summary> /// <param name="value">The item to add to the current collection</param> public int Add(object value) { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <summary> /// Determines whether the current collection contains a specific value. /// </summary> /// <param name="value">The object to locate in the current collection.</param> public bool Contains(object value) { throw new NotImplementedException(); } /// <summary> /// Determines the index of a specific item in the current instance. /// </summary> /// <returns>Index of the item if found, or -1 if not in the collection</returns> /// <param name="value">Value to find</param> public int IndexOf(object value) { int count = store.Count; for (int index = 0; index < count; ++index) { if (store[index].Equals(value)) return index; } return -1; } /// <summary> /// Insert a value into the collection with the specified index /// </summary> /// <param name="index">Index to add the item</param> /// <param name="value">Value to add</param> public void Insert(int index, object value) { throw new NotSupportedException(ReadOnlyErrorMsg); } /// <summary> /// Gets a value indicating whether this instance is fixed size. /// </summary> /// <value><c>true</c> if this instance is fixed size; otherwise, <c>false</c>.</value> public bool IsFixedSize { get { return true; } } /// <summary> /// Removes the first occurrence of an item from the current collection. /// </summary> /// <param name="value">The item to remove from the current collection.</param> public void Remove(object value) { throw new NotSupportedException(ReadOnlyErrorMsg); } object IList.this [int index] { get { return this[index]; } set { throw new NotSupportedException(ReadOnlyErrorMsg); } } #endregion #region ICollection Members /// <summary> /// Copies the contents of the collection to the specified array starting at the specified index /// </summary> /// <param name="array">Array to copy to</param> /// <param name="index">Index in the array to start copying to</param> public void CopyTo(Array array, int index) { for (int i = 0; i < Count; i++) { array.SetValue(this[i], index + i); } } /// <summary> /// Gets a value indicating whether this instance is synchronized. /// </summary> /// <value><c>true</c> if this instance is synchronized; otherwise, <c>false</c>.</value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets the sync root. /// </summary> /// <value>The sync root.</value> public object SyncRoot { get { return this; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new DataStoreEnumerator(this); } #endregion #region Internal IEnumerator implementation class DataStoreEnumerator : IEnumerator<T> { readonly DataStoreVirtualCollection<T> collection; int cursor; public DataStoreEnumerator(DataStoreVirtualCollection<T> collection) { this.collection = collection; this.cursor = -1; } #region IEnumerator<T> Members public T Current { get { return collection[cursor]; } } #endregion #region IEnumerator Members object IEnumerator.Current { get { return Current; } } public bool MoveNext() { cursor++; return cursor != collection.Count; } public void Reset() { cursor = -1; } #endregion #region IDisposable Members public void Dispose() { } #endregion } #endregion } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /*! \brief This class represents a Medium \details A Medium is an area closed by a something that is permeable or not. Each Medium contains a list of molecules which contains the concentration of each kind of molecules. Each Medium also has a list of reactions. You can define molecule diffusion between mediums with Fick or ActiveTransport. \sa Fick \sa ActiveTransport */ using System.Xml; public class Medium : LoadableFromXmlImpl { private LinkedList<Reaction> _reactions; //!< The list of reactions private Dictionary<string, Molecule> _molecules; //!< The list of molecules (Molecule) private int _numberId; //!< The id of the Medium private string _name; //!< The name of the Medium private string _reactionsSet; //!< The ReactionSet id assigned to this Medium private string _moleculesSet; //!< The MoleculeSet id assigned to this Medium private bool _enableSequential; private bool _enableNoise; private NumberGenerator _numberGenerator; //!< Random number generator private bool _enableEnergy; private float _energy; //!< Represents the quantity of ATP private float _energyVariation; //!< The variation of energy during one frame private const float _energyVariationFactor = 0.3f; private float _maxEnergy; //!< The maximum quantity of ATP private float _energyProductionRate; //!< The energy production speed public bool enableShufflingReactionOrder; //!< Enables shuffling of reactions //TODO refactor interactions out of medium private const string _shortkeyPlusSuffix = ".PLUS"; private const string _shortkeyMinusSuffix = ".MINUS"; private const string _characterMediumName = "Cellia"; private const string _mediumTag = "Medium"; public void setId(int id) { _numberId = id; } public int getId() { return _numberId; } public void setName(string name) { _name = name; } public string getName() { return _name; } public void setReactions(LinkedList<Reaction> RL) { _reactions = RL; } public LinkedList<Reaction> getReactions() { return _reactions; } public void setReactionSet(string reactionsSet) { _reactionsSet = reactionsSet; } public string getReactionSet() { return _reactionsSet; } public void setMoleculeSet(string moleculesSet) { _moleculesSet = moleculesSet; } public string getMoleculeSet() { return _moleculesSet; } public Dictionary<string, Molecule> getMolecules() { return _molecules; } //TODO extract energy methods and fields and make class out of it public void setEnergy(float v) { _energy = Mathf.Min(v, _maxEnergy); if (_energy < 0f) _energy = 0f; } public float getEnergy() { return _energy; } public void addEnergy(float v) { addVariation(v); //_energy += v; if (_energy < 0) _energy = 0f; else if (_energy > _maxEnergy) _energy = _maxEnergy; } public void subEnergy(float v) { addVariation(-v); //_energy -= v; if (_energy < 0) _energy = 0f; else if (_energy > _maxEnergy) _energy = _maxEnergy; } public void setMaxEnergy(float v) { _maxEnergy = v; if (_maxEnergy < 0f) _maxEnergy = 0f; } public float getMaxEnergy() { return _maxEnergy; } public void setEnergyProductionRate(float v) { _energyProductionRate = v; } public float getEnergyProductionRate() { return _energyProductionRate; } public float getEnergyVariation() { return _energyVariation; } public void addVariation(float variation) { _energyVariation += variation; } public void applyVariation() { _energy += _energyVariation * _energyVariationFactor; if (_energy <= 0f) _energy = 0f; else if (_energy >= _maxEnergy) _energy = _maxEnergy; ResetVariation(); } public void resetMolecules() { foreach (Molecule m in _molecules.Values) { m.setConcentration(0); } } // Reset the variation value : called at the end of the update public void ResetVariation() { _energyVariation = 0f; } public void enableEnergy(bool b) { _enableEnergy = b; foreach (Reaction r in _reactions) r.enableEnergy = b; } public void enableSequential(bool b) { _enableSequential = b; foreach (Reaction r in _reactions) r.enableSequential = b; } public void enableNoise(bool b) { _enableNoise = b; } /*! \brief Add a new reaction to the medium \param reaction The reaction to add. */ public void addReaction(Reaction reaction) { // Debug.Log(this.GetType() + " addReaction to medium#"+_numberId+" with "+reaction); if (reaction != null) { reaction.setMedium(this); reaction.enableEnergy = _enableEnergy; _reactions.AddLast(reaction); // Debug.Log(this.GetType() + " addReaction _reactions="+Logger.ToString<Reaction>(_reactions)); } else { Debug.LogWarning(this.GetType() + " addReaction Cannot add this reaction because null was given"); } } /* ! \brief Remove the reaction that has the given name \param name The name of the reaction to remove. */ public void removeReactionByName(string name) { LinkedListNode<Reaction> node = _reactions.First; bool b = true; while (node != null && b) { if (node.Value.getName() == name) { _reactions.Remove(node); b = false; } node = node.Next; } } /* ! \brief Remove the reaction that has the same characteristics as the one given as parameter \param reaction The model of reaction to remove. \param checkNameAndMedium Whether the name and medium must be taken into account or not. */ public void removeReaction(Reaction reaction, bool checkNameAndMedium) { LinkedListNode<Reaction> node = _reactions.First; bool b = true; while (node != null && b) { if (node.Value.Equals(reaction, checkNameAndMedium)) { _reactions.Remove(node); b = false; } node = node.Next; } if (b) { Debug.LogWarning(this.GetType() + " removeReaction failed to find matching reaction"); } else { // Debug.Log(this.GetType() + " removeReaction successfully removed matching reaction"); } } /*! \brief Substract a concentration to molecule corresponding to the name. \param name The name of the Molecules. \param value The value to substract. */ public void subMolConcentration(string name, float value) { Molecule mol = ReactionEngine.getMoleculeFromName(name, _molecules); if (mol != null) mol.setConcentration(mol.getConcentration() - value); } /*! \brief Add a concentration to molecule corresponding to the name. \param name The name of the Molecules. \param value The value to Add. */ public void addMolConcentration(string name, float value) { Molecule mol = ReactionEngine.getMoleculeFromName(name, _molecules); if (mol != null) mol.setConcentration(mol.getConcentration() + value); } /*! \brief Load reactions from a ReactionSet \param reactionsSet The set to load */ public void initReactionsFromReactionSet(ReactionSet reactionsSet) { if (reactionsSet == null) return; foreach (Reaction reaction in reactionsSet.reactions) addReaction(Reaction.copyReaction(reaction)); // _reactions.AddLast(reaction); } /*! \brief Load degradation from each molecules \param allMolecules The list of all the molecules */ public void initDegradationReactions(Dictionary<string, Molecule> allMolecules) { foreach (Molecule mol in allMolecules.Values) addReaction(new Degradation(mol.getDegradationRate(), mol.getName())); } /*! \brief Load Molecules from a MoleculeSet \param molSet The set to Load \param allMolecules The list of all the molecules */ public void initMoleculesFromMoleculeSets(MoleculeSet molSet, Dictionary<string, Molecule> allMolecules) { // Debug.Log(this.GetType() + " initMoleculesFromMoleculeSets medium#" + _numberId); Molecule newMol; Molecule startingMolStatus; _molecules = new Dictionary<string, Molecule>(); foreach (Molecule mol in allMolecules.Values) { newMol = new Molecule(mol); startingMolStatus = ReactionEngine.getMoleculeFromName(mol.getName(), molSet.molecules); if (startingMolStatus == null) { newMol.setConcentration(0); } else { newMol.setConcentration(startingMolStatus.getConcentration()); } // Debug.Log(this.GetType() + " initMoleculesFromMoleculeSets medium#" + _numberId // + " add mol " + newMol.getName() // + " with cc=" + newMol.getConcentration() // // ); _molecules.Add(newMol.getName(), newMol); } } /*! \brief This function initialize the production of ATP. \details It create a reaction of type ATPProducer */ private void initATPProduction() { ATPProducer reaction = new ATPProducer(); reaction.setProduction(_energyProductionRate); reaction.setName("ATP Production"); if (_reactions == null) setReactions(new LinkedList<Reaction>()); addReaction(reaction); } /*! \brief Initialize the Medium \param reactionsSets The list of all the reactions sets \param moleculesSets The list of all the molecules sets */ public void Init(LinkedList<ReactionSet> reactionsSets, LinkedList<MoleculeSet> moleculesSets) { //Receive a linkedlist of Sets _reactions = new LinkedList<Reaction>(); _numberGenerator = new NumberGenerator(NumberGenerator.normale, -10f, 10f, 0.01f); //Try to find the good set in the LinkedList ReactionSet reactSet = ReactionEngine.getReactionSetFromId(_reactionsSet, reactionsSets); MoleculeSet molSet = ReactionEngine.getMoleculeSetFromId(_moleculesSet, moleculesSets); //Put all the different molecules from the linkedList in an arrayList var allMolecules = ReactionEngine.getAllMoleculesFromMoleculeSets(moleculesSets); if (reactSet == null) Debug.LogWarning(this.GetType() + " Init Cannot find group of reactions named " + _reactionsSet); if (molSet == null) Debug.LogWarning(this.GetType() + " Init Cannot find group of molecules named" + _moleculesSet); initATPProduction(); initReactionsFromReactionSet(reactSet); initMoleculesFromMoleculeSets(molSet, allMolecules); initDegradationReactions(allMolecules); foreach (Reaction r in _reactions) { r.enableSequential = _enableSequential; } } /*! \brief Set the concentration of each molecules of the medium to their new values \details Called only if sequential is disabled */ public void updateMoleculesConcentrations() { foreach (Molecule m in _molecules.Values) m.updateConcentration(); } /*! \brief Debug the concentration of each molecules of the medium */ public void Log() { string content = ""; foreach (Molecule m in _molecules.Values) { if (!string.IsNullOrEmpty(content)) { content += ", "; } content += m.ToString(); } // Debug.Log(this.GetType() + " debug() #" + _numberId + "[" + content + "]"); } /*! \brief Execute everything about simulation into the Medium */ public void Update() { if (enableShufflingReactionOrder) LinkedListExtensions.Shuffle<Reaction>(_reactions); foreach (Reaction reaction in _reactions) { // PromoterReaction promoter = reaction as PromoterReaction; // if (promoter != null) { // Debug.Log(this.GetType() + " Update reaction.react("+_molecules+") with reaction="+reaction); // } reaction.react(_molecules); } applyVariation(); if (_enableNoise) { float noise; foreach (Molecule m in _molecules.Values) { noise = _numberGenerator.getNumber(); if (_enableSequential) m.addConcentration(noise); else m.addNewConcentration(noise); } } //TODO improve check that it's the medium of the character //TODO refactor interactions out of medium if (_name == _characterMediumName) { if (GameConfiguration.isAdmin) { //TODO optimize manageMoleculeConcentrationWithKey("AMPI"); manageMoleculeConcentrationWithKey("AMPR"); manageMoleculeConcentrationWithKey("ATC"); manageMoleculeConcentrationWithKey("FLUO1"); manageMoleculeConcentrationWithKey("FLUO2"); manageMoleculeConcentrationWithKey("IPTG"); manageMoleculeConcentrationWithKey("MOV"); manageMoleculeConcentrationWithKey("REPR1"); manageMoleculeConcentrationWithKey("REPR2"); manageMoleculeConcentrationWithKey("REPR3"); // manageMoleculeConcentrationWithKey("REPR4"); } } } private class MoleculeShortcut { public string shortCutPlus; public string shortCutMinus; public Molecule molecule; public MoleculeShortcut(string sCPlus, string sCMinus, Molecule mol) { this.shortCutPlus = sCPlus; this.shortCutMinus = sCMinus; this.molecule = mol; } } private Dictionary<string, MoleculeShortcut> _shortcuts = new Dictionary<string, MoleculeShortcut>(); private MoleculeShortcut _shortCut; private Molecule _molecule; //TODO refactor interactions out of medium private void manageMoleculeConcentrationWithKey(String molecule) { _shortCut = null; _shortcuts.TryGetValue(molecule, out _shortCut); if (null == _shortCut) { _molecule = ReactionEngine.getMoleculeFromName(molecule, _molecules); if (null != _molecule) { _shortCut = new MoleculeShortcut( GameStateController.keyPrefix + molecule + _shortkeyPlusSuffix, GameStateController.keyPrefix + molecule + _shortkeyMinusSuffix, _molecule ); _shortcuts.Add(molecule, _shortCut); } else { Debug.LogWarning(this.GetType() + " molecule " + molecule + " not found"); return; } } if (GameStateController.isShortcutKey(_shortCut.shortCutPlus)) { if (_enableSequential) _shortCut.molecule.addConcentration(10f); else _shortCut.molecule.addNewConcentration(100f); } if (GameStateController.isShortcutKey(_shortCut.shortCutMinus)) { if (_enableSequential) _shortCut.molecule.addConcentration(-10f); else _shortCut.molecule.addNewConcentration(-100f); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// loading methods ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*! * \brief Load medium files * \details This class loads everything about mediums from medium files A medium file should respect this syntax: <Mediums> <Medium type="Cellia"> <Id>01</Id> -> Unique ID of the medium <Name>Cellia</Name> -> Name of the medium <ReactionSet>CelliaReactions</ReactionSet> -> ReactionSet to load in the medium <MoleculeSet>CelliaMolecules</MoleculeSet> -> MoleculeSet to load in the medium <Energy>1000</Energy> -> Initial Energy <MaxEnergy>2000</MaxEnergy> -> Maximal energy <EnergyProductionRate>10</EnergyProductionRate> -> The energy production speed </Medium> </Mediums> * * \sa ReactionSet * \sa MoleculeSet * \sa Medium */ public override string getTag() { return _mediumTag; } /*! \brief This function load the initial energy of the medium and parse the validity of the given string \param value The value to parse and load \param med The medium to initialize \return Return true if the function succeeded to parse the string or false else */ private bool loadEnergy(string value) { if (String.IsNullOrEmpty(value)) { // Debug.Log(this.GetType() + " Error: Empty Energy field. default value = 0"); setEnergy(0f); } else setEnergy(parseFloat(value)); return true; } /*! \brief This function load the energy production rate of the medium and parse the validity of the given string \param value The value to parse and load \param med The medium to initialize \return Return true if the function succeeded to parse the string or false else */ private bool loadEnergyProductionRate(string value) { float productionRate; if (String.IsNullOrEmpty(value)) { // Debug.Log(this.GetType() + " Error: Empty EnergyProductionRate field. default value = 0"); productionRate = 0f; } else productionRate = parseFloat(value); setEnergyProductionRate(productionRate); return true; } /*! \brief This function load the maximum energy in the medium and parse the validity of the given string \param value The value to parse and load \param med The medium to initialize \return Return true if the function succeeded to parse the string or false else */ private bool loadMaxEnergy(string value) { float prodMax; if (String.IsNullOrEmpty(value)) { // Debug.Log(this.GetType() + " Error: Empty EnergyProductionRate field. default value = 0"); prodMax = 0f; } else prodMax = parseFloat(value); setMaxEnergy(prodMax); return true; } /*! \brief This function create a new Medium based on the information in the given XML Node \param node The XmlNode to load. */ public override bool tryInstantiateFromXml(XmlNode node) { // Debug.Log(this.GetType() + " tryInstantiateFromXml(" + Logger.ToString(node) + ")"); foreach (XmlNode attr in node) { if (null == attr) { continue; } switch (attr.Name) { case "Id": setId(Convert.ToInt32(attr.InnerText)); break; case "Name": setName(attr.InnerText); break; case "Energy": loadEnergy(attr.InnerText); break; case "EnergyProductionRate": loadEnergyProductionRate(attr.InnerText); break; case "MaxEnergy": loadMaxEnergy(attr.InnerText); break; case "ReactionSet": setReactionSet(attr.InnerText); break; case "MoleculeSet": setMoleculeSet(attr.InnerText); break; } } if ( //_reactions; //!< The list of reactions //_molecules; //!< The list of molecules (Molecule) (0 == _numberId) || (string.IsNullOrEmpty(_name)) //!< The name of the Medium || string.IsNullOrEmpty(_reactionsSet) //!< The ReactionSet id assigned to this Medium || string.IsNullOrEmpty(_moleculesSet) //!< The MoleculeSet id assigned to this Medium //_enableSequential; //_enableNoise; //_numberGenerator //!< Random number generator (initialized in Init) //_enableEnergy; //_energy; //!< Represents the quantity of ATP //_energyVariation; //!< The variation of energy during one frame //_maxEnergy; //!< The maximum quantity of ATP //_energyProductionRate; //!< The energy production speed ) { Debug.LogError("Medium.tryInstantiateFromXml failed to load because " + "_numberId=" + _numberId + "& _name=" + _name + "& _reactionsSet=" + _reactionsSet + "& _moleculesSet=" + _moleculesSet ); return false; } else { // Debug.Log(this.GetType() + " tryInstantiateFromXml(node) loaded this=" + this); return true; } } public override string ToString() { string moleculeString = null == _molecules ? "" : _molecules.Count.ToString(); string reactionString = null == _reactions ? "" : _reactions.Count.ToString(); return "[Medium " + "name:" + _name + "; id:" + _numberId + "; molecules:" + moleculeString + "; reactions:" + reactionString + "]"; } public string ToStringDetailed() { string moleculeString = null == _molecules ? "" : Logger.ToString<Molecule>("Molecule", _molecules); string reactionString = null == _reactions ? "" : Logger.ToString<Reaction>(_reactions); return "[Medium " + "name:" + _name + "; id:" + _numberId + "; molecules:" + moleculeString + "; reactions:" + reactionString + "]"; } }
// // ExtensionNodeDescription.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Collections.Specialized; using Mono.Addins.Serialization; namespace Mono.Addins.Description { /// <summary> /// An extension node definition. /// </summary> public class ExtensionNodeDescription: ObjectDescription, NodeElement { ExtensionNodeDescriptionCollection childNodes; string[] attributes; string nodeName; /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.ExtensionNodeDescription"/> class. /// </summary> /// <param name='nodeName'> /// Node name. /// </param> public ExtensionNodeDescription (string nodeName) { this.nodeName = nodeName; } internal ExtensionNodeDescription (XmlElement elem) { Element = elem; nodeName = elem.LocalName; } internal ExtensionNodeDescription () { } /// <summary> /// Gets the type of the node. /// </summary> /// <returns> /// The node type. /// </returns> /// <remarks> /// This method only works when the add-in description to which the node belongs has been /// loaded from an add-in registry. /// </remarks> public ExtensionNodeType GetNodeType () { if (Parent is Extension) { Extension ext = (Extension) Parent; object ob = ext.GetExtendedObject (); if (ob is ExtensionPoint) { ExtensionPoint ep = (ExtensionPoint) ob; return ep.NodeSet.GetAllowedNodeTypes () [NodeName]; } else if (ob is ExtensionNodeDescription) { ExtensionNodeDescription pn = (ExtensionNodeDescription) ob; ExtensionNodeType pt = ((ExtensionNodeDescription) pn).GetNodeType (); if (pt != null) return pt.GetAllowedNodeTypes () [NodeName]; } } else if (Parent is ExtensionNodeDescription) { ExtensionNodeType pt = ((ExtensionNodeDescription) Parent).GetNodeType (); if (pt != null) return pt.GetAllowedNodeTypes () [NodeName]; } return null; } /// <summary> /// Gets the extension path under which this node is registered /// </summary> /// <returns> /// The parent path. /// </returns> /// <remarks> /// For example, if the id of the node is 'ThisNode', and the node is a child of another node with id 'ParentNode', and /// that parent node is defined in an extension with the path '/Core/MainExtension', then the parent path is 'Core/MainExtension/ParentNode'. /// </remarks> public string GetParentPath () { if (Parent is Extension) return ((Extension)Parent).Path; else if (Parent is ExtensionNodeDescription) { ExtensionNodeDescription pn = (ExtensionNodeDescription) Parent; return pn.GetParentPath () + "/" + pn.Id; } else return string.Empty; } internal override void Verify (string location, StringCollection errors) { if (nodeName == null || nodeName.Length == 0) errors.Add (location + "Node: NodeName can't be empty."); ChildNodes.Verify (location + NodeName + "/", errors); } /// <summary> /// Gets or sets the name of the node. /// </summary> /// <value> /// The name of the node. /// </value> public string NodeName { get { return nodeName; } internal set { if (Element != null) throw new InvalidOperationException ("Can't change node name of xml element"); nodeName = value; } } /// <summary> /// Gets or sets the identifier of the node. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get { return GetAttribute ("id"); } set { SetAttribute ("id", value); } } /// <summary> /// Gets or sets the identifier of the node after which this node has to be inserted /// </summary> /// <value> /// The identifier of the reference node /// </value> public string InsertAfter { get { return GetAttribute ("insertafter"); } set { if (value == null || value.Length == 0) RemoveAttribute ("insertafter"); else SetAttribute ("insertafter", value); } } /// <summary> /// Gets or sets the identifier of the node before which this node has to be inserted /// </summary> /// <value> /// The identifier of the reference node /// </value> public string InsertBefore { get { return GetAttribute ("insertbefore"); } set { if (value == null || value.Length == 0) RemoveAttribute ("insertbefore"); else SetAttribute ("insertbefore", value); } } /// <summary> /// Gets a value indicating whether this node is a condition. /// </summary> /// <value> /// <c>true</c> if this node is a condition; otherwise, <c>false</c>. /// </value> public bool IsCondition { get { return nodeName == "Condition" || nodeName == "ComplexCondition"; } } internal override void SaveXml (XmlElement parent) { CreateElement (parent, nodeName); if (attributes != null) { for (int n = 0; n < attributes.Length; n += 2) Element.SetAttribute (attributes [n], attributes [n + 1]); } ChildNodes.SaveXml (Element); } /// <summary> /// Gets the value of an attribute. /// </summary> /// <returns> /// The value of the attribute, or an empty string if the attribute is not defined. /// </returns> /// <param name='key'> /// Name of the attribute. /// </param> public string GetAttribute (string key) { if (Element != null) return Element.GetAttribute (key); if (attributes == null) return string.Empty; for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == key) return attributes [n+1]; } return string.Empty; } /// <summary> /// Sets the value of an attribute. /// </summary> /// <param name='key'> /// Name of the attribute /// </param> /// <param name='value'> /// The value. /// </param> public void SetAttribute (string key, string value) { if (Element != null) { Element.SetAttribute (key, value); return; } if (value == null) value = string.Empty; if (attributes == null) { attributes = new string [2]; attributes [0] = key; attributes [1] = value; return; } for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == key) { attributes [n+1] = value; return; } } string[] newList = new string [attributes.Length + 2]; attributes.CopyTo (newList, 0); attributes = newList; attributes [attributes.Length - 2] = key; attributes [attributes.Length - 1] = value; } /// <summary> /// Removes an attribute. /// </summary> /// <param name='name'> /// Name of the attribute to remove. /// </param> public void RemoveAttribute (string name) { if (Element != null) { Element.RemoveAttribute (name); return; } if (attributes == null) return; for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == name) { string[] newar = new string [attributes.Length - 2]; Array.Copy (attributes, 0, newar, 0, n); Array.Copy (attributes, n+2, newar, n, attributes.Length - n - 2); attributes = newar; break; } } } /// <summary> /// Gets the attributes of the node. /// </summary> /// <value> /// The attributes. /// </value> public NodeAttribute[] Attributes { get { string [] result = SaveXmlAttributes (); if (result == null || result.Length == 0) return new NodeAttribute [0]; NodeAttribute[] ats = new NodeAttribute [result.Length / 2]; for (int n=0; n<ats.Length; n++) { NodeAttribute at = new NodeAttribute (); at.name = result [n*2]; at.value = result [n*2 + 1]; ats [n] = at; } return ats; } } /// <summary> /// Gets the child nodes. /// </summary> /// <value> /// The child nodes. /// </value> public ExtensionNodeDescriptionCollection ChildNodes { get { if (childNodes == null) { childNodes = new ExtensionNodeDescriptionCollection (this); if (Element != null) { foreach (XmlNode nod in Element.ChildNodes) { if (nod is XmlElement) childNodes.Add (new ExtensionNodeDescription ((XmlElement)nod)); } } } return childNodes; } } NodeElementCollection NodeElement.ChildNodes { get { return ChildNodes; } } string[] SaveXmlAttributes () { if (Element != null) { var result = new string [Element.Attributes.Count * 2]; for (int n = 0; n < result.Length; n += 2) { XmlAttribute at = Element.Attributes [n / 2]; result [n] = at.LocalName; result [n + 1] = at.Value; } return result; } return attributes; } internal override void Write (BinaryXmlWriter writer) { writer.WriteValue ("nodeName", nodeName); writer.WriteValue ("attributes", SaveXmlAttributes ()); writer.WriteValue ("ChildNodes", ChildNodes); } internal override void Read (BinaryXmlReader reader) { nodeName = reader.ReadStringValue ("nodeName"); attributes = (string[]) reader.ReadValue ("attributes"); childNodes = (ExtensionNodeDescriptionCollection) reader.ReadValue ("ChildNodes", new ExtensionNodeDescriptionCollection (this)); } } }
using System.Security.Claims; using System.Threading.Tasks; using AllReady.Areas.Admin.Controllers; using AllReady.Configuration; using AllReady.Constants; using AllReady.Features.Login; using AllReady.Features.Manage; using AllReady.Models; using AllReady.Providers.ExternalUserInformationProviders; using AllReady.Security; using AllReady.ViewModels.Account; using MediatR; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.Options; using UserType = AllReady.Models.UserType; namespace AllReady.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IOptions<GeneralSettings> _generalSettings; private readonly IMediator _mediator; private readonly IExternalUserInformationProviderFactory _externalUserInformationProviderFactory; private readonly IRedirectAccountControllerRequests _redirectAccountControllerRequests; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IOptions<GeneralSettings> generalSettings, IMediator mediator, IExternalUserInformationProviderFactory externalUserInformationProviderFactory, IRedirectAccountControllerRequests redirectAccountControllerRequests ) { _userManager = userManager; _signInManager = signInManager; _generalSettings = generalSettings; _mediator = mediator; _externalUserInformationProviderFactory = externalUserInformationProviderFactory; _redirectAccountControllerRequests = redirectAccountControllerRequests; } // GET: /Account/Login [HttpGet] [AllowAnonymous] public async Task<IActionResult> Login(string returnUrl = null) { await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ViewData["ReturnUrl"] = returnUrl; return View(); } // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // Require admin users to have a confirmed email before they can log on. var user = await _mediator.SendAsync(new ApplicationUserQuery { UserName = model.Email }); if (user != null) { var isAdminUser = user.IsUserType(UserType.OrgAdmin) || user.IsUserType(UserType.SiteAdmin); if (isAdminUser && !await _userManager.IsEmailConfirmedAsync(user)) { //TODO: Showing the error page here makes for a bad experience for the user. //It would be better if we redirected to a specific page prompting the user to check their email for a confirmation email and providing an option to resend the confirmation email. ViewData["Message"] = "You must have a confirmed email to log on."; return View("Error"); } } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true); if (result.Succeeded) { return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(AdminController.SendCode), AreaNames.Admin, new { ReturnUrl = returnUrl, model.RememberMe }); } if (result.IsLockedOut) { return View("Lockout"); } ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } // If we got this far, something failed, redisplay form return View(model); } // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register() { return View(); } // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { FirstName = model.FirstName, LastName = model.LastName, UserName = model.Email, Email = model.Email, PhoneNumber = model.PhoneNumber, TimeZoneId = _generalSettings.Value.DefaultTimeZone }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ConfirmEmail), Controller = "Account", Values = new { userId = user.Id, token = emailConfirmationToken }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl }); var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken }); await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser")); await _signInManager.SignInAsync(user, isPersistent: false); TempData["NewAccount"] = true; return RedirectToPage("/Index"); } AddErrorsToModelState(result); } // If we got this far, something failed, redisplay form return View(model); } // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); return RedirectToPage("/Index"); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string token) { if (userId == null || token == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, token); if (result.Succeeded && user.IsProfileComplete()) { await _mediator.SendAsync(new RemoveUserProfileIncompleteClaimCommand { UserId = user.Id }); if (_signInManager.IsSignedIn(User)) { await _signInManager.RefreshSignInAsync(user); } } return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !await _userManager.IsEmailConfirmedAsync(user)) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } var code = await _userManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ResetPassword), Controller = "Account", Values = new { userId = user.Id, code }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendResetPasswordEmail { Email = model.Email, CallbackUrl = callbackUrl }); return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(ResetPasswordConfirmation)); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(ResetPasswordConfirmation)); } AddErrorsToModelState(result); return View(); } // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action(new UrlActionContext { Action = nameof(ExternalLoginCallback), Values = new { ReturnUrl = returnUrl } }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null) { var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var externalLoginSignInAsyncResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, isPersistent: false); var externalUserInformationProvider = _externalUserInformationProviderFactory.GetExternalUserInformationProvider(externalLoginInfo.LoginProvider); var externalUserInformation = await externalUserInformationProvider.GetExternalUserInformation(externalLoginInfo); if (externalLoginSignInAsyncResult.Succeeded) { if (string.IsNullOrEmpty(externalUserInformation.Email)) return View("Error"); var user = await _mediator.SendAsync(new ApplicationUserQuery { UserName = externalUserInformation.Email }); return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user); } // If the user does not have an account, then ask the user to create an account. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = externalUserInformation.Email, FirstName = externalUserInformation.FirstName, LastName = externalUserInformation.LastName, ReturnUrl = returnUrl, LoginProvider = externalLoginInfo.LoginProvider, EmailIsVerifiedByExternalLoginProvider = !string.IsNullOrEmpty(externalUserInformation.Email) }); } // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (_signInManager.IsSignedIn(User)) { return RedirectToAction(nameof(ManageController.Index), "Manage"); } if (ModelState.IsValid) { var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, TimeZoneId = _generalSettings.Value.DefaultTimeZone, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, externalLoginInfo); if (result.Succeeded) { var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); if (model.EmailIsVerifiedByExternalLoginProvider) { await _userManager.ConfirmEmailAsync(user, emailConfirmationToken); } else { var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ConfirmEmail), Controller = "Account", Values = new { userId = user.Id, token = emailConfirmationToken }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl }); } var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken }); await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser")); await _signInManager.SignInAsync(user, isPersistent: false); return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user); } } AddErrorsToModelState(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } private void AddErrorsToModelState(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } public interface IRedirectAccountControllerRequests { IActionResult RedirectToLocal(string returnUrl, ApplicationUser user); } public class RedirectAccountControllerRequests : IRedirectAccountControllerRequests { private readonly IUrlHelper _urlHelper; public RedirectAccountControllerRequests(IUrlHelper urlHelper) { _urlHelper = urlHelper; } public IActionResult RedirectToLocal(string returnUrl, ApplicationUser user) { if (_urlHelper.IsLocalUrl(returnUrl)) { return new RedirectResult(returnUrl); } if (user.IsUserType(UserType.SiteAdmin)) { return new RedirectToActionResult(nameof(SiteController.Index), "Site", new { area = AreaNames.Admin }); } if (user.IsUserType(UserType.OrgAdmin)) { return new RedirectToActionResult(nameof(Areas.Admin.Controllers.CampaignController.Index), "Campaign", new { area = AreaNames.Admin }); } return new RedirectToPageResult("/Index"); } } }
// ZlibBaseStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 15:45:15> // // ------------------------------------------------------------------ // // This module defines the ZlibBaseStream class, which is an intnernal // base class for DeflateStream, ZlibStream and GZipStream. // // ------------------------------------------------------------------ using System; using SharpCompress.Common; using SharpCompress.Common.Tar.Headers; namespace SharpCompress.Compressor.Deflate { internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } internal class ZlibBaseStream : System.IO.Stream { protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; protected internal ZlibStreamFlavor _flavor; protected internal CompressionMode _compressionMode; protected internal CompressionLevel _level; protected internal bool _leaveOpen; protected internal byte[] _workingBuffer; protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; protected internal System.IO.Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 private CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } public ZlibBaseStream(System.IO.Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen) : base() { this._flushMode = FlushType.None; //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; this._stream = stream; this._leaveOpen = leaveOpen; this._compressionMode = compressionMode; this._flavor = flavor; this._level = level; // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { crc = new CRC32(); } } protected internal bool _wantCompress { get { return (this._compressionMode == CompressionMode.Compress); } } private ZlibCodec z { get { if (_z == null) { bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (this._compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; _z.InitializeDeflate(this._level, wantRfc1950Header); } } return _z; } } private byte[] workingBuffer { get { if (_workingBuffer == null) _workingBuffer = new byte[_bufferSize]; return _workingBuffer; } } public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) crc.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; else if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); } private void finish() { if (_z == null) return; if (_streamMode == StreamMode.Writer) { bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message == null) throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); else throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) { _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); Flush(); // workitem 7159 if (_flavor == ZlibStreamFlavor.GZIP) { if (_wantCompress) { // Emit the GZIP trailer: CRC32 and size mod 2^32 int c1 = crc.Crc32Result; _stream.Write(BitConverter.GetBytes(c1), 0, 4); int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF); _stream.Write(BitConverter.GetBytes(c2), 0, 4); } else { throw new ZlibException("Writing with decompression is not supported."); } } } // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) { if (!_wantCompress) { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) return; // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 byte[] trailer = new byte[8]; // workitem 8679 if (_z.AvailableBytesIn != 8) { // Make sure we have read to the end of the stream Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn); int bytesNeeded = 8 - _z.AvailableBytesIn; int bytesRead = _stream.Read(trailer, _z.AvailableBytesIn, bytesNeeded); if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format( "Protocol error. AvailableBytesIn={0}, expected 8", _z.AvailableBytesIn + bytesRead)); } } else { Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); } Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BitConverter.ToInt32(trailer, 4); Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) throw new ZlibException( String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); if (isize_actual != isize_expected) throw new ZlibException( String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, isize_expected)); } else { throw new ZlibException("Reading with compression is not supported."); } } } } private void end() { if (z == null) return; if (_wantCompress) { _z.EndDeflate(); } else { _z.EndInflate(); } _z = null; } protected override void Dispose(bool disposing) { if (isDisposed) { return; } isDisposed = true; base.Dispose(disposing); if (disposing) { if (_stream == null) return; try { finish(); } finally { end(); if (!_leaveOpen) _stream.Dispose(); _stream = null; } } } public override void Flush() { _stream.Flush(); } public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); //_outStream.Seek(offset, origin); } public override void SetLength(System.Int64 value) { _stream.SetLength(value); } #if NOT public int Read() { if (Read(_buf1, 0, 1) == 0) return 0; // calculate CRC after reading if (crc!=null) crc.SlurpBlock(_buf1,0,1); return (_buf1[0] & 0xFF); } #endif private bool nomoreinput = false; private bool isDisposed; private string ReadZeroTerminatedString() { var list = new System.Collections.Generic.List<byte>(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) throw new ZlibException("Unexpected EOF reading GZIP header."); else { if (_buf1[0] == 0) done = true; else list.Add(_buf1[0]); } } while (!done); byte[] a = list.ToArray(); return ArchiveEncoding.Default.GetString(a, 0, a.Length); } private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; // read the header on the first read byte[] header = new byte[10]; int n = _stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) return 0; if (n != 10) throw new ZlibException("Not a valid GZIP stream."); if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) throw new ZlibException("Bad GZIP header."); Int32 timet = BitConverter.ToInt32(header, 4); _GzipMtime = TarHeader.Epoch.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field n = _stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; Int16 extraLength = (Int16)(header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) throw new ZlibException("Unexpected end-of-file reading GZIP header."); totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) _GzipFileName = ReadZeroTerminatedString(); if ((header[3] & 0x10) == 0x010) _GzipComment = ReadZeroTerminatedString(); if ((header[3] & 0x02) == 0x02) Read(_buf1, 0, 1); // CRC16, ignore return totalBytesRead; } public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; } public override System.Boolean CanRead { get { return this._stream.CanRead; } } public override System.Boolean CanSeek { get { return this._stream.CanSeek; } } public override System.Boolean CanWrite { get { return this._stream.CanWrite; } } public override System.Int64 Length { get { return _stream.Length; } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal enum StreamMode { Writer, Reader, Undefined, } } }
--- /dev/null 2016-03-16 08:01:56.000000000 -0400 +++ src/System.Threading.Tasks.Dataflow/src/SR.cs 2016-03-16 08:02:26.394959000 -0400 @@ -0,0 +1,254 @@ +using System; +using System.Resources; + +namespace FxResources.System.Threading.Tasks.Dataflow +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.Threading.Tasks.Dataflow.SR"; + + internal static String Argument_BoundedCapacityNotSupported + { + get + { + return SR.GetResourceString("Argument_BoundedCapacityNotSupported", null); + } + } + + internal static String Argument_CantConsumeFromANullSource + { + get + { + return SR.GetResourceString("Argument_CantConsumeFromANullSource", null); + } + } + + internal static String Argument_InvalidMessageHeader + { + get + { + return SR.GetResourceString("Argument_InvalidMessageHeader", null); + } + } + + internal static String Argument_InvalidMessageId + { + get + { + return SR.GetResourceString("Argument_InvalidMessageId", null); + } + } + + internal static String Argument_InvalidSourceForFilteredLink + { + get + { + return SR.GetResourceString("Argument_InvalidSourceForFilteredLink", null); + } + } + + internal static String Argument_NonGreedyNotSupported + { + get + { + return SR.GetResourceString("Argument_NonGreedyNotSupported", null); + } + } + + internal static String ArgumentOutOfRange_BatchSizeMustBeNoGreaterThanBoundedCapacity + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_BatchSizeMustBeNoGreaterThanBoundedCapacity", null); + } + } + + internal static String ArgumentOutOfRange_GenericPositive + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_GenericPositive", null); + } + } + + internal static String ArgumentOutOfRange_NeedNonNegOrNegative1 + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1", null); + } + } + + internal static String ConcurrentCollection_SyncRoot_NotSupported + { + get + { + return SR.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported", null); + } + } + + internal static String event_DataflowBlockCompleted + { + get + { + return SR.GetResourceString("event_DataflowBlockCompleted", null); + } + } + + internal static String event_DataflowBlockCreated + { + get + { + return SR.GetResourceString("event_DataflowBlockCreated", null); + } + } + + internal static String event_DataflowBlockLinking + { + get + { + return SR.GetResourceString("event_DataflowBlockLinking", null); + } + } + + internal static String event_DataflowBlockUnlinking + { + get + { + return SR.GetResourceString("event_DataflowBlockUnlinking", null); + } + } + + internal static String event_TaskLaunchedForMessageHandling + { + get + { + return SR.GetResourceString("event_TaskLaunchedForMessageHandling", null); + } + } + + internal static String InvalidOperation_DataNotAvailableForReceive + { + get + { + return SR.GetResourceString("InvalidOperation_DataNotAvailableForReceive", null); + } + } + + internal static String InvalidOperation_FailedToConsumeReservedMessage + { + get + { + return SR.GetResourceString("InvalidOperation_FailedToConsumeReservedMessage", null); + } + } + + internal static String InvalidOperation_MessageNotReservedByTarget + { + get + { + return SR.GetResourceString("InvalidOperation_MessageNotReservedByTarget", null); + } + } + + internal static String NotSupported_MemberNotNeeded + { + get + { + return SR.GetResourceString("NotSupported_MemberNotNeeded", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Threading.Tasks.Dataflow.SR); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, new Object[] { p1 }); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, new Object[] { p1, p2 }); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, new Object[] { p1, p2, p3 }); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str, StringComparison.Ordinal)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\Quat.h:28 namespace UnrealEngine { public partial class FQuat : NativeStructWrapper { public FQuat(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } /// <summary> /// Default constructor (no initialization). /// </summary> public FQuat() : base(E_CreateStruct_FQuat(), false) { } /// <summary> /// Constructor. /// </summary> /// <param name="inX">X component of the quaternion</param> /// <param name="inY">Y component of the quaternion</param> /// <param name="inZ">Z component of the quaternion</param> /// <param name="inW">W component of the quaternion</param> public FQuat(float inX, float inY, float inZ, float inW) : base(E_CreateStruct_FQuat_float_float_float_float(inX, inY, inZ, inW), false) { } /// <summary> /// Copy constructor. /// </summary> /// <param name="q">A FQuat object to use to create new quaternion from.</param> public FQuat(FQuat q) : base(E_CreateStruct_FQuat_FQuat(q), false) { } /// <summary> /// Creates and initializes a new quaternion from the given matrix. /// </summary> /// <param name="m">The rotation matrix to initialize from.</param> public FQuat(FMatrix m) : base(E_CreateStruct_FQuat_FMatrix(m), false) { } /// <summary> /// Creates and initializes a new quaternion from the given rotator. /// </summary> /// <param name="r">The rotator to initialize from.</param> public FQuat(FRotator r) : base(E_CreateStruct_FQuat_FRotator(r), false) { } /// <summary> /// Creates and initializes a new quaternion from the a rotation around the given axis. /// </summary> /// <param name="axis">assumed to be a normalized vector</param> /// <param name="angle">angle to rotate above the given axis (in radians)</param> public FQuat(FVector axis, float angleRad) : base(E_CreateStruct_FQuat_FVector_float(axis, angleRad), false) { } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FQuat_Identity_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FQuat_W_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FQuat_W_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FQuat_X_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FQuat_X_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FQuat_Y_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FQuat_Y_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FQuat_Z_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FQuat_Z_SET(IntPtr Ptr, float Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat_float_float_float_float(float inX, float inY, float inZ, float inW); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat_FQuat(IntPtr q); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat_FMatrix(IntPtr m); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat_FRotator(IntPtr r); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FQuat_FVector_float(IntPtr axis, float angleRad); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_AngularDistance(IntPtr self, IntPtr q); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_CalcTangents(IntPtr self, IntPtr prevP, IntPtr p, IntPtr nextP, float tension, IntPtr outTan); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FQuat_ContainsNaN(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_DiagnosticCheckNaN(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_EnforceShortestArcWith(IntPtr self, IntPtr otherQuat); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FQuat_Equals(IntPtr self, IntPtr q, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_Error(IntPtr self, IntPtr q1, IntPtr q2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_ErrorAutoNormalize(IntPtr self, IntPtr a, IntPtr b); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Euler(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Exp(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_FastBilerp(IntPtr self, IntPtr p00, IntPtr p10, IntPtr p01, IntPtr p11, float fracX, float fracY); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_FastLerp(IntPtr self, IntPtr a, IntPtr b, float alpha); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_FindBetween(IntPtr self, IntPtr vector1, IntPtr vector2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_FindBetweenNormals(IntPtr self, IntPtr normal1, IntPtr normal2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_FindBetweenVectors(IntPtr self, IntPtr vector1, IntPtr vector2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_GetAngle(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetAxisX(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetAxisY(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetAxisZ(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetForwardVector(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetNormalized(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetRightVector(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetRotationAxis(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_GetUpVector(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FQuat_InitFromString(IntPtr self, string inSourceString); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Inverse(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FQuat_IsIdentity(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FQuat_IsNormalized(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Log(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_MakeFromEuler(IntPtr self, IntPtr euler); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_Normalize(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_RotateVector(IntPtr self, IntPtr v); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Rotator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_Size(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FQuat_SizeSquared(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Slerp(IntPtr self, IntPtr quat1, IntPtr quat2, float slerp); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Slerp_NotNormalized(IntPtr self, IntPtr quat1, IntPtr quat2, float slerp); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_SlerpFullPath(IntPtr self, IntPtr quat1, IntPtr quat2, float alpha); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_SlerpFullPath_NotNormalized(IntPtr self, IntPtr quat1, IntPtr quat2, float alpha); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Squad(IntPtr self, IntPtr quat1, IntPtr tang1, IntPtr quat2, IntPtr tang2, float alpha); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_SquadFullPath(IntPtr self, IntPtr quat1, IntPtr tang1, IntPtr quat2, IntPtr tang2, float alpha); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_ToAxisAndAngle(IntPtr self, IntPtr axis, float angle); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FQuat_ToString(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FQuat_ToSwingTwist(IntPtr self, IntPtr inTwistAxis, IntPtr outSwing, IntPtr outTwist); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_UnrotateVector(IntPtr self, IntPtr v); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FQuat_Vector(IntPtr self); #endregion #region Property /// <summary> /// Identity quaternion. /// </summary> public static FQuat Identity { get => E_PROP_FQuat_Identity_GET(); } /// <summary> /// The quaternion's W-component. /// </summary> public float W { get => E_PROP_FQuat_W_GET(NativePointer); set => E_PROP_FQuat_W_SET(NativePointer, value); } /// <summary> /// The quaternion's X-component. /// </summary> public float X { get => E_PROP_FQuat_X_GET(NativePointer); set => E_PROP_FQuat_X_SET(NativePointer, value); } /// <summary> /// The quaternion's Y-component. /// </summary> public float Y { get => E_PROP_FQuat_Y_GET(NativePointer); set => E_PROP_FQuat_Y_SET(NativePointer, value); } /// <summary> /// The quaternion's Z-component. /// </summary> public float Z { get => E_PROP_FQuat_Z_GET(NativePointer); set => E_PROP_FQuat_Z_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Find the angular distance between two rotation quaternions (in radians) /// </summary> public float AngularDistance(FQuat q) => E_FQuat_AngularDistance(this, q); /// <summary> /// Calculate tangents between given points /// </summary> /// <param name="prevP">quaternion at P-1</param> /// <param name="p">quaternion to return the tangent</param> /// <param name="nextP">quaternion P+1</param> /// <param name="tension">todo document</param> /// <param name="outTan">Out control point</param> public void CalcTangents(FQuat prevP, FQuat p, FQuat nextP, float tension, FQuat outTan) => E_FQuat_CalcTangents(this, prevP, p, nextP, tension, outTan); /// <summary> /// Utility to check if there are any non-finite values (NaN or Inf) in this Quat. /// </summary> /// <return>true</return> public bool ContainsNaN() => E_FQuat_ContainsNaN(this); public void DiagnosticCheckNaN() => E_FQuat_DiagnosticCheckNaN(this); /// <summary> /// Enforce that the delta between this Quaternion and another one represents /// <para>the shortest possible rotation angle </para> /// </summary> public void EnforceShortestArcWith(FQuat otherQuat) => E_FQuat_EnforceShortestArcWith(this, otherQuat); /// <summary> /// Checks whether another Quaternion is equal to this, within specified tolerance. /// </summary> /// <param name="q">The other Quaternion.</param> /// <param name="tolerance">Error tolerance for comparison with other Quaternion.</param> /// <return>true</return> public bool Equals(FQuat q, float tolerance) => E_FQuat_Equals(this, q, tolerance); /// <summary> /// Error measure (angle) between two quaternions, ranged [0..1]. /// <para>Returns the hypersphere-angle between two quaternions; alignment shouldn't matter, though </para> /// @note normalized input is expected. /// </summary> public float Error(FQuat q1, FQuat q2) => E_FQuat_Error(this, q1, q2); /// <summary> /// FQuat::Error with auto-normalization. /// </summary> public float ErrorAutoNormalize(FQuat a, FQuat b) => E_FQuat_ErrorAutoNormalize(this, a, b); /// <summary> /// Convert a Quaternion into floating-point Euler angles (in degrees). /// </summary> public FVector Euler() => E_FQuat_Euler(this); /// <summary> /// @note Exp should really only be used after Log. /// <para>Assumes a quaternion with W=0 and V=theta*v (where |v| = 1). </para> /// Exp(q) = (sin(theta)*v, cos(theta)) /// </summary> public FQuat Exp() => E_FQuat_Exp(this); /// <summary> /// Bi-Linear Quaternion interpolation. /// <para>Result is NOT normalized. </para> /// </summary> public FQuat FastBilerp(FQuat p00, FQuat p10, FQuat p01, FQuat p11, float fracX, float fracY) => E_FQuat_FastBilerp(this, p00, p10, p01, p11, fracX, fracY); /// <summary> /// Fast Linear Quaternion Interpolation. /// <para>Result is NOT normalized. </para> /// </summary> public FQuat FastLerp(FQuat a, FQuat b, float alpha) => E_FQuat_FastLerp(this, a, b, alpha); /// <summary> /// Generates the 'smallest' (geodesic) rotation between two vectors of arbitrary length. /// </summary> public FQuat FindBetween(FVector vector1, FVector vector2) => E_FQuat_FindBetween(this, vector1, vector2); /// <summary> /// Generates the 'smallest' (geodesic) rotation between two normals (assumed to be unit length). /// </summary> public FQuat FindBetweenNormals(FVector normal1, FVector normal2) => E_FQuat_FindBetweenNormals(this, normal1, normal2); /// <summary> /// Generates the 'smallest' (geodesic) rotation between two vectors of arbitrary length. /// </summary> public FQuat FindBetweenVectors(FVector vector1, FVector vector2) => E_FQuat_FindBetweenVectors(this, vector1, vector2); /// <summary> /// Get the angle of this quaternion /// </summary> public float GetAngle() => E_FQuat_GetAngle(this); /// <summary> /// Get the forward direction (X axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetAxisX() => E_FQuat_GetAxisX(this); /// <summary> /// Get the right direction (Y axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetAxisY() => E_FQuat_GetAxisY(this); /// <summary> /// Get the up direction (Z axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetAxisZ() => E_FQuat_GetAxisZ(this); /// <summary> /// Get the forward direction (X axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetForwardVector() => E_FQuat_GetForwardVector(this); /// <summary> /// Get a normalized copy of this quaternion. /// <para>If it is too small, returns an identity quaternion. </para> /// </summary> /// <param name="tolerance">Minimum squared length of quaternion for normalization.</param> public FQuat GetNormalized(float tolerance) => E_FQuat_GetNormalized(this, tolerance); /// <summary> /// Get the right direction (Y axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetRightVector() => E_FQuat_GetRightVector(this); /// <summary> /// Get the axis of rotation of the Quaternion. /// <para>This is the axis around which rotation occurs to transform the canonical coordinate system to the target orientation. </para> /// For the identity Quaternion which has no such rotation, FVector(1,0,0) is returned. /// </summary> public FVector GetRotationAxis() => E_FQuat_GetRotationAxis(this); /// <summary> /// Get the up direction (Z axis) after it has been rotated by this Quaternion. /// </summary> public FVector GetUpVector() => E_FQuat_GetUpVector(this); /// <summary> /// Initialize this FQuat from a FString. /// <para>The string is expected to contain X=, Y=, Z=, W=, otherwise </para> /// this FQuat will have indeterminate (invalid) values. /// </summary> /// <param name="inSourceString">FString containing the quaternion values.</param> /// <return>true</return> public bool InitFromString(string inSourceString) => E_FQuat_InitFromString(this, inSourceString); /// <summary> /// </summary> /// <return>inverse</return> public FQuat Inverse() => E_FQuat_Inverse(this); /// <summary> /// Checks whether this Quaternion is an Identity Quaternion. /// <para>Assumes Quaternion tested is normalized. </para> /// </summary> /// <param name="tolerance">Error tolerance for comparison with Identity Quaternion.</param> /// <return>true</return> public bool IsIdentity(float tolerance) => E_FQuat_IsIdentity(this, tolerance); public bool IsNormalized() => E_FQuat_IsNormalized(this); /// <summary> /// </summary> /// <return>quaternion</return> public FQuat Log() => E_FQuat_Log(this); /// <summary> /// Convert a vector of floating-point Euler angles (in degrees) into a Quaternion. /// </summary> /// <param name="euler">the Euler angles</param> /// <return>constructed</return> public FQuat MakeFromEuler(FVector euler) => E_FQuat_MakeFromEuler(this, euler); /// <summary> /// Normalize this quaternion if it is large enough. /// <para>If it is too small, returns an identity quaternion. </para> /// </summary> /// <param name="tolerance">Minimum squared length of quaternion for normalization.</param> public void Normalize(float tolerance) => E_FQuat_Normalize(this, tolerance); /// <summary> /// Rotate a vector by this quaternion. /// </summary> /// <param name="v">the vector to be rotated</param> /// <return>vector</return> public FVector RotateVector(FVector v) => E_FQuat_RotateVector(this, v); /// <summary> /// Get the FRotator representation of this Quaternion. /// </summary> public FRotator Rotator() => E_FQuat_Rotator(this); /// <summary> /// Get the length of this quaternion. /// </summary> /// <return>The</return> public float Size() => E_FQuat_Size(this); /// <summary> /// Get the length squared of this quaternion. /// </summary> /// <return>The</return> public float SizeSquared() => E_FQuat_SizeSquared(this); /// <summary> /// Spherical interpolation. Will correct alignment. Result is normalized. /// </summary> public FQuat Slerp(FQuat quat1, FQuat quat2, float slerp) => E_FQuat_Slerp(this, quat1, quat2, slerp); /// <summary> /// Spherical interpolation. Will correct alignment. Result is NOT normalized. /// </summary> public FQuat Slerp_NotNormalized(FQuat quat1, FQuat quat2, float slerp) => E_FQuat_Slerp_NotNormalized(this, quat1, quat2, slerp); /// <summary> /// Simpler Slerp that doesn't do any checks for 'shortest distance' etc. /// <para>We need this for the cubic interpolation stuff so that the multiple Slerps dont go in different directions. </para> /// Result is normalized. /// </summary> public FQuat SlerpFullPath(FQuat quat1, FQuat quat2, float alpha) => E_FQuat_SlerpFullPath(this, quat1, quat2, alpha); /// <summary> /// Simpler Slerp that doesn't do any checks for 'shortest distance' etc. /// <para>We need this for the cubic interpolation stuff so that the multiple Slerps dont go in different directions. </para> /// Result is NOT normalized. /// </summary> public FQuat SlerpFullPath_NotNormalized(FQuat quat1, FQuat quat2, float alpha) => E_FQuat_SlerpFullPath_NotNormalized(this, quat1, quat2, alpha); /// <summary> /// Given start and end quaternions of quat1 and quat2, and tangents at those points tang1 and tang2, calculate the point at Alpha (between 0 and 1) between them. Result is normalized. /// <para>This will correct alignment by ensuring that the shortest path is taken. </para> /// </summary> public FQuat Squad(FQuat quat1, FQuat tang1, FQuat quat2, FQuat tang2, float alpha) => E_FQuat_Squad(this, quat1, tang1, quat2, tang2, alpha); /// <summary> /// Simpler Squad that doesn't do any checks for 'shortest distance' etc. /// <para>Given start and end quaternions of quat1 and quat2, and tangents at those points tang1 and tang2, calculate the point at Alpha (between 0 and 1) between them. Result is normalized. </para> /// </summary> public FQuat SquadFullPath(FQuat quat1, FQuat tang1, FQuat quat2, FQuat tang2, float alpha) => E_FQuat_SquadFullPath(this, quat1, tang1, quat2, tang2, alpha); /// <summary> /// get the axis and angle of rotation of this quaternion /// <para>@warning : assumes normalized quaternions. </para> /// </summary> /// <param name="axis">out] vector of axis of the quaternion</param> /// <param name="angle">out] angle of the quaternion</param> public void ToAxisAndAngle(FVector axis, float angle) => E_FQuat_ToAxisAndAngle(this, axis, angle); /// <summary> /// Get a textual representation of the vector. /// </summary> /// <return>Text</return> public override string ToString() => E_FQuat_ToString(this); /// <summary> /// Get the swing and twist decomposition for a specified axis /// <para>@warning assumes normalised quaternion and twist axis </para> /// </summary> /// <param name="inTwistAxis">Axis to use for decomposition</param> /// <param name="outSwing">swing component quaternion</param> /// <param name="outTwist">Twist component quaternion</param> public void ToSwingTwist(FVector inTwistAxis, FQuat outSwing, FQuat outTwist) => E_FQuat_ToSwingTwist(this, inTwistAxis, outSwing, outTwist); /// <summary> /// Rotate a vector by the inverse of this quaternion. /// </summary> /// <param name="v">the vector to be rotated</param> /// <return>vector</return> public FVector UnrotateVector(FVector v) => E_FQuat_UnrotateVector(this, v); /// <summary> /// Convert a rotation into a unit vector facing in its direction. Equivalent to GetForwardVector(). /// </summary> public FVector Vector() => E_FQuat_Vector(this); #endregion public static implicit operator IntPtr(FQuat self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FQuat(IntPtr adress) { return adress == IntPtr.Zero ? null : new FQuat(adress, false); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using ClosedXML.Excel.CalcEngine.Functions; namespace ClosedXML.Excel.CalcEngine { internal static class MathTrig { private static readonly Random _rnd = new Random(); public static void Register(CalcEngine ce) { ce.RegisterFunction("ABS", 1, Abs); ce.RegisterFunction("ACOS", 1, Acos); ce.RegisterFunction("ACOSH", 1, Acosh); ce.RegisterFunction("ASIN", 1, Asin); ce.RegisterFunction("ASINH", 1, Asinh); ce.RegisterFunction("ATAN", 1, Atan); ce.RegisterFunction("ATAN2", 2, Atan2); ce.RegisterFunction("ATANH", 1, Atanh); ce.RegisterFunction("CEILING", 1, Ceiling); ce.RegisterFunction("COMBIN", 2, Combin); ce.RegisterFunction("COS", 1, Cos); ce.RegisterFunction("COSH", 1, Cosh); ce.RegisterFunction("DEGREES", 1, Degrees); ce.RegisterFunction("EVEN", 1, Even); ce.RegisterFunction("EXP", 1, Exp); ce.RegisterFunction("FACT", 1, Fact); ce.RegisterFunction("FACTDOUBLE", 1, FactDouble); ce.RegisterFunction("FLOOR", 1, Floor); ce.RegisterFunction("GCD", 1, 255, Gcd); ce.RegisterFunction("INT", 1, Int); ce.RegisterFunction("LCM", 1, 255, Lcm); ce.RegisterFunction("LN", 1, Ln); ce.RegisterFunction("LOG", 1, 2, Log); ce.RegisterFunction("LOG10", 1, Log10); ce.RegisterFunction("MDETERM", 1, MDeterm); ce.RegisterFunction("MINVERSE", 1, MInverse); ce.RegisterFunction("MMULT", 2, MMult); ce.RegisterFunction("MOD", 2, Mod); ce.RegisterFunction("MROUND", 2, MRound); ce.RegisterFunction("MULTINOMIAL", 1, 255, Multinomial); ce.RegisterFunction("ODD", 1, Odd); ce.RegisterFunction("PI", 0, Pi); ce.RegisterFunction("POWER", 2, Power); ce.RegisterFunction("PRODUCT", 1, 255, Product); ce.RegisterFunction("QUOTIENT", 2, Quotient); ce.RegisterFunction("RADIANS", 1, Radians); ce.RegisterFunction("RAND", 0, Rand); ce.RegisterFunction("RANDBETWEEN", 2, RandBetween); ce.RegisterFunction("ROMAN", 1, 2, Roman); ce.RegisterFunction("ROUND", 2, Round); ce.RegisterFunction("ROUNDDOWN", 2, RoundDown); ce.RegisterFunction("ROUNDUP", 1, 2, RoundUp); ce.RegisterFunction("SERIESSUM", 4, SeriesSum); ce.RegisterFunction("SIGN", 1, Sign); ce.RegisterFunction("SIN", 1, Sin); ce.RegisterFunction("SINH", 1, Sinh); ce.RegisterFunction("SQRT", 1, Sqrt); ce.RegisterFunction("SQRTPI", 1, SqrtPi); ce.RegisterFunction("SUBTOTAL", 2, 255, Subtotal); ce.RegisterFunction("SUM", 1, int.MaxValue, Sum); ce.RegisterFunction("SUMIF", 2, 3, SumIf); //ce.RegisterFunction("SUMPRODUCT", 1, SumProduct); ce.RegisterFunction("SUMSQ", 1, 255, SumSq); //ce.RegisterFunction("SUMX2MY2", SumX2MY2, 1); //ce.RegisterFunction("SUMX2PY2", SumX2PY2, 1); //ce.RegisterFunction("SUMXMY2", SumXMY2, 1); ce.RegisterFunction("TAN", 1, Tan); ce.RegisterFunction("TANH", 1, Tanh); ce.RegisterFunction("TRUNC", 1, Trunc); } private static object Abs(List<Expression> p) { return Math.Abs(p[0]); } private static object Acos(List<Expression> p) { return Math.Acos(p[0]); } private static object Asin(List<Expression> p) { return Math.Asin(p[0]); } private static object Atan(List<Expression> p) { return Math.Atan(p[0]); } private static object Atan2(List<Expression> p) { return Math.Atan2(p[0], p[1]); } private static object Ceiling(List<Expression> p) { return Math.Ceiling(p[0]); } private static object Cos(List<Expression> p) { return Math.Cos(p[0]); } private static object Cosh(List<Expression> p) { return Math.Cosh(p[0]); } private static object Exp(List<Expression> p) { return Math.Exp(p[0]); } private static object Floor(List<Expression> p) { return Math.Floor(p[0]); } private static object Int(List<Expression> p) { return (int) ((double) p[0]); } private static object Ln(List<Expression> p) { return Math.Log(p[0]); } private static object Log(List<Expression> p) { var lbase = p.Count > 1 ? (double) p[1] : 10; return Math.Log(p[0], lbase); } private static object Log10(List<Expression> p) { return Math.Log10(p[0]); } private static object Pi(List<Expression> p) { return Math.PI; } private static object Power(List<Expression> p) { return Math.Pow(p[0], p[1]); } private static object Rand(List<Expression> p) { return _rnd.NextDouble(); } private static object RandBetween(List<Expression> p) { return _rnd.Next((int) (double) p[0], (int) (double) p[1]); } private static object Sign(List<Expression> p) { return Math.Sign(p[0]); } private static object Sin(List<Expression> p) { return Math.Sin(p[0]); } private static object Sinh(List<Expression> p) { return Math.Sinh(p[0]); } private static object Sqrt(List<Expression> p) { return Math.Sqrt(p[0]); } private static object Sum(List<Expression> p) { var tally = new Tally(); foreach (var e in p) { tally.Add(e); } return tally.Sum(); } private static object SumIf(List<Expression> p) { // get parameters var range = p[0] as IEnumerable; var sumRange = p.Count < 3 ? range : p[2] as IEnumerable; var criteria = p[1].Evaluate(); // build list of values in range and sumRange var rangeValues = new List<object>(); foreach (var value in range) { rangeValues.Add(value); } var sumRangeValues = new List<object>(); foreach (var value in sumRange) { sumRangeValues.Add(value); } // compute total var ce = new CalcEngine(); var tally = new Tally(); for (var i = 0; i < Math.Min(rangeValues.Count, sumRangeValues.Count); i++) { if (CalcEngineHelpers.ValueSatisfiesCriteria(rangeValues[i], criteria, ce)) { tally.AddValue(sumRangeValues[i]); } } // done return tally.Sum(); } private static object Tan(List<Expression> p) { return Math.Tan(p[0]); } private static object Tanh(List<Expression> p) { return Math.Tanh(p[0]); } private static object Trunc(List<Expression> p) { return (double) (int) ((double) p[0]); } public static double DegreesToRadians(double degrees) { return (Math.PI/180.0)*degrees; } public static double RadiansToDegrees(double radians) { return (180.0/Math.PI)*radians; } public static double GradsToRadians(double grads) { return (grads/200.0)*Math.PI; } public static double RadiansToGrads(double radians) { return (radians/Math.PI)*200.0; } public static double DegreesToGrads(double degrees) { return (degrees/9.0)*10.0; } public static double GradsToDegrees(double grads) { return (grads/10.0)*9.0; } public static double ASinh(double x) { return (Math.Log(x + Math.Sqrt(x*x + 1.0))); } private static object Acosh(List<Expression> p) { return XLMath.ACosh(p[0]); } private static object Asinh(List<Expression> p) { return XLMath.ASinh(p[0]); } private static object Atanh(List<Expression> p) { return XLMath.ATanh(p[0]); } private static object Combin(List<Expression> p) { Int32 n = (int) p[0]; Int32 k = (int) p[1]; return XLMath.Combin(n, k); } private static object Degrees(List<Expression> p) { return p[0] * (180.0 / Math.PI); } private static object Fact(List<Expression> p) { var num = Math.Floor(p[0]); double fact = 1.0; if (num > 1) for (int i = 2; i <= num; i++) fact *= i; return fact; } private static object FactDouble(List<Expression> p) { var num = Math.Floor(p[0]); double fact = 1.0; if (num > 1) { var start = Math.Abs(num % 2) < XLHelper.Epsilon ? 2 : 1; for (int i = start; i <= num; i = i + 2) fact *= i; } return fact; } private static object Gcd(List<Expression> p) { return p.Select(v => (int)v).Aggregate(Gcd); } private static int Gcd(int a, int b) { return b == 0 ? a : Gcd(b, a % b); } private static object Lcm(List<Expression> p) { return p.Select(v => (int)v).Aggregate(Lcm); } private static int Lcm(int a, int b) { if (a == 0 || b == 0) return 0; return a * ( b / Gcd(a, b)); } private static object Mod(List<Expression> p) { Int32 n = (int)Math.Abs(p[0]); Int32 d = (int)p[1]; var ret = n % d; return d < 0 ? ret * -1 : ret; } private static object MRound(List<Expression> p) { var n = (Decimal)(Double)p[0]; var k = (Decimal)(Double)p[1]; var mod = n % k; var mult = Math.Floor(n / k); var div = k / 2; if (Math.Abs(mod - div) <= (Decimal)XLHelper.Epsilon) return (k * mult) + k; return k * mult; } private static object Multinomial(List<Expression> p) { return Multinomial(p.Select(v => (double)v).ToList()); } private static double Multinomial(List<double> numbers) { double numbersSum = 0; foreach (var number in numbers) numbersSum += number; double maxNumber = numbers.Max(); var denomFactorPowers = new double[(uint)numbers.Max() + 1]; foreach (var number in numbers) for (int i = 2; i <= number; i++) denomFactorPowers[i]++; for (int i = 2; i < denomFactorPowers.Length; i++) denomFactorPowers[i]--; // reduce with nominator; int currentFactor = 2; double currentPower = 1; double result = 1; for (double i = maxNumber + 1; i <= numbersSum; i++) { double tempDenom = 1; while (tempDenom < result && currentFactor < denomFactorPowers.Length) { if (currentPower > denomFactorPowers[currentFactor]) { currentFactor++; currentPower = 1; } else { tempDenom *= currentFactor; currentPower++; } } result = result / tempDenom * i; } return result; } private static object Odd(List<Expression> p) { var num = (int)Math.Ceiling(p[0]); var addValue = num >= 0 ? 1 : -1; return XLMath.IsOdd(num) ? num : num + addValue; } private static object Even(List<Expression> p) { var num = (int)Math.Ceiling(p[0]); var addValue = num >= 0 ? 1 : -1; return XLMath.IsEven(num) ? num : num + addValue; } private static object Product(List<Expression> p) { if (p.Count == 0) return 0; Double total = 1; p.ForEach(v => total *= v); return total; } private static object Quotient(List<Expression> p) { Double n = p[0]; Double k = p[1]; return (int)(n / k); } private static object Radians(List<Expression> p) { return p[0] * Math.PI / 180.0; } private static object Roman(List<Expression> p) { Int32 intTemp; Boolean boolTemp; if (p.Count == 1 || (Boolean.TryParse(p[1]._token.Value.ToString(), out boolTemp) && boolTemp) || (Int32.TryParse(p[1]._token.Value.ToString(), out intTemp) && intTemp == 1)) return XLMath.ToRoman((int)p[0]); throw new ArgumentException("Can only support classic roman types."); } private static object Round(List<Expression> p) { var value = (Double)p[0]; var digits = (Int32)(Double)p[1]; if (digits >= 0) { return Math.Round(value, digits); } else { digits = Math.Abs(digits); double temp = value / Math.Pow(10, digits); temp = Math.Round(temp, 0); return temp * Math.Pow(10, digits); } } private static object RoundDown(List<Expression> p) { var value = (Double)p[0]; var digits = (Int32)(Double)p[1]; if (value >= 0) return Math.Floor(value * Math.Pow(10, digits)) / Math.Pow(10, digits); return Math.Ceiling(value * Math.Pow(10, digits)) / Math.Pow(10, digits); } private static object RoundUp(List<Expression> p) { var value = (Double)p[0]; var digits = (Int32)(Double)p[1]; if (value >= 0) return Math.Ceiling(value * Math.Pow(10, digits)) / Math.Pow(10, digits); return Math.Floor(value * Math.Pow(10, digits)) / Math.Pow(10, digits); } private static object SeriesSum(List<Expression> p) { var x = (Double)p[0]; var n = (Double)p[1]; var m = (Double)p[2]; var obj = p[3] as XObjectExpression; if (obj == null) return p[3] * Math.Pow(x , n); Double total = 0; Int32 i = 0; foreach (var e in obj) { total += (double)e * Math.Pow(x, n + i * m); i++; } return total; } private static object SqrtPi(List<Expression> p) { var num = (Double)p[0]; return Math.Sqrt(Math.PI * num); } private static object Subtotal(List<Expression> p) { var fId = (int)(Double)p[0]; var tally = new Tally(p.Skip(1)); switch (fId) { case 1: return tally.Average(); case 2: return tally.Count(true); case 3: return tally.Count(false); case 4: return tally.Max(); case 5: return tally.Min(); case 6: return tally.Product(); case 7: return tally.Std(); case 8: return tally.StdP(); case 9: return tally.Sum(); case 10: return tally.Var(); case 11: return tally.VarP(); default: throw new ArgumentException("Function not supported."); } } private static object SumSq(List<Expression> p) { var t = new Tally(p); return t.NumericValues().Sum(v => Math.Pow(v, 2)); } private static object MMult(List<Expression> p) { Double[,] A = GetArray(p[0]); Double[,] B = GetArray(p[1]); if (A.GetLength(0) != B.GetLength(0) || A.GetLength(1) != B.GetLength(1)) throw new ArgumentException("Ranges must have the same number of rows and columns."); var C = new double[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); i++) { for (int j = 0; j < B.GetLength(1); j++) { for (int k = 0; k < A.GetLength(1); k++) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static double[,] GetArray(Expression expression) { var oExp1 = expression as XObjectExpression; if (oExp1 == null) return new [,]{{(Double)expression}}; var range = (oExp1.Value as CellRangeReference).Range; var rowCount = range.RowCount(); var columnCount = range.ColumnCount(); var arr = new double[rowCount,columnCount]; for (int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { arr[row, column] = range.Cell(row + 1, column + 1).GetDouble(); } } return arr; } private static object MDeterm(List<Expression> p) { var arr = GetArray(p[0]); var m = new XLMatrix(arr); return m.Determinant(); } private static object MInverse(List<Expression> p) { var arr = GetArray(p[0]); var m = new XLMatrix(arr); return m.Invert().mat; } } }
// 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.IO; using System.Text; using System.Collections; using System.Xml.Schema; using System.Diagnostics; using System.Globalization; namespace System.Xml { internal class ValidatingReaderNodeData { private string _localName; private string _namespaceUri; private string _prefix; private string _nameWPrefix; private string _rawValue; private string _originalStringValue; // Original value private int _depth; private AttributePSVIInfo _attributePSVIInfo; //Used only for default attributes private XmlNodeType _nodeType; private int _lineNo; private int _linePos; public ValidatingReaderNodeData() { Clear(XmlNodeType.None); } public ValidatingReaderNodeData(XmlNodeType nodeType) { Clear(nodeType); } public string LocalName { get { return _localName; } set { _localName = value; } } public string Namespace { get { return _namespaceUri; } set { _namespaceUri = value; } } public string Prefix { get { return _prefix; } set { _prefix = value; } } public string GetAtomizedNameWPrefix(XmlNameTable nameTable) { if (_nameWPrefix == null) { if (_prefix.Length == 0) { _nameWPrefix = _localName; } else { _nameWPrefix = nameTable.Add(string.Concat(_prefix, ":", _localName)); } } return _nameWPrefix; } public int Depth { get { return _depth; } set { _depth = value; } } public string RawValue { get { return _rawValue; } set { _rawValue = value; } } public string OriginalStringValue { get { return _originalStringValue; } set { _originalStringValue = value; } } public XmlNodeType NodeType { get { return _nodeType; } set { _nodeType = value; } } public AttributePSVIInfo AttInfo { get { return _attributePSVIInfo; } set { _attributePSVIInfo = value; } } public int LineNumber { get { return _lineNo; } } public int LinePosition { get { return _linePos; } } internal void Clear(XmlNodeType nodeType) { _nodeType = nodeType; _localName = string.Empty; _prefix = string.Empty; _namespaceUri = string.Empty; _rawValue = string.Empty; if (_attributePSVIInfo != null) { _attributePSVIInfo.Reset(); } _nameWPrefix = null; _lineNo = 0; _linePos = 0; } internal void SetLineInfo(int lineNo, int linePos) { _lineNo = lineNo; _linePos = linePos; } internal void SetLineInfo(IXmlLineInfo lineInfo) { if (lineInfo != null) { _lineNo = lineInfo.LineNumber; _linePos = lineInfo.LinePosition; } } internal void SetItemData(string localName, string prefix, string ns, int depth) { _localName = localName; _prefix = prefix; _namespaceUri = ns; _depth = depth; _rawValue = string.Empty; } internal void SetItemData(string value) { SetItemData(value, value); } internal void SetItemData(string value, string originalStringValue) { _rawValue = value; _originalStringValue = originalStringValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; namespace System.Reflection.Tests { public class MethodInfoCreateDelegateTests { //Create Open Instance delegate to a public method [Fact] public void TestCreateDelegate1() { Type typeTestClass = typeof(ClassA); RunBasicTestsHelper(typeTestClass); } //Inheritance Tests [Fact] public void TestCreateDelegate2() { Type typeTestClass = typeof(ClassA); Type TestSubClassType = typeof(SubClassA); RunInheritanceTestsHelper(typeTestClass, TestSubClassType); } //Generic Tests [Fact] public void TestCreateDelegate3() { Type typeGenericClassString = typeof(GenericClass<String>); RunGenericTestsHelper(typeGenericClassString); } //create open instance delegate with incorrect delegate type [Fact] public void TestCreateDelegate4() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int)); }); } //Verify ArgumentNullExcpeption when type is null [Fact] public void TestCreateDelegate5() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentNullException>(() => { miPublicInstanceMethod.CreateDelegate(null); }); } //create closed instance delegate with incorrect delegate type [Fact] public void TestCreateDelegate6() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int), TestClass); }); } //Verify ArgumentNullExcpeption when type is null [Fact] public void TestCreateDelegate7() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentNullException>(() => { miPublicInstanceMethod.CreateDelegate(null, TestClass); }); } //closed instance delegate with incorrect object type [Fact] public void TestCreateDelegate8() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), new DummyClass()); }); } //create closed static method with inccorect argument [Fact] public void TestCreateDelegate9() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Str), new DummyClass()); }); } [Fact] public void TestCreateDelegate10() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicStructMethod = GetMethod(typeof(ClassA), "PublicStructMethod"); ClassA classAObj = new ClassA(); Delegate dlgt = miPublicStructMethod.CreateDelegate(typeof(Delegate_DateTime_Str)); Object retValue = ((Delegate_DateTime_Str)dlgt).DynamicInvoke(new Object[] { classAObj, null }); Object actualReturnValue = classAObj.PublicStructMethod(new DateTime()); Assert.True(retValue.Equals(actualReturnValue)); } public void RunBasicTestsHelper(Type typeTestClass) { ClassA TestClass = (ClassA)Activator.CreateInstance(typeTestClass); MethodInfo miPublicInstanceMethod = GetMethod(typeTestClass, "PublicInstanceMethod"); MethodInfo miPrivateInstanceMethod = GetMethod(typeTestClass, "PrivateInstanceMethod"); MethodInfo miPublicStaticMethod = GetMethod(typeTestClass, "PublicStaticMethod"); Delegate dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); Object retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestClass }); Assert.True(retValue.Equals(TestClass.PublicInstanceMethod())); Assert.NotNull(miPrivateInstanceMethod); dlgt = miPrivateInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestClass }); Assert.True(retValue.Equals(21)); dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), TestClass); retValue = ((Delegate_Void_Int)dlgt).DynamicInvoke(null); Assert.True(retValue.Equals(TestClass.PublicInstanceMethod())); dlgt = miPublicStaticMethod.CreateDelegate(typeof(Delegate_Str_Str)); retValue = ((Delegate_Str_Str)dlgt).DynamicInvoke(new Object[] { "85" }); Assert.True(retValue.Equals("85")); dlgt = miPublicStaticMethod.CreateDelegate(typeof(Delegate_Void_Str), "93"); retValue = ((Delegate_Void_Str)dlgt).DynamicInvoke(null); Assert.True(retValue.Equals("93")); } public void RunInheritanceTestsHelper(Type typeTestClass, Type TestSubClassType) { SubClassA TestSubClass = (SubClassA)Activator.CreateInstance(TestSubClassType); ClassA TestClass = (ClassA)Activator.CreateInstance(typeTestClass); MethodInfo miPublicInstanceMethod = GetMethod(typeTestClass, "PublicInstanceMethod"); Delegate dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); object retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestSubClass }); Assert.True(retValue.Equals(TestSubClass.PublicInstanceMethod())); dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), TestSubClass); retValue = ((Delegate_Void_Int)dlgt).DynamicInvoke(); Assert.True(retValue.Equals(TestSubClass.PublicInstanceMethod())); } public void RunGenericTestsHelper(Type typeGenericClassString) { GenericClass<String> genericClass = (GenericClass<String>)Activator.CreateInstance(typeGenericClassString); MethodInfo miMethod1String = GetMethod(typeGenericClassString, "Method1"); MethodInfo miMethod2String = GetMethod(typeGenericClassString, "Method2"); MethodInfo miMethod2IntGeneric = miMethod2String.MakeGenericMethod(new Type[] { typeof(int) }); MethodInfo miMethod2StringGeneric = miMethod2String.MakeGenericMethod(new Type[] { typeof(String) }); Delegate dlgt = miMethod1String.CreateDelegate(typeof(Delegate_GC_T_T<String>)); object retValue = ((Delegate_GC_T_T<String>)dlgt).DynamicInvoke(new Object[] { genericClass, "TestGeneric" }); Assert.True(retValue.Equals(genericClass.Method1("TestGeneric"))); dlgt = miMethod1String.CreateDelegate(typeof(Delegate_T_T<String>), genericClass); retValue = ((Delegate_T_T<String>)dlgt).DynamicInvoke(new Object[] { "TestGeneric" }); Assert.True(retValue.Equals(genericClass.Method1("TestGeneric"))); dlgt = miMethod2IntGeneric.CreateDelegate(typeof(Delegate_T_T<int>)); retValue = ((Delegate_T_T<int>)dlgt).DynamicInvoke(new Object[] { 58 }); Assert.True(retValue.Equals(58)); dlgt = miMethod2StringGeneric.CreateDelegate(typeof(Delegate_Void_T<String>), "firstArg"); retValue = ((Delegate_Void_T<String>)dlgt).DynamicInvoke(); Assert.True(retValue.Equals("firstArg")); } // Gets MethodInfo object from current class public static MethodInfo GetMethod(string method) { return GetMethod(typeof(MethodInfoCreateDelegateTests), method); } //Gets MethodInfo object from a Type public static MethodInfo GetMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } } public delegate int Delegate_TC_Int(ClassA tc); public delegate int Delegate_Void_Int(); public delegate String Delegate_Str_Str(String x); public delegate String Delegate_Void_Str(); public delegate String Delegate_DateTime_Str(ClassA tc, DateTime dt); public delegate T Delegate_GC_T_T<T>(GenericClass<T> gc, T x); public delegate T Delegate_T_T<T>(T x); public delegate T Delegate_Void_T<T>(); public class ClassA { public virtual int PublicInstanceMethod() { return 17; } private int PrivateInstanceMethod() { return 21; } public static String PublicStaticMethod(String x) { return x; } public string PublicStructMethod(DateTime dt) { return dt.ToString(); } } public class SubClassA : ClassA { public override int PublicInstanceMethod() { return 79; } } public class DummyClass { public int DummyMethod() { return -1; } public override String ToString() { return "DummyClass"; } } public class GenericClass<T> { public T Method1(T t) { return t; } public static S Method2<S>(S s) { return s; } } }
using System; using System.Runtime.CompilerServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif // TODO: Add comments describing what this class does. It is not obvious. namespace Godot { public static partial class GD { public static object Bytes2Var(byte[] bytes) { return godot_icall_GD_bytes2var(bytes); } public static object Convert(object what, int type) { return godot_icall_GD_convert(what, type); } public static real_t Db2Linear(real_t db) { return (real_t)Math.Exp(db * 0.11512925464970228420089957273422); } public static real_t DecTime(real_t value, real_t amount, real_t step) { real_t sgn = Mathf.Sign(value); real_t val = Mathf.Abs(value); val -= amount * step; if (val < 0) val = 0; return val * sgn; } public static FuncRef FuncRef(Object instance, string funcname) { var ret = new FuncRef(); ret.SetInstance(instance); ret.SetFunction(funcname); return ret; } public static int Hash(object var) { return godot_icall_GD_hash(var); } public static Object InstanceFromId(int instanceId) { return godot_icall_GD_instance_from_id(instanceId); } public static real_t Linear2Db(real_t linear) { return (real_t)(Math.Log(linear) * 8.6858896380650365530225783783321); } public static Resource Load(string path) { return ResourceLoader.Load(path); } public static T Load<T>(string path) where T : class { return ResourceLoader.Load<T>(path); } public static void Print(params object[] what) { godot_icall_GD_print(what); } public static void PrintStack() { Print(System.Environment.StackTrace); } public static void PrintErr(params object[] what) { godot_icall_GD_printerr(what); } public static void PrintRaw(params object[] what) { godot_icall_GD_printraw(what); } public static void PrintS(params object[] what) { godot_icall_GD_prints(what); } public static void PrintT(params object[] what) { godot_icall_GD_printt(what); } public static int[] Range(int length) { var ret = new int[length]; for (int i = 0; i < length; i++) { ret[i] = i; } return ret; } public static int[] Range(int from, int to) { if (to < from) return new int[0]; var ret = new int[to - from]; for (int i = from; i < to; i++) { ret[i - from] = i; } return ret; } public static int[] Range(int from, int to, int increment) { if (to < from && increment > 0) return new int[0]; if (to > from && increment < 0) return new int[0]; // Calculate count int count; if (increment > 0) count = (to - from - 1) / increment + 1; else count = (from - to - 1) / -increment + 1; var ret = new int[count]; if (increment > 0) { int idx = 0; for (int i = from; i < to; i += increment) { ret[idx++] = i; } } else { int idx = 0; for (int i = from; i > to; i += increment) { ret[idx++] = i; } } return ret; } public static void Seed(int seed) { godot_icall_GD_seed(seed); } public static string Str(params object[] what) { return godot_icall_GD_str(what); } public static object Str2Var(string str) { return godot_icall_GD_str2var(str); } public static bool TypeExists(string type) { return godot_icall_GD_type_exists(type); } public static byte[] Var2Bytes(object var) { return godot_icall_GD_var2bytes(var); } public static string Var2Str(object var) { return godot_icall_GD_var2str(var); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_bytes2var(byte[] bytes); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_convert(object what, int type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_GD_hash(object var); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static Object godot_icall_GD_instance_from_id(int instance_id); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_print(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printerr(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printraw(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_prints(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printt(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_seed(int seed); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_str(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_str2var(string str); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_GD_type_exists(string type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_GD_var2bytes(object what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_var2str(object var); } }
using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent { #if OS_WINDOWS public static class WindowsProcessExtensions { // Reference: https://blogs.msdn.microsoft.com/matt_pietrek/2004/08/25/reading-another-processs-environment/ // Reference: http://blog.gapotchenko.com/eazfuscator.net/reading-environment-variables public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable) { var trace = hostContext.GetTrace(nameof(WindowsProcessExtensions)); Dictionary<string, string> environmentVariables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); IntPtr processHandle = process.SafeHandle.DangerousGetHandle(); // only support 32/64 bits process runs on x64 OS. if (!Environment.Is64BitOperatingSystem) { throw new PlatformNotSupportedException(); } PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION(); int returnLength = 0; int status = NtQueryInformationProcess(processHandle, PROCESSINFOCLASS.ProcessBasicInformation, ref pbi, Marshal.SizeOf(pbi), ref returnLength); if (status != 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } bool wow64; if (!IsWow64Process(processHandle, out wow64)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } IntPtr environmentBlockAddress; if (!wow64) { // 64 bits process IntPtr UserProcessParameterAddress = ReadIntPtr64(processHandle, new IntPtr(pbi.PebBaseAddress) + 0x20); environmentBlockAddress = ReadIntPtr64(processHandle, UserProcessParameterAddress + 0x80); } else { // 32 bits process IntPtr UserProcessParameterAddress = ReadIntPtr32(processHandle, new IntPtr(pbi.PebBaseAddress) + 0x1010); environmentBlockAddress = ReadIntPtr32(processHandle, UserProcessParameterAddress + 0x48); } MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION(); if (VirtualQueryEx(processHandle, environmentBlockAddress, ref memInfo, Marshal.SizeOf(memInfo)) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Int64 dataSize = memInfo.RegionSize.ToInt64() - (environmentBlockAddress.ToInt64() - memInfo.BaseAddress.ToInt64()); byte[] envData = new byte[dataSize]; IntPtr res_len = IntPtr.Zero; if (!ReadProcessMemory(processHandle, environmentBlockAddress, envData, new IntPtr(dataSize), ref res_len)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (res_len.ToInt64() != dataSize) { throw new ArgumentOutOfRangeException(nameof(ReadProcessMemory)); } string environmentVariableString; Int64 environmentVariableBytesLength = 0; // check env encoding if (envData[0] != 0 && envData[1] == 0) { // Unicode for (Int64 index = 0; index < dataSize; index++) { // Unicode encoded environment variables block ends up with '\0\0\0\0'. if (environmentVariableBytesLength == 0 && envData[index] == 0 && index + 3 < dataSize && envData[index + 1] == 0 && envData[index + 2] == 0 && envData[index + 3] == 0) { environmentVariableBytesLength = index + 3; } else if (environmentVariableBytesLength != 0) { // set it '\0' so we can easily trim it, most array method doesn't take int64 envData[index] = 0; } } if (environmentVariableBytesLength == 0) { throw new ArgumentException(nameof(environmentVariableBytesLength)); } environmentVariableString = Encoding.Unicode.GetString(envData); } else if (envData[0] != 0 && envData[1] != 0) { // ANSI for (Int64 index = 0; index < dataSize; index++) { // Unicode encoded environment variables block ends up with '\0\0'. if (environmentVariableBytesLength == 0 && envData[index] == 0 && index + 1 < dataSize && envData[index + 1] == 0) { environmentVariableBytesLength = index + 1; } else if (environmentVariableBytesLength != 0) { // set it '\0' so we can easily trim it, most array method doesn't take int64 envData[index] = 0; } } if (environmentVariableBytesLength == 0) { throw new ArgumentException(nameof(environmentVariableBytesLength)); } environmentVariableString = Encoding.Default.GetString(envData); } else { throw new ArgumentException(nameof(envData)); } foreach (var envString in environmentVariableString.Split("\0", StringSplitOptions.RemoveEmptyEntries)) { string[] env = envString.Split("=", 2); if (!string.IsNullOrEmpty(env[0])) { environmentVariables[env[0]] = env[1]; trace.Verbose($"PID:{process.Id} ({env[0]}={env[1]})"); } } if (environmentVariables.TryGetValue(variable, out string envVariable)) { return envVariable; } else { return null; } } private static IntPtr ReadIntPtr32(IntPtr hProcess, IntPtr ptr) { IntPtr readPtr = IntPtr.Zero; IntPtr data = Marshal.AllocHGlobal(sizeof(Int32)); try { IntPtr res_len = IntPtr.Zero; if (!ReadProcessMemory(hProcess, ptr, data, new IntPtr(sizeof(Int32)), ref res_len)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (res_len.ToInt32() != sizeof(Int32)) { throw new ArgumentOutOfRangeException(nameof(ReadProcessMemory)); } readPtr = new IntPtr(Marshal.ReadInt32(data)); } finally { Marshal.FreeHGlobal(data); } return readPtr; } private static IntPtr ReadIntPtr64(IntPtr hProcess, IntPtr ptr) { IntPtr readPtr = IntPtr.Zero; IntPtr data = Marshal.AllocHGlobal(IntPtr.Size); try { IntPtr res_len = IntPtr.Zero; if (!ReadProcessMemory(hProcess, ptr, data, new IntPtr(sizeof(Int64)), ref res_len)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (res_len.ToInt32() != IntPtr.Size) { throw new ArgumentOutOfRangeException(nameof(ReadProcessMemory)); } readPtr = Marshal.ReadIntPtr(data); } finally { Marshal.FreeHGlobal(data); } return readPtr; } private enum PROCESSINFOCLASS : int { ProcessBasicInformation = 0 }; [StructLayout(LayoutKind.Sequential)] private struct MEMORY_BASIC_INFORMATION { public IntPtr BaseAddress; public IntPtr AllocationBase; public int AllocationProtect; public IntPtr RegionSize; public int State; public int Protect; public int Type; } [StructLayout(LayoutKind.Sequential)] private struct PROCESS_BASIC_INFORMATION { public long ExitStatus; public long PebBaseAddress; public long AffinityMask; public long BasePriority; public long UniqueProcessId; public long InheritedFromUniqueProcessId; }; [DllImport("ntdll.dll", SetLastError = true)] private static extern int NtQueryInformationProcess(IntPtr processHandle, PROCESSINFOCLASS processInformationClass, ref PROCESS_BASIC_INFORMATION processInformation, int processInformationLength, ref int returnLength); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool IsWow64Process(IntPtr processHandle, out bool wow64Process); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, IntPtr dwSize, ref IntPtr lpNumberOfBytesRead); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, IntPtr dwSize, ref IntPtr lpNumberOfBytesRead); [DllImport("kernel32.dll")] private static extern int VirtualQueryEx(IntPtr processHandle, IntPtr baseAddress, ref MEMORY_BASIC_INFORMATION memoryInformation, int memoryInformationLength); } #else public static class LinuxProcessExtensions { public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable) { var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions)); Dictionary<string, string> env = new Dictionary<string, string>(); if (Directory.Exists("/proc")) { string envFile = $"/proc/{process.Id}/environ"; trace.Info($"Read env from {envFile}"); string envContent = File.ReadAllText(envFile); if (!string.IsNullOrEmpty(envContent)) { // on linux, environment variables are seprated by '\0' var envList = envContent.Split('\0', StringSplitOptions.RemoveEmptyEntries); foreach (var envStr in envList) { // split on the first '=' var keyValuePair = envStr.Split('=', 2); if (keyValuePair.Length == 2) { env[keyValuePair[0]] = keyValuePair[1]; trace.Verbose($"PID:{process.Id} ({keyValuePair[0]}={keyValuePair[1]})"); } } } } else { // On OSX, there is no /proc folder for us to read environment for given process, // So we have call `ps e -p <pid> -o command` to print out env to STDOUT, // However, the output env are not format in a parseable way, it's just a string that concatenate all envs with space, // It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs. // So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space) trace.Info($"Read env from output of `ps e -p {process.Id} -o command`"); List<string> psOut = new List<string>(); object outputLock = new object(); using (var p = hostContext.CreateService<IProcessInvoker>()) { p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout) { if (!string.IsNullOrEmpty(stdout.Data)) { lock (outputLock) { psOut.Add(stdout.Data); } } }; p.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr) { if (!string.IsNullOrEmpty(stderr.Data)) { lock (outputLock) { trace.Error(stderr.Data); } } }; int exitCode = p.ExecuteAsync(workingDirectory: hostContext.GetDirectory(WellKnownDirectory.Root), fileName: "ps", arguments: $"e -p {process.Id} -o command", environment: null, cancellationToken: CancellationToken.None).GetAwaiter().GetResult(); if (exitCode == 0) { trace.Info($"Successfully dump environment variables for {process.Id}"); if (psOut.Count > 0) { string psOutputString = string.Join(" ", psOut); trace.Verbose($"ps output: '{psOutputString}'"); int varStartIndex = psOutputString.IndexOf(variable, StringComparison.Ordinal); if (varStartIndex >= 0) { string rightPart = psOutputString.Substring(varStartIndex + variable.Length + 1); string value = rightPart.Substring(0, rightPart.IndexOf(' ')); env[variable] = value; trace.Verbose($"PID:{process.Id} ({variable}={value})"); } } } } } if (env.TryGetValue(variable, out string envVariable)) { return envVariable; } else { return null; } } } #endif }
using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Reflection; using System.IO; #if FRB_XNA using Microsoft.Xna.Framework; #endif #if SILVERLIGHT using System.Windows.Resources; #endif namespace FlatRedBall.IO.Csv { #region XML Docs /// <summary> /// Class providing methods for interacting with .CSV spreadsheet files. /// </summary> #endregion public static class CsvFileManager { public static char Delimiter = ','; #if FRB_RAW public static string ContentManagerName = "Global"; #else public static string ContentManagerName = FlatRedBallServices.GlobalContentManager; #endif public static List<object> CsvDeserializeList(Type typeOfElement, string fileName) { List<object> listOfObjects = new List<object>(); CsvDeserializeList(typeOfElement, fileName, listOfObjects); return listOfObjects; } public static void CsvDeserializeList(Type typeOfElement, string fileName, IList listToPopulate) { RuntimeCsvRepresentation rcr = CsvDeserializeToRuntime(fileName); rcr.CreateObjectList(typeOfElement, listToPopulate, ContentManagerName); } public static void CsvDeserializeDictionary<KeyType, ValueType>(string fileName, Dictionary<KeyType, ValueType> dictionaryToPopulate) { RuntimeCsvRepresentation rcr = null; CsvDeserializeDictionary(fileName, dictionaryToPopulate, out rcr); } public static void CsvDeserializeDictionary<KeyType, ValueType>(string fileName, Dictionary<KeyType, ValueType> dictionaryToPopulate, out RuntimeCsvRepresentation rcr) { rcr = CsvDeserializeToRuntime(fileName); rcr.CreateObjectDictionary<KeyType, ValueType>(dictionaryToPopulate, ContentManagerName); } public static RuntimeCsvRepresentation CsvDeserializeToRuntime(string fileName) { return CsvDeserializeToRuntime<RuntimeCsvRepresentation>(fileName); } public static T CsvDeserializeToRuntime<T>(string fileName) where T : RuntimeCsvRepresentation, new() { if (FileManager.IsRelative(fileName)) { fileName = FileManager.MakeAbsolute(fileName); } #if ANDROID || IOS fileName = fileName.ToLowerInvariant(); #endif FileManager.ThrowExceptionIfFileDoesntExist(fileName); T runtimeCsvRepresentation = null; string extension = FileManager.GetExtension(fileName).ToLower(); if (extension == "csv" || extension == "txt") { #if SILVERLIGHT || XBOX360 || WINDOWS_PHONE || MONOGAME Stream stream = FileManager.GetStreamForFile(fileName); #else // Creating a filestream then using that enables us to open files that are open by other apps. FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); #endif System.IO.StreamReader streamReader = new StreamReader(stream); using (CsvReader csv = new CsvReader(streamReader, true, Delimiter, CsvReader.DefaultQuote, CsvReader.DefaultEscape, CsvReader.DefaultComment, true, CsvReader.DefaultBufferSize)) { runtimeCsvRepresentation = new T(); string[] fileHeaders = csv.GetFieldHeaders(); runtimeCsvRepresentation.Headers = new CsvHeader[fileHeaders.Length]; for (int i = 0; i < fileHeaders.Length; i++) { runtimeCsvRepresentation.Headers[i] = new CsvHeader(fileHeaders[i]); } int numberOfHeaders = runtimeCsvRepresentation.Headers.Length; runtimeCsvRepresentation.Records = new List<string[]>(); int recordIndex = 0; int columnIndex = 0; string[] newRecord = null; try { while (csv.ReadNextRecord()) { newRecord = new string[numberOfHeaders]; if (recordIndex == 123) { int m = 3; } bool anyNonEmpty = false; for (columnIndex = 0; columnIndex < numberOfHeaders; columnIndex++) { string record = csv[columnIndex]; newRecord[columnIndex] = record; if (record != "") { anyNonEmpty = true; } } if (anyNonEmpty) { runtimeCsvRepresentation.Records.Add(newRecord); } recordIndex++; } } catch (Exception e) { string message = "Error reading record " + recordIndex + " at column " + columnIndex; if(columnIndex != 0 && newRecord != null) { foreach(string s in newRecord) { message += "\n" + s; } } throw new Exception(message, e); } } // Vic says - not sure how this got here, but it causes a crash! //streamReader.DiscardBufferedData(); FileManager.Close(streamReader); streamReader.Dispose(); FileManager.Close(stream); stream.Dispose(); #if XBOX360 if (FileManager.IsFileNameInUserFolder(fileName)) { FileManager.DisposeLastStorageContainer(); } #endif } return runtimeCsvRepresentation; } public static void Serialize(RuntimeCsvRepresentation rcr, string fileName) { if (rcr == null) throw new ArgumentNullException("rcr"); string toSave = rcr.GenerateCsvString(Delimiter); FileManager.SaveText(toSave, fileName); } private static void AppendMemberValue(StringBuilder stringBuilder, ref bool first, Type type, Object valueAsObject) { if (first) first = false; else stringBuilder.Append(" ,"); String value; bool isString = false; if (type == typeof(string)) //check if the value is a string if so, it should be surrounded in quotes { isString = true; } if (valueAsObject == null) { value = ""; stringBuilder.Append(value); } else //if not null, append the value { if (isString) { stringBuilder.Append("\""); } value = valueAsObject.ToString(); value = value.Replace('\n', ' '); //replace newlines stringBuilder.Append(value); if (isString) { stringBuilder.Append("\""); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Services { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Services; /// <summary> /// Static proxy methods. /// </summary> internal static class ServiceProxySerializer { /// <summary> /// Writes proxy method invocation data to the specified writer. /// </summary> /// <param name="writer">Writer.</param> /// <param name="method">Method.</param> /// <param name="arguments">Arguments.</param> /// <param name="platform">The platform.</param> public static void WriteProxyMethod(BinaryWriter writer, MethodBase method, object[] arguments, Platform platform) { Debug.Assert(writer != null); Debug.Assert(method != null); writer.WriteString(method.Name); if (arguments != null) { writer.WriteBoolean(true); writer.WriteInt(arguments.Length); if (platform == Platform.DotNet) { // Write as is foreach (var arg in arguments) { writer.WriteObjectDetached(arg); } } else { // Other platforms do not support Serializable, need to convert arrays and collections var methodArgs = method.GetParameters(); Debug.Assert(methodArgs.Length == arguments.Length); for (int i = 0; i < arguments.Length; i++) WriteArgForPlatforms(writer, methodArgs[i], arguments[i]); } } else writer.WriteBoolean(false); } /// <summary> /// Reads proxy method invocation data from the specified reader. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="mthdName">Method name.</param> /// <param name="mthdArgs">Method arguments.</param> public static void ReadProxyMethod(IBinaryStream stream, Marshaller marsh, out string mthdName, out object[] mthdArgs) { var reader = marsh.StartUnmarshal(stream); var srvKeepBinary = reader.ReadBoolean(); mthdName = reader.ReadString(); if (reader.ReadBoolean()) { mthdArgs = new object[reader.ReadInt()]; if (srvKeepBinary) reader = marsh.StartUnmarshal(stream, true); for (var i = 0; i < mthdArgs.Length; i++) mthdArgs[i] = reader.ReadObject<object>(); } else mthdArgs = null; } /// <summary> /// Writes method invocation result. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="methodResult">Method result.</param> /// <param name="invocationError">Method invocation error.</param> public static void WriteInvocationResult(IBinaryStream stream, Marshaller marsh, object methodResult, Exception invocationError) { Debug.Assert(stream != null); Debug.Assert(marsh != null); var writer = marsh.StartMarshal(stream); BinaryUtils.WriteInvocationResult(writer, invocationError == null, invocationError ?? methodResult); marsh.FinishMarshal(writer); } /// <summary> /// Reads method invocation result. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Binary flag.</param> /// <returns> /// Method invocation result, or exception in case of error. /// </returns> public static object ReadInvocationResult(IBinaryStream stream, Marshaller marsh, bool keepBinary) { Debug.Assert(stream != null); Debug.Assert(marsh != null); var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize; var reader = marsh.StartUnmarshal(stream, mode); object err; var res = BinaryUtils.ReadInvocationResult(reader, out err); if (err == null) return res; var binErr = err as IBinaryObject; throw binErr != null ? new ServiceInvocationException("Proxy method invocation failed with a binary error. " + "Examine BinaryCause for details.", binErr) : new ServiceInvocationException("Proxy method invocation failed with an exception. " + "Examine InnerException for details.", (Exception) err); } /// <summary> /// Reads service deployment result. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Binary flag.</param> /// <returns> /// Method invocation result, or exception in case of error. /// </returns> public static void ReadDeploymentResult(IBinaryStream stream, Marshaller marsh, bool keepBinary) { Debug.Assert(stream != null); Debug.Assert(marsh != null); var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize; var reader = marsh.StartUnmarshal(stream, mode); object err; BinaryUtils.ReadInvocationResult(reader, out err); if (err == null) { return; } // read failed configurations ICollection<ServiceConfiguration> failedCfgs; try { // switch to BinaryMode.Deserialize mode to avoid IService casting exception reader = marsh.StartUnmarshal(stream); failedCfgs = reader.ReadNullableCollectionRaw(f => new ServiceConfiguration(f)); } catch (Exception e) { throw new ServiceDeploymentException("Service deployment failed with an exception. " + "Examine InnerException for details.", e); } var binErr = err as IBinaryObject; throw binErr != null ? new ServiceDeploymentException("Service deployment failed with a binary error. " + "Examine BinaryCause for details.", binErr, failedCfgs) : new ServiceDeploymentException("Service deployment failed with an exception. " + "Examine InnerException for details.", (Exception) err, failedCfgs); } /// <summary> /// Writes the argument in platform-compatible format. /// </summary> private static void WriteArgForPlatforms(BinaryWriter writer, ParameterInfo param, object arg) { var hnd = GetPlatformArgWriter(param, arg); if (hnd != null) { hnd(writer, arg); } else { writer.WriteObjectDetached(arg); } } /// <summary> /// Gets arg writer for platform-compatible service calls. /// </summary> private static Action<BinaryWriter, object> GetPlatformArgWriter(ParameterInfo param, object arg) { var type = param.ParameterType; // Unwrap nullable type = Nullable.GetUnderlyingType(type) ?? type; if (arg == null || type.IsPrimitive) return null; var handler = BinarySystemHandlers.GetWriteHandler(type); if (handler != null) return null; if (type.IsArray) return (writer, o) => writer.WriteArrayInternal((Array) o); if (arg is ICollection) return (writer, o) => writer.WriteCollection((ICollection) o); return null; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Region.Framework.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Capabilities.Handlers { public class WebFetchInvDescHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private ILibraryService m_LibraryService; // private object m_fetchLock = new Object(); public WebFetchInvDescHandler(IInventoryService invService, ILibraryService libService) { m_InventoryService = invService; m_LibraryService = libService; } public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // lock (m_fetchLock) // { // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Received request {0}", request); // nasty temporary hack here, the linden client falsely // identifies the uuid 00000000-0000-0000-0000-000000000000 // as a string which breaks us // // correctly mark it as a uuid // request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>"); // another hack <integer>1</integer> results in a // System.ArgumentException: Object type System.Int32 cannot // be converted to target type: System.Boolean // request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>"); request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>"); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); } ArrayList foldersrequested = (ArrayList)hash["folders"]; string response = ""; for (int i = 0; i < foldersrequested.Count; i++) { string inventoryitemstr = ""; Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); } LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest); inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply); inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", ""); inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", ""); response += inventoryitemstr; } if (response.Length == 0) { // Ter-guess: If requests fail a lot, the client seems to stop requesting descendants. // Therefore, I'm concluding that the client only has so many threads available to do requests // and when a thread stalls.. is stays stalled. // Therefore we need to return something valid response = "<llsd><map><key>folders</key><array /></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>"; } // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request"); //m_log.Debug("[WEB FETCH INV DESC HANDLER] "+response); return response; // } } /// <summary> /// Construct an LLSD reply packet to a CAPS inventory request /// </summary> /// <param name="invFetch"></param> /// <returns></returns> private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch) { LLSDInventoryDescendents reply = new LLSDInventoryDescendents(); LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents(); contents.agent_id = invFetch.owner_id; contents.owner_id = invFetch.owner_id; contents.folder_id = invFetch.folder_id; reply.folders.Array.Add(contents); InventoryCollection inv = new InventoryCollection(); inv.Folders = new List<InventoryFolderBase>(); inv.Items = new List<InventoryItemBase>(); int version = 0; int descendents = 0; inv = Fetch( invFetch.owner_id, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version, out descendents); if (inv != null && inv.Folders != null) { foreach (InventoryFolderBase invFolder in inv.Folders) { contents.categories.Array.Add(ConvertInventoryFolder(invFolder)); } descendents += inv.Folders.Count; } if (inv != null && inv.Items != null) { foreach (InventoryItemBase invItem in inv.Items) { contents.items.Array.Add(ConvertInventoryItem(invItem)); } } contents.descendents = descendents; contents.version = version; // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Replying to request for folder {0} (fetch items {1}, fetch folders {2}) with {3} items and {4} folders for agent {5}", // invFetch.folder_id, // invFetch.fetch_items, // invFetch.fetch_folders, // contents.items.Array.Count, // contents.categories.Array.Count, // invFetch.owner_id); return reply; } /// <summary> /// Handle the caps inventory descendents fetch. /// </summary> /// <param name="agentID"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> /// <param name="version"></param> /// <returns>An empty InventoryCollection if the inventory look up failed</returns> private InventoryCollection Fetch( UUID agentID, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder, out int version, out int descendents) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Fetching folders ({0}), items ({1}) from {2} for agent {3}", // fetchFolders, fetchItems, folderID, agentID); // FIXME MAYBE: We're not handling sortOrder! version = 0; descendents = 0; InventoryFolderImpl fold; if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null && agentID == m_LibraryService.LibraryRootFolder.Owner) { if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(folderID)) != null) { InventoryCollection ret = new InventoryCollection(); ret.Folders = new List<InventoryFolderBase>(); ret.Items = fold.RequestListOfItems(); descendents = ret.Folders.Count + ret.Items.Count; return ret; } } InventoryCollection contents = new InventoryCollection(); if (folderID != UUID.Zero) { InventoryCollection fetchedContents = m_InventoryService.GetFolderContent(agentID, folderID); if (fetchedContents == null) { m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of folder {0} for user {1}", folderID, agentID); return contents; } contents = fetchedContents; InventoryFolderBase containingFolder = new InventoryFolderBase(); containingFolder.ID = folderID; containingFolder.Owner = agentID; containingFolder = m_InventoryService.GetFolder(containingFolder); if (containingFolder != null) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Retrieved folder {0} {1} for agent id {2}", // containingFolder.Name, containingFolder.ID, agentID); version = containingFolder.Version; if (fetchItems) { List<InventoryItemBase> itemsToReturn = contents.Items; List<InventoryItemBase> originalItems = new List<InventoryItemBase>(itemsToReturn); // descendents must only include the links, not the linked items we add descendents = originalItems.Count; // Add target items for links in this folder before the links themselves. foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.Link) { InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) itemsToReturn.Insert(0, linkedItem); } } // Now scan for folder links and insert the items they target and those links at the head of the return data foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.LinkFolder) { InventoryCollection linkedFolderContents = m_InventoryService.GetFolderContent(ownerID, item.AssetID); List<InventoryItemBase> links = linkedFolderContents.Items; itemsToReturn.InsertRange(0, links); foreach (InventoryItemBase link in linkedFolderContents.Items) { // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (link != null) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Adding item {0} {1} from folder {2} linked from {3}", // link.Name, (AssetType)link.AssetType, item.AssetID, containingFolder.Name); InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(link.AssetID)); if (linkedItem != null) itemsToReturn.Insert(0, linkedItem); } } } } } // foreach (InventoryItemBase item in contents.Items) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Returning item {0}, type {1}, parent {2} in {3} {4}", // item.Name, (AssetType)item.AssetType, item.Folder, containingFolder.Name, containingFolder.ID); // } // ===== // // foreach (InventoryItemBase linkedItem in linkedItemsToAdd) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Inserted linked item {0} for link in folder {1} for agent {2}", // linkedItem.Name, folderID, agentID); // // contents.Items.Add(linkedItem); // } // // // If the folder requested contains links, then we need to send those folders first, otherwise the links // // will be broken in the viewer. // HashSet<UUID> linkedItemFolderIdsToSend = new HashSet<UUID>(); // foreach (InventoryItemBase item in contents.Items) // { // if (item.AssetType == (int)AssetType.Link) // { // InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // // // Take care of genuinely broken links where the target doesn't exist // // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // // rather than having to keep track of every folder requested in the recursion. // if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) // { // // We don't need to send the folder if source and destination of the link are in the same // // folder. // if (linkedItem.Folder != containingFolder.ID) // linkedItemFolderIdsToSend.Add(linkedItem.Folder); // } // } // } // // foreach (UUID linkedItemFolderId in linkedItemFolderIdsToSend) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Recursively fetching folder {0} linked by item in folder {1} for agent {2}", // linkedItemFolderId, folderID, agentID); // // int dummyVersion; // InventoryCollection linkedCollection // = Fetch( // agentID, linkedItemFolderId, ownerID, fetchFolders, fetchItems, sortOrder, out dummyVersion); // // InventoryFolderBase linkedFolder = new InventoryFolderBase(linkedItemFolderId); // linkedFolder.Owner = agentID; // linkedFolder = m_InventoryService.GetFolder(linkedFolder); // //// contents.Folders.AddRange(linkedCollection.Folders); // // contents.Folders.Add(linkedFolder); // contents.Items.AddRange(linkedCollection.Items); // } // } } } else { // Lost items don't really need a version version = 1; } return contents; } /// <summary> /// Convert an internal inventory folder object into an LLSD object. /// </summary> /// <param name="invFolder"></param> /// <returns></returns> private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder) { LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder(); llsdFolder.folder_id = invFolder.ID; llsdFolder.parent_id = invFolder.ParentID; llsdFolder.name = invFolder.Name; llsdFolder.type = invFolder.Type; llsdFolder.preferred_type = -1; return llsdFolder; } /// <summary> /// Convert an internal inventory item object into an LLSD object. /// </summary> /// <param name="invItem"></param> /// <returns></returns> private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem) { LLSDInventoryItem llsdItem = new LLSDInventoryItem(); llsdItem.asset_id = invItem.AssetID; llsdItem.created_at = invItem.CreationDate; llsdItem.desc = invItem.Description; llsdItem.flags = (int)invItem.Flags; llsdItem.item_id = invItem.ID; llsdItem.name = invItem.Name; llsdItem.parent_id = invItem.Folder; llsdItem.type = invItem.AssetType; llsdItem.inv_type = invItem.InvType; llsdItem.permissions = new LLSDPermissions(); llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid; llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions; llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions; llsdItem.permissions.group_id = invItem.GroupID; llsdItem.permissions.group_mask = (int)invItem.GroupPermissions; llsdItem.permissions.is_owner_group = invItem.GroupOwned; llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions; llsdItem.permissions.owner_id = invItem.Owner; llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions; llsdItem.sale_info = new LLSDSaleInfo(); llsdItem.sale_info.sale_price = invItem.SalePrice; llsdItem.sale_info.sale_type = invItem.SaleType; return llsdItem; } } }
//----------------------------------------------------------------------- // <copyright file="GraphMergeSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class GraphMergeSpec : TwoStreamsSetup<int> { public GraphMergeSpec(ITestOutputHelper helper) : base(helper) { } protected override Fixture CreateFixture(GraphDsl.Builder<NotUsed> builder) => new MergeFixture(builder); private sealed class MergeFixture : Fixture { public MergeFixture(GraphDsl.Builder<NotUsed> builder) : base(builder) { var merge = builder.Add(new Merge<int, int>(2)); Left = merge.In(0); Right = merge.In(1); Out = merge.Out; } public override Inlet<int> Left { get; } public override Inlet<int> Right { get; } public override Outlet<int> Out { get; } } [Fact] public void A_Merge_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { // Different input sizes(4 and 6) var source1 = Source.From(Enumerable.Range(0, 4)); var source2 = Source.From(Enumerable.Range(4, 6)); var source3 = Source.From(new List<int>()); var probe = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var m1 = b.Add(new Merge<int>(2)); var m2 = b.Add(new Merge<int>(2)); var sink = Sink.FromSubscriber(probe); b.From(source1).To(m1.In(0)); b.From(m1.Out).Via(Flow.Create<int>().Select(x => x*2)).To(m2.In(0)); b.From(m2.Out).Via(Flow.Create<int>().Select(x => x / 2).Select(x=>x+1)).To(sink); b.From(source2).To(m1.In(1)); b.From(source3).To(m2.In(1)); return ClosedShape.Instance; })).Run(Materializer); var subscription = probe.ExpectSubscription(); var collected = new List<int>(); for (var i = 1; i <= 10; i++) { subscription.Request(1); collected.Add(probe.ExpectNext()); } collected.ShouldAllBeEquivalentTo(Enumerable.Range(1,10)); probe.ExpectComplete(); }, Materializer); } [Fact] public void A_Merge_must_work_with_one_way_merge() { var task = Source.FromGraph(GraphDsl.Create(b => { var merge = b.Add(new Merge<int>(1)); var source = b.Add(Source.From(Enumerable.Range(1, 3))); b.From(source).To(merge.In(0)); return new SourceShape<int>(merge.Out); })).RunAggregate(new List<int>(), (list, i) => { list.Add(i); return list; }, Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 3)); } [Fact] public void A_Merge_must_work_with_n_way_merge() { var source1 = Source.Single(1); var source2 = Source.Single(2); var source3 = Source.Single(3); var source4 = Source.Single(4); var source5 = Source.Single(5); var source6 = Source.Empty<int>(); var probe = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var merge = b.Add(new Merge<int>(6)); b.From(source1).To(merge.In(0)); b.From(source2).To(merge.In(1)); b.From(source3).To(merge.In(2)); b.From(source4).To(merge.In(3)); b.From(source5).To(merge.In(4)); b.From(source6).To(merge.In(5)); b.From(merge.Out).To(Sink.FromSubscriber(probe)); return ClosedShape.Instance; })).Run(Materializer); var subscription = probe.ExpectSubscription(); var collected = new List<int>(); for (var i = 1; i <= 5; i++) { subscription.Request(1); collected.Add(probe.ExpectNext()); } collected.ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); probe.ExpectComplete(); } [Fact] public void A_Merge_must_work_with_one_immediately_completed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4))); var subscription1 = subscriber1.ExpectSubscription(); subscription1.Request(4); subscriber1.ExpectNext(1, 2, 3, 4).ExpectComplete(); var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>()); var subscription2 = subscriber2.ExpectSubscription(); subscription2.Request(4); subscriber2.ExpectNext(1, 2, 3, 4).ExpectComplete(); }, Materializer); } [Fact] public void A_Merge_must_work_with_one_delayed_completed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4))); var subscription1 = subscriber1.ExpectSubscription(); subscription1.Request(4); subscriber1.ExpectNext(1, 2, 3, 4).ExpectComplete(); var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>()); var subscription2 = subscriber2.ExpectSubscription(); subscription2.Request(4); subscriber2.ExpectNext(1, 2, 3, 4).ExpectComplete(); }, Materializer); } [Fact(Skip = "This is nondeterministic, multiple scenarios can happen")] public void A_Merge_must_work_with_one_immediately_failed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { }, Materializer); } [Fact(Skip = "This is nondeterministic, multiple scenarios can happen")] public void A_Merge_must_work_with_one_delayed_failed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { }, Materializer); } [Fact] public void A_Merge_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up1 = TestPublisher.CreateManualProbe<int>(this); var up2 = TestPublisher.CreateManualProbe<int>(this); var down = TestSubscriber.CreateManualProbe<int>(this); var src1 = Source.AsSubscriber<int>(); var src2 = Source.AsSubscriber<int>(); var t = RunnableGraph.FromGraph(GraphDsl.Create(src1, src2, Tuple.Create, (b, s1, s2) => { var merge = b.Add(new Merge<int>(2)); var sink = Sink.FromSubscriber(down) .MapMaterializedValue<Tuple<ISubscriber<int>, ISubscriber<int>>>(_ => null); b.From(s1.Outlet).To(merge.In(0)); b.From(s2.Outlet).To(merge.In(1)); b.From(merge.Out).To(sink); return ClosedShape.Instance; })).Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up1.Subscribe(t.Item1); up2.Subscribe(t.Item2); var upSub1 = up1.ExpectSubscription(); upSub1.ExpectCancellation(); var upSub2 = up2.ExpectSubscription(); upSub2.ExpectCancellation(); }, Materializer); } } }
#if UNITY_STANDALONE || UNITY_EDITOR using UnityEngine; using System.Collections; using ProBuilder2.Common; namespace ProBuilder2.Examples { /** * \brief This class allows the user to select a single face at a time and move it forwards or backwards. * More advanced usage of the ProBuilder API should make use of the pb_Object->SelectedFaces list to keep * track of the selected faces. */ public class RuntimeEdit : MonoBehaviour { class pb_Selection { public pb_Object pb; ///< This is the currently selected ProBuilder object. public pb_Face face; ///< Keep a reference to the currently selected face. public pb_Selection(pb_Object _pb, pb_Face _face) { pb = _pb; face = _face; } public bool HasObject() { return pb != null; } public bool IsValid() { return pb != null && face != null; } public bool Equals(pb_Selection sel) { if(sel != null && sel.IsValid()) return (pb == sel.pb && face == sel.face); else return false; } public void Destroy() { if(pb != null) GameObject.Destroy(pb.gameObject); } public override string ToString() { return "pb_Object: " + pb == null ? "Null" : pb.name + "\npb_Face: " + ( (face == null) ? "Null" : face.ToString() ); } } pb_Selection currentSelection; pb_Selection previousSelection; private pb_Object preview; public Material previewMaterial; /** * \brief Wake up! */ void Awake() { SpawnCube(); } /** * \brief This is the usual Unity OnGUI method. We only use it to show a 'Reset' button. */ void OnGUI() { // To reset, nuke the pb_Object and build a new one. if(GUI.Button(new Rect(5, Screen.height - 25, 80, 20), "Reset")) { currentSelection.Destroy(); Destroy(preview.gameObject); SpawnCube(); } } /** * \brief Creates a new ProBuilder cube and sets it up with a concave MeshCollider. */ void SpawnCube() { // This creates a basic cube with ProBuilder features enabled. See the ProBuilder.Shape enum to // see all possible primitive types. pb_Object pb = pb_ShapeGenerator.CubeGenerator(Vector3.one); // The runtime component requires that a concave mesh collider be present in order for face selection // to work. pb.gameObject.AddComponent<MeshCollider>().convex = false; // Now set it to the currentSelection currentSelection = new pb_Selection(pb, null); } Vector2 mousePosition_initial = Vector2.zero; bool dragging = false; public float rotateSpeed = 100f; /** * \brief This is responsible for moving the camera around and not much else. */ public void LateUpdate() { if(!currentSelection.HasObject()) return; if(Input.GetMouseButtonDown(1) || (Input.GetMouseButtonDown(0) && Input.GetKey(KeyCode.LeftAlt))) { mousePosition_initial = Input.mousePosition; dragging = true; } if(dragging) { Vector2 delta = (Vector3)mousePosition_initial - (Vector3)Input.mousePosition; Vector3 dir = new Vector3(delta.y, delta.x, 0f); currentSelection.pb.gameObject.transform.RotateAround(Vector3.zero, dir, rotateSpeed * Time.deltaTime); // If there is a currently selected face, update the preview. if(currentSelection.IsValid()) RefreshSelectedFacePreview(); } if(Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(0)) { dragging = false; } } /** * \brief The 'meat' of the operation. This listens for a click event, then checks for a positive * face selection. If the click has hit a pb_Object, select it. */ public void Update() { if(Input.GetMouseButtonUp(0) && !Input.GetKey(KeyCode.LeftAlt)) { if(FaceCheck(Input.mousePosition)) { if(currentSelection.IsValid()) { // Check if this face has been previously selected, and if so, move the face. // Otherwise, just accept this click as a selection. if(!currentSelection.Equals(previousSelection)) { previousSelection = new pb_Selection(currentSelection.pb, currentSelection.face); RefreshSelectedFacePreview(); return; } Vector3 localNormal = pb_Math.Normal( pbUtil.ValuesWithIndices(currentSelection.pb.vertices, currentSelection.face.distinctIndices) );// currentSelection.pb.GetVertices(currentSelection.face.distinctIndices)); if(Input.GetKey(KeyCode.LeftShift)) currentSelection.pb.TranslateVertices( currentSelection.face.distinctIndices, localNormal.normalized * -.5f ); else currentSelection.pb.TranslateVertices( currentSelection.face.distinctIndices, localNormal.normalized * .5f ); currentSelection.pb.Refresh(); // Refresh will update the Collision mesh volume, face UVs as applicatble, and normal information. // this create the selected face preview RefreshSelectedFacePreview(); } } } } /** * \brief This is how we figure out what face is clicked. */ public bool FaceCheck(Vector3 pos) { Ray ray = Camera.main.ScreenPointToRay (pos); RaycastHit hit; if( Physics.Raycast(ray.origin, ray.direction, out hit)) { pb_Object hitpb = hit.transform.gameObject.GetComponent<pb_Object>(); if(hitpb == null) return false; Mesh m = hitpb.msh; int[] tri = new int[3] { m.triangles[hit.triangleIndex * 3 + 0], m.triangles[hit.triangleIndex * 3 + 1], m.triangles[hit.triangleIndex * 3 + 2] }; currentSelection.pb = hitpb; return hitpb.FaceWithTriangle(tri, out currentSelection.face); } return false; } void RefreshSelectedFacePreview() { pb_Face face = new pb_Face(currentSelection.face); // Copy the currently selected face face.ShiftIndicesToZero(); // Shift the selected face indices to zero // Copy the currently selected vertices in world space. // World space so that we don't have to apply transforms // to match the current selection. Vector3[] verts = currentSelection.pb.VerticesInWorldSpace(currentSelection.face.distinctIndices); // Now go through and move the verts we just grabbed out about .1m from the original face. Vector3 normal = pb_Math.Normal(verts); for(int i = 0; i < verts.Length; i++) verts[i] += normal.normalized * .01f; if(preview) Destroy(preview.gameObject); preview = pb_Object.CreateInstanceWithVerticesFaces(verts, new pb_Face[1]{face}); preview.SetFaceMaterial(preview.faces, previewMaterial); preview.ToMesh(); preview.Refresh(); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Research.DataStructures; using Microsoft.Research.Graphs; namespace Microsoft.Research.CodeAnalysis { using Tag = System.String; using SubroutineContext = FList<STuple<CFGBlock, CFGBlock, string>>; using System.Diagnostics.Contracts; /// <summary> /// Used to pass a handler to emit warnings /// </summary> public delegate void ErrorHandler(string format, params string[] args); /// <summary> /// Represents a filter that determines what handlers apply to a given context. /// </summary> /// <typeparam name="Label">Underlying program point representation</typeparam> /// <typeparam name="Data">Client data type for auxiliary client information</typeparam> /// <typeparam name="Type">Type for exception filter</typeparam> public interface IHandlerFilter<Type, Data> { /// <summary>Given handler is a catch handler with given exception filter.</summary> /// <param name="data">Client specific data that helps client determine match</param> /// <param name="exception">Catch type</param> /// <param name="stopPropagation">Client should set this to true if no outer enclosing handlers are possible</param> /// <returns>true if handler applies, false, if handler does not apply</returns> bool Catch(Data data, Type exception, out bool stopPropagation); /// <summary>Given handler is a filter handler with filter code.</summary> /// <param name="data">Client specific data that helps client determine match</param> /// <param name="filterCode">Code determining applicability of filter</param> /// <param name="stopPropagation">Client should set this to true if no outer enclosing handlers are possible</param> /// <returns>true if handler applies, false, if handler does not apply</returns> bool Filter(Data data, APC filterCode, out bool stopPropagation); } /// <summary> /// An abstract view of a control flow graph, generic over underlying code. /// </summary> public partial interface ICFG { /// <summary> /// The entry point of the method /// </summary> APC Entry { get; } /// <summary> /// The entry point of the method after all requires contracts /// </summary> APC EntryAfterRequires { get; } /// <summary> /// The normal exit point of the method /// </summary> APC NormalExit { get; } /// <summary> /// The exceptional exit point of the method /// </summary> APC ExceptionExit { get; } /// <summary> /// If the label has a single successor, then this returns the unique post pc. /// Otherwise the result is equal to label. /// </summary> APC Post(APC label); /// <summary> /// Returns the immediate normal successor program point if there is a single one. /// Otherwise, must use Successors which returns all (or 0). /// </summary> [Pure] bool HasSingleSuccessor(APC ppoint, out APC singleSuccessor); /// <summary> /// Provides the immediate normal successor program points of the given ppoint /// </summary> [Pure] IEnumerable<APC> Successors(APC ppoint); /// <summary> /// Returns the immediate normal predecessor program point if there is a single one. /// Otherwise, must use Predecessor which returns all (or 0). /// </summary> [Pure] bool HasSinglePredecessor(APC ppoint, out APC singlePredecessor, bool skipContracts = false); /// <summary> /// Provides the immediate normal predecessor program points of the given ppoint /// </summary> [Pure] IEnumerable<APC> Predecessors(APC ppoint, bool skipContracts = false); /// <summary> /// If ppoint is the beginning of a call instruction, then this provides the first PC prior to /// ppoint and prior to any requires of the call /// </summary> [Pure] APC PredecessorPCPriorToRequires(APC ppoint); /// <summary> /// Returns true if the given program point is the target of multiple forward control /// transfers. /// </summary> [Pure] bool IsJoinPoint(APC ppoint); /// <summary> /// Returns true if the given program point is the target of multiple backward control /// transfers. /// </summary> [Pure] bool IsSplitPoint(APC ppoint); /// <summary> /// Returns true if the given program point is a back edge target in a forward traversal /// </summary> [Pure] bool IsForwardBackEdgeTarget(APC ppoint); /// <summary> /// Returns true if the given program point is a back edge target in a backward traversal /// </summary> [Pure] bool IsBackwardBackEdgeTarget(APC ppoint); /// <summary> /// Returns true if the edge described by the two program points is a back edge in a forward /// traversal of the CFG. /// NOTE: the edge must be an edge related by the Successors relation above, not /// an arbitrary pair. /// </summary> [Pure] bool IsForwardBackEdge(APC from, APC to); /// <summary> /// Returns true if the edge described by the two program points is a back edge in a backward /// traversal of the CFG. /// NOTE: the edge must be an edge related by the Predecessor relation above, not /// an arbitrary pair. /// </summary> [Pure] bool IsBackwardBackEdge(APC from, APC to); /// <summary> /// Returns the APC corresponding to loop heads. /// </summary> IEnumerable<CFGBlock> LoopHeads { get; } /// <summary> /// Returns true if the program point is the first point in a logical block /// </summary> [Pure] bool IsBlockStart(APC ppoint); /// <summary> /// Returns true if the program point is the last point in a logical block /// </summary> [Pure] bool IsBlockEnd(APC ppoint); /// <summary> /// Returns a set of program points that are possible execution continuations if /// an exception is raised at the given ppoint. /// /// The supplied predicate allows the client to determine which handlers are possible /// candidates. The predicate is called from closest enclosing to outermost. /// </summary> /// <param name="data">Arbitrary client data passed to the handler predicate</param> /// <returns>A set of continuation program points that represent how execution continues to a chosen handler. /// The continuation includes Finally and Fault executions that intervene between the given ppoint and a /// chosen handler. /// </returns> [Pure] IEnumerable<APC> ExceptionHandlers<Type, Data>(APC ppoint, Data data, IHandlerFilter<Type, Data> handlerPredicate); /// <summary> /// Returns a graph wrapper for the cfg that can be used with standard graph algorithms. /// There's only one APC used per block (the first in the block), and the set of nodes is not /// explicitly given. /// </summary> [Pure] IGraph<APC, Unit> AsForwardGraph(bool includeExceptionEdges); /// <summary> /// Returns a graph wrapper for the cfg that can be used with standard graph algorithms. /// There's only one APC used per block (the first in the block), and the set of nodes is not /// explicitly given. /// </summary> [Pure] IGraph<APC, Unit> AsBackwardGraph(bool includeExceptionEdges, bool skipContracts); [Pure] IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit> GetDecoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder); /// <summary> /// Get a subroutine view of the CFG for block level operations /// </summary> Subroutine Subroutine { get; } /// <summary> /// Get the subroutines on the edge from ---> to /// </summary> FList<Pair<string, Subroutine>> GetOrdinaryEdgeSubroutines(CFGBlock from, CFGBlock to, SubroutineContext context); /// <summary> /// Returns a textual representation of an abstract PC /// </summary> [Pure] string ToString(APC pc); /// <summary> /// Prints out a textual representation of the CFG /// /// Also decodes the synthetic IL from the CFG generation /// eg. Assumes /// </summary> /// <param name="tw">Target for output</param> /// <param name="edgePrinter">Optional info printer for successor edges</param> void Print(TextWriter tw, ILPrinter<APC> ilPrinter, BlockInfoPrinter<APC>/*?*/ edgePrinter, Func<CFGBlock, IEnumerable<SubroutineContext>> contextLookup, SubroutineContext context); } #region ICFG contract binding [ContractClass(typeof(ICFGContract))] public partial interface ICFG { } [ContractClassFor(typeof(ICFG))] internal abstract class ICFGContract : ICFG { #region ICFG Members public APC Entry { get { throw new NotImplementedException(); } } public APC EntryAfterRequires { get { throw new NotImplementedException(); } } public APC NormalExit { get { throw new NotImplementedException(); } } public APC ExceptionExit { get { throw new NotImplementedException(); } } public APC Post(APC label) { throw new NotImplementedException(); } public bool HasSingleSuccessor(APC ppoint, out APC singleSuccessor) { throw new NotImplementedException(); } public IEnumerable<APC> Successors(APC ppoint) { Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null); throw new NotImplementedException(); } public bool HasSinglePredecessor(APC ppoint, out APC singlePredecessor, bool skipContracts) { throw new NotImplementedException(); } public IEnumerable<APC> Predecessors(APC ppoint, bool skipContracts) { Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null); throw new NotImplementedException(); } public APC PredecessorPCPriorToRequires(APC ppoint) { Contract.Requires(ppoint.Index == 0); throw new NotImplementedException(); } public bool IsJoinPoint(APC ppoint) { throw new NotImplementedException(); } public bool IsSplitPoint(APC ppoint) { throw new NotImplementedException(); } public bool IsForwardBackEdgeTarget(APC ppoint) { throw new NotImplementedException(); } public bool IsBackwardBackEdgeTarget(APC ppoint) { throw new NotImplementedException(); } public bool IsForwardBackEdge(APC from, APC to) { throw new NotImplementedException(); } public bool IsBackwardBackEdge(APC from, APC to) { throw new NotImplementedException(); } public IEnumerable<CFGBlock> LoopHeads { get { Contract.Ensures(Contract.Result<IEnumerable<CFGBlock>>() != null); throw new NotImplementedException(); } } public bool IsBlockStart(APC ppoint) { throw new NotImplementedException(); } public bool IsBlockEnd(APC ppoint) { throw new NotImplementedException(); } public IEnumerable<APC> ExceptionHandlers<Type, Data>(APC ppoint, Data data, IHandlerFilter<Type, Data> handlerPredicate) { Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null); throw new NotImplementedException(); } public IGraph<APC, Unit> AsForwardGraph(bool includeExceptionEdges) { Contract.Ensures(Contract.Result<IGraph<APC, Unit>>() != null); throw new NotImplementedException(); } public IGraph<APC, Unit> AsBackwardGraph(bool includeExceptionEdges, bool skipContracts) { Contract.Ensures(Contract.Result<IGraph<APC, Unit>>() != null); throw new NotImplementedException(); } public IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit> GetDecoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder) { Contract.Ensures(Contract.Result<IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit>>() != null); throw new NotImplementedException(); } public Subroutine Subroutine { get { Contract.Ensures(Contract.Result<Subroutine>() != null); throw new NotImplementedException(); } } public Tag ToString(APC pc) { Contract.Ensures(Contract.Result<string>() != null); throw new NotImplementedException(); } public void Print(TextWriter tw, ILPrinter<APC> ilPrinter, BlockInfoPrinter<APC> edgePrinter, Func<CFGBlock, IEnumerable<SubroutineContext>> contextLookup, SubroutineContext context) { throw new NotImplementedException(); } #endregion public FList<Pair<Tag, Subroutine>> GetOrdinaryEdgeSubroutines(CFGBlock from, CFGBlock to, SubroutineContext context) { Contract.Requires(from != null); Contract.Requires(to != null); throw new NotImplementedException(); } } #endregion /// <summary> /// Code query /// </summary> public interface ICodeQuery<Label, Local, Parameter, Method, Field, Type, Data, Result> : IVisitMSIL<Label, Local, Parameter, Method, Field, Type, Unit, Unit, Data, Result> { /// <summary> /// Called if Code represents a nested code aggregate /// </summary> /// <param name="aggregateStart">Start label of aggregate</param> /// <param name="data">Client specific data threaded through the dispatch</param> /// <param name="current">Label where instruction is decoded</param> /// <param name="canBeTargetOfBranch">true if current can be a branch target. If not, the CFG can remove unnecessary program points </param> Result Aggregate(Label current, Label aggregateStart, bool canBeTargetOfBranch, Data data); } public interface ICodeProvider<Label, Local, Parameter, Method, Field, Type> { /// <summary> /// Dispatches to the appropriate method in query based on the code at the given label /// </summary> R Decode<Visitor, T, R>(Label label, Visitor query, T data) where Visitor : ICodeQuery<Label, Local, Parameter, Method, Field, Type, T, R>; // Code Lookup(Label label); /// <summary> /// Returns the label of the code textually following the code at the given location (if sensible) /// </summary> /// <returns>true if next label is meaningful.</returns> bool Next(Label current, out Label nextLabel); /// <summary> /// Returns true if pc has source context associated with it /// </summary> bool HasSourceContext(Label pc); /// <summary> /// Returns the name of the associated document of the source context for this pc /// </summary> string SourceDocument(Label pc); /// <summary> /// Returns the first line number in the source context of this pc. /// </summary> int SourceStartLine(Label pc); /// <summary> /// Returns the last line number in the source context of this pc. /// </summary> int SourceEndLine(Label pc); /// <summary> /// Returns the first column number in the source context of this pc. /// </summary> int SourceStartColumn(Label pc); /// <summary> /// Returns the first column number in the source context of this pc. /// </summary> int SourceEndColumn(Label pc); /// <summary> /// The character index of the first character of the source context of this pc, /// when treating the source document as a single string. /// </summary> int SourceStartIndex(Label pc); /// <summary> /// The number of characters in the source context of this pc. /// </summary> int SourceLength(Label pc); /// <summary> /// Returns the IL offset within the method of the given instruction or 0 /// </summary> int ILOffset(Label pc); /// <summary> /// If the label corresponds to a contract (assert/requires, etc), this /// may provide the user or tool provided condition. /// </summary> string SourceAssertionCondition(Label label); } public interface IMethodCodeProvider<Label, Local, Parameter, Method, Field, Type, Handler> : ICodeProvider<Label, Local, Parameter, Method, Field, Type> { /// <summary> /// Returns the handlers associated with the provided method /// </summary> IEnumerable<Handler> TryBlocks(Method method); /// <summary> /// Decodes ExceptionInfo for the kind of handler /// </summary> bool IsFaultHandler(Handler info); /// <summary> /// Decodes ExceptionInfo for the kind of handler /// </summary> bool IsFinallyHandler(Handler info); /// <summary> /// Decodes ExceptionInfo for the kind of handler /// </summary> bool IsCatchHandler(Handler info); /// <summary> /// Decodes ExceptionInfo for the kind of handler /// </summary> bool IsFilterHandler(Handler info); /// <summary> /// If the handler is a CatchHandler, this method returns the type of exception caught. /// Fails if !IsCatchHandler /// </summary> Type CatchType(Handler info); /// <summary> /// Should return true if this handler catches all Exceptions /// </summary> bool IsCatchAllHandler(Handler info); /// <summary> /// Decodes ExceptionInfo for the Label corresponding to the start of try block /// </summary> Label TryStart(Handler info); /// <summary> /// Decodes ExceptionInfo for the Label corresponding to the end of try block /// </summary> Label TryEnd(Handler info); /// <summary> /// Decodes ExceptionInfo for the Label corresponding to the start of filter decision block (if any) /// </summary> Label FilterDecisionStart(Handler info); /// <summary> /// Decodes ExceptionInfo for the Label corresponding to the start of handler block /// </summary> Label HandlerStart(Handler info); /// <summary> /// Decodes ExceptionInfo for the Label corresponding to the end of handler block /// </summary> Label HandlerEnd(Handler info); } public interface ICodeConsumer<Local, Parameter, Method, Field, Type, Data, Result> { Result Accept<Label>(ICodeProvider<Label, Local, Parameter, Method, Field, Type> codeProvider, Label entryPoint, Data data); } public interface IMethodCodeConsumer<Local, Parameter, Method, Field, Type, Data, Result> { Result Accept<Label, Handler>(IMethodCodeProvider<Label, Local, Parameter, Method, Field, Type, Handler> codeProvider, Label entryPoint, Method method, Data data); } }
// 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; /// <summary> /// UInt64.System.IConvertible.ToType(Type,provider) /// </summary> public class UInt64IConvertibleToType { public static int Main() { UInt64IConvertibleToType ui64icttype = new UInt64IConvertibleToType(); TestLibrary.TestFramework.BeginTestCase("UInt64IConvertibleToType"); if (ui64icttype.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:UInt64 MinValue to Type of string"); try { UInt64 uintA = UInt64.MinValue; IConvertible iConvert = (IConvertible)(uintA); string strA = (string)iConvert.ToType(typeof(string), null); if (strA != uintA.ToString()) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:UInt64 MinValue to Type of bool"); try { UInt64 uintA = UInt64.MinValue; IConvertible iConvert = (IConvertible)(uintA); bool boolA = (bool)iConvert.ToType(typeof(bool), null); if (boolA) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:UInt64 MaxValue to Type of bool"); try { UInt64 uintA = UInt64.MaxValue; IConvertible iConvert = (IConvertible)(uintA); bool boolA = (bool)iConvert.ToType(typeof(bool), null); if (!boolA) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:Convert a random UInt64 to Type of double,decimal and single"); try { UInt64 uintA = this.GetInt64(0, UInt64.MaxValue); ; IConvertible iConvert = (IConvertible)(uintA); Double doubleA = (Double)iConvert.ToType(typeof(Double), null); Decimal decimalA = (Decimal)iConvert.ToType(typeof(Decimal), null); Single singleA = (Single)iConvert.ToType(typeof(Single), null); if (doubleA != uintA || decimalA != uintA || singleA != uintA) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5:UInt64 between MinValue to Int32.Max to Type of Int32"); try { UInt64 uintA = this.GetInt64(0, Int32.MaxValue); IConvertible iConvert = (IConvertible)(uintA); Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null); if (int32A != (Int32)uintA) { TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6:UInt64 between MinValue to Int16.Max to Type of Int16"); try { UInt64 uintA = this.GetInt64(0, Int16.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); Int16 int16A = (Int16)iConvert.ToType(typeof(Int16), null); if (int16A != (Int16)uintA) { TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7:UInt64 between MinValue and SByte.Max to Type of SByte"); try { UInt64 uintA = this.GetInt64(0, SByte.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); SByte sbyteA = (SByte)iConvert.ToType(typeof(SByte), null); if (sbyteA != (SByte)uintA) { TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8:UInt64 between MinValue and Byte.Max to Type of Byte"); try { UInt64 uintA = this.GetInt64(0, Byte.MaxValue + 1); IConvertible iConvert = (IConvertible)(uintA); Byte byteA = (Byte)iConvert.ToType(typeof(Byte), null); if (byteA != (Byte)uintA) { TestLibrary.TestFramework.LogError("015", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:UInt64 between Int32.MaxValue and UInt64.MaxValue to Type of Int32"); try { UInt64 uintA = this.GetInt64((ulong)Int32.MaxValue + 1, UInt64.MaxValue); IConvertible iConvert = (IConvertible)(uintA); Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The argument type is a null reference"); try { UInt64 uintA = 100; IConvertible iConvert = (IConvertible)(uintA); object oBject = (Int16)iConvert.ToType(null, null); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region ForTestObject private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #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. //------------------------------------------------------------------------------ namespace System.Data.SqlClient { /// <devdoc> Class of variables for the Tds connection. /// </devdoc> internal static class TdsEnums { // internal tdsparser constants public const string SQL_PROVIDER_NAME = Common.DbConnectionStringDefaults.ApplicationName; public static readonly decimal SQL_SMALL_MONEY_MIN = new decimal(-214748.3648); public static readonly decimal SQL_SMALL_MONEY_MAX = new decimal(214748.3647); // HACK!!! // Constant for SqlDbType.SmallVarBinary... store internal variable here instead of on // SqlDbType so that it is not surfaced to the user!!! Related to dtc and the fact that // the TransactionManager TDS stream is the only token left that uses VarBinarys instead of // BigVarBinarys. public const SqlDbType SmallVarBinary = (SqlDbType)(SqlDbType.Variant) + 1; // network protocol string constants public const string TCP = "tcp"; public const string NP = "np"; public const string RPC = "rpc"; public const string BV = "bv"; public const string ADSP = "adsp"; public const string SPX = "spx"; public const string VIA = "via"; public const string LPC = "lpc"; // network function string contants public const string INIT_SSPI_PACKAGE = "InitSSPIPackage"; public const string INIT_SESSION = "InitSession"; public const string CONNECTION_GET_SVR_USER = "ConnectionGetSvrUser"; public const string GEN_CLIENT_CONTEXT = "GenClientContext"; // tdsparser packet handling constants public const byte SOFTFLUSH = 0; public const byte HARDFLUSH = 1; public const byte IGNORE = 2; // header constants public const int HEADER_LEN = 8; public const int HEADER_LEN_FIELD_OFFSET = 2; public const int YUKON_HEADER_LEN = 12; //Yukon headers also include a MARS session id public const int MARS_ID_OFFSET = 8; public const int HEADERTYPE_QNOTIFICATION = 1; public const int HEADERTYPE_MARS = 2; public const int HEADERTYPE_TRACE = 3; // other various constants public const int SUCCEED = 1; public const int FAIL = 0; public const short TYPE_SIZE_LIMIT = 8000; public const int MIN_PACKET_SIZE = 512; // Login packet can be no greater than 4k until server sends us env-change // increasing packet size. public const int DEFAULT_LOGIN_PACKET_SIZE = 4096; public const int MAX_PRELOGIN_PAYLOAD_LENGTH = 1024; public const int MAX_PACKET_SIZE = 32768; public const int MAX_SERVER_USER_NAME = 256; // obtained from luxor // Severity 0 - 10 indicates informational (non-error) messages // Severity 11 - 16 indicates errors that can be corrected by user (syntax errors, etc...) // Severity 17 - 19 indicates failure due to insufficient resources in the server // (max locks exceeded, not enough memory, other internal server limits reached, etc..) // Severity 20 - 25 Severe problems with the server, connection terminated. public const byte MIN_ERROR_CLASS = 11; // webdata 100667: This should actually be 11 public const byte MAX_USER_CORRECTABLE_ERROR_CLASS = 16; public const byte FATAL_ERROR_CLASS = 20; // Message types public const byte MT_SQL = 1; // SQL command batch public const byte MT_LOGIN = 2; // Login message for pre-Sphinx (before version 7.0) public const byte MT_RPC = 3; // Remote procedure call public const byte MT_TOKENS = 4; // Table response data stream public const byte MT_BINARY = 5; // Unformatted binary response data (UNUSED) public const byte MT_ATTN = 6; // Attention (break) signal public const byte MT_BULK = 7; // Bulk load data public const byte MT_OPEN = 8; // Set up subchannel (UNUSED) public const byte MT_CLOSE = 9; // Close subchannel (UNUSED) public const byte MT_ERROR = 10; // Protocol error detected public const byte MT_ACK = 11; // Protocol acknowledgement (UNUSED) public const byte MT_ECHO = 12; // Echo data (UNUSED) public const byte MT_LOGOUT = 13; // Logout message (UNUSED) public const byte MT_TRANS = 14; // Transaction Manager Interface public const byte MT_OLEDB = 15; // ? (UNUSED) public const byte MT_LOGIN7 = 16; // Login message for Sphinx (version 7) or later public const byte MT_SSPI = 17; // SSPI message public const byte MT_PRELOGIN = 18; // Pre-login handshake // Message status bits public const byte ST_EOM = 0x1; // Packet is end-of-message public const byte ST_AACK = 0x2; // Packet acknowledges attention (server to client) public const byte ST_IGNORE = 0x2; // Ignore this event (client to server) public const byte ST_BATCH = 0x4; // Message is part of a batch. public const byte ST_RESET_CONNECTION = 0x8; // Exec sp_reset_connection prior to processing message public const byte ST_RESET_CONNECTION_PRESERVE_TRANSACTION = 0x10; // reset prior to processing, with preserving local tx // TDS control tokens public const byte SQLCOLFMT = 0xa1; public const byte SQLPROCID = 0x7c; public const byte SQLCOLNAME = 0xa0; public const byte SQLTABNAME = 0xa4; public const byte SQLCOLINFO = 0xa5; public const byte SQLALTNAME = 0xa7; public const byte SQLALTFMT = 0xa8; public const byte SQLERROR = 0xaa; public const byte SQLINFO = 0xab; public const byte SQLRETURNVALUE = 0xac; public const byte SQLRETURNSTATUS = 0x79; public const byte SQLRETURNTOK = 0xdb; public const byte SQLALTCONTROL = 0xaf; public const byte SQLROW = 0xd1; public const byte SQLNBCROW = 0xd2; // same as ROW with null-bit-compression support public const byte SQLALTROW = 0xd3; public const byte SQLDONE = 0xfd; public const byte SQLDONEPROC = 0xfe; public const byte SQLDONEINPROC = 0xff; public const byte SQLOFFSET = 0x78; public const byte SQLORDER = 0xa9; public const byte SQLDEBUG_CMD = 0x60; public const byte SQLLOGINACK = 0xad; public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state public const byte SQLENVCHANGE = 0xe3; // Environment change notification public const byte SQLSECLEVEL = 0xed; // Security level token ??? public const byte SQLROWCRC = 0x39; // ROWCRC datastream??? public const byte SQLCOLMETADATA = 0x81; // Column metadata including name public const byte SQLALTMETADATA = 0x88; // Alt column metadata including name public const byte SQLSSPI = 0xed; // SSPI data // Environment change notification streams // TYPE on TDS ENVCHANGE token stream (from sql\ntdbms\include\odsapi.h) // public const byte ENV_DATABASE = 1; // Database changed public const byte ENV_LANG = 2; // Language changed public const byte ENV_CHARSET = 3; // Character set changed public const byte ENV_PACKETSIZE = 4; // Packet size changed public const byte ENV_LOCALEID = 5; // Unicode data sorting locale id public const byte ENV_COMPFLAGS = 6; // Unicode data sorting comparison flags public const byte ENV_COLLATION = 7; // SQL Collation // The following are environment change tokens valid for Yukon or later. public const byte ENV_BEGINTRAN = 8; // Transaction began public const byte ENV_COMMITTRAN = 9; // Transaction committed public const byte ENV_ROLLBACKTRAN = 10; // Transaction rolled back public const byte ENV_ENLISTDTC = 11; // Enlisted in Distributed Transaction public const byte ENV_DEFECTDTC = 12; // Defected from Distributed Transaction public const byte ENV_LOGSHIPNODE = 13; // Realtime Log shipping primary node public const byte ENV_PROMOTETRANSACTION = 15; // Promote Transaction public const byte ENV_TRANSACTIONMANAGERADDRESS = 16; // Transaction Manager Address public const byte ENV_TRANSACTIONENDED = 17; // Transaction Ended public const byte ENV_SPRESETCONNECTIONACK = 18; // SP_Reset_Connection ack public const byte ENV_USERINSTANCE = 19; // User Instance public const byte ENV_ROUTING = 20; // Routing (ROR) information public enum EnvChangeType : byte { ENVCHANGE_DATABASE = ENV_DATABASE, ENVCHANGE_LANG = ENV_LANG, ENVCHANGE_CHARSET = ENV_CHARSET, ENVCHANGE_PACKETSIZE = ENV_PACKETSIZE, ENVCHANGE_LOCALEID = ENV_LOCALEID, ENVCHANGE_COMPFLAGS = ENV_COMPFLAGS, ENVCHANGE_COLLATION = ENV_COLLATION, ENVCHANGE_BEGINTRAN = ENV_BEGINTRAN, ENVCHANGE_COMMITTRAN = ENV_COMMITTRAN, ENVCHANGE_ROLLBACKTRAN = ENV_ROLLBACKTRAN, ENVCHANGE_ENLISTDTC = ENV_ENLISTDTC, ENVCHANGE_DEFECTDTC = ENV_DEFECTDTC, ENVCHANGE_LOGSHIPNODE = ENV_LOGSHIPNODE, ENVCHANGE_PROMOTETRANSACTION = ENV_PROMOTETRANSACTION, ENVCHANGE_TRANSACTIONMANAGERADDRESS = ENV_TRANSACTIONMANAGERADDRESS, ENVCHANGE_TRANSACTIONENDED = ENV_TRANSACTIONENDED, ENVCHANGE_SPRESETCONNECTIONACK = ENV_SPRESETCONNECTIONACK, ENVCHANGE_USERINSTANCE = ENV_USERINSTANCE, ENVCHANGE_ROUTING = ENV_ROUTING } // done status stream bit masks public const int DONE_MORE = 0x0001; // more command results coming public const int DONE_ERROR = 0x0002; // error in command batch public const int DONE_INXACT = 0x0004; // transaction in progress public const int DONE_PROC = 0x0008; // done from stored proc public const int DONE_COUNT = 0x0010; // count in done info public const int DONE_ATTN = 0x0020; // oob ack public const int DONE_INPROC = 0x0040; // like DONE_PROC except proc had error public const int DONE_RPCINBATCH = 0x0080; // Done from RPC in batch public const int DONE_SRVERROR = 0x0100; // Severe error in which resultset should be discarded public const int DONE_FMTSENT = 0x8000; // fmt message sent, done_inproc req'd // Feature Extension public const byte FEATUREEXT_TERMINATOR = 0xFF; public const byte FEATUREEXT_SRECOVERY = 0x01; [Flags] public enum FeatureExtension : uint { None = 0, SessionRecovery = 1, } // Loginrec defines public const byte MAX_LOG_NAME = 30; // TDS 4.2 login rec max name length public const byte MAX_PROG_NAME = 10; // max length of loginrec progran name public const byte SEC_COMP_LEN = 8; // length of security compartments public const byte MAX_PK_LEN = 6; // max length of TDS packet size public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes) public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes) public const int CLIENT_PROG_VER = 0x06000000; // Client interface version public const int YUKON_LOG_REC_FIXED_LEN = 0x5e; // misc public const int TEXT_TIME_STAMP_LEN = 8; public const int COLLATION_INFO_LEN = 4; /* public const byte INT4_LSB_HI = 0; // lsb is low byte (eg 68000) // public const byte INT4_LSB_LO = 1; // lsb is low byte (eg VAX) public const byte INT2_LSB_HI = 2; // lsb is low byte (eg 68000) // public const byte INT2_LSB_LO = 3; // lsb is low byte (eg VAX) public const byte FLT_IEEE_HI = 4; // lsb is low byte (eg 68000) public const byte CHAR_ASCII = 6; // ASCII character set public const byte TWO_I4_LSB_HI = 8; // lsb is low byte (eg 68000 // public const byte TWO_I4_LSB_LO = 9; // lsb is low byte (eg VAX) // public const byte FLT_IEEE_LO = 10; // lsb is low byte (eg MSDOS) public const byte FLT4_IEEE_HI = 12; // IEEE 4-byte floating point -lsb is high byte // public const byte FLT4_IEEE_LO = 13; // IEEE 4-byte floating point -lsb is low byte public const byte TWO_I2_LSB_HI = 16; // lsb is high byte // public const byte TWO_I2_LSB_LO = 17; // lsb is low byte public const byte LDEFSQL = 0; // server sends its default public const byte LDEFUSER = 0; // regular old user public const byte LINTEGRATED = 8; // integrated security login */ /* Versioning scheme table: Client sends: 0x70000000 -> Sphinx 0x71000000 -> Shiloh RTM 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM Server responds: 0x07000000 -> Sphinx // Notice server response format is different for bwd compat 0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM */ // Shiloh SP1 and beyond versioning scheme: // Majors: public const int YUKON_MAJOR = 0x72; // the high-byte is sufficient to distinguish later versions public const int KATMAI_MAJOR = 0x73; public const int DENALI_MAJOR = 0x74; // Increments: public const int YUKON_INCREMENT = 0x09; public const int KATMAI_INCREMENT = 0x0b; public const int DENALI_INCREMENT = 0x00; // Minors: public const int YUKON_RTM_MINOR = 0x0002; public const int KATMAI_MINOR = 0x0003; public const int DENALI_MINOR = 0x0004; public const int ORDER_68000 = 1; public const int USE_DB_ON = 1; public const int INIT_DB_FATAL = 1; public const int SET_LANG_ON = 1; public const int INIT_LANG_FATAL = 1; public const int ODBC_ON = 1; public const int SSPI_ON = 1; public const int REPL_ON = 3; // send the read-only intent to the server public const int READONLY_INTENT_ON = 1; // Token masks public const byte SQLLenMask = 0x30; // mask to check for length tokens public const byte SQLFixedLen = 0x30; // Mask to check for fixed token public const byte SQLVarLen = 0x20; // Value to check for variable length token public const byte SQLZeroLen = 0x10; // Value to check for zero length token public const byte SQLVarCnt = 0x00; // Value to check for variable count token // Token masks for COLINFO status public const byte SQLDifferentName = 0x20; // column name different than select list name public const byte SQLExpression = 0x4; // column was result of an expression public const byte SQLKey = 0x8; // column is part of the key for the table public const byte SQLHidden = 0x10; // column not part of select list but added because part of key // Token masks for COLMETADATA flags // first byte public const byte Nullable = 0x1; public const byte Identity = 0x10; public const byte Updatability = 0xb; // mask off bits 3 and 4 // second byte public const byte ClrFixedLen = 0x1; // Fixed length CLR type public const byte IsColumnSet = 0x4; // Column is an XML representation of an aggregation of other columns // null values public const uint VARLONGNULL = 0xffffffff; // null value for text and image types public const int VARNULL = 0xffff; // null value for character and binary types public const int MAXSIZE = 8000; // max size for any column public const byte FIXEDNULL = 0; public const ulong UDTNULL = 0xffffffffffffffff; // SQL Server Data Type Tokens. public const int SQLVOID = 0x1f; public const int SQLTEXT = 0x23; public const int SQLVARBINARY = 0x25; public const int SQLINTN = 0x26; public const int SQLVARCHAR = 0x27; public const int SQLBINARY = 0x2d; public const int SQLIMAGE = 0x22; public const int SQLCHAR = 0x2f; public const int SQLINT1 = 0x30; public const int SQLBIT = 0x32; public const int SQLINT2 = 0x34; public const int SQLINT4 = 0x38; public const int SQLMONEY = 0x3c; public const int SQLDATETIME = 0x3d; public const int SQLFLT8 = 0x3e; public const int SQLFLTN = 0x6d; public const int SQLMONEYN = 0x6e; public const int SQLDATETIMN = 0x6f; public const int SQLFLT4 = 0x3b; public const int SQLMONEY4 = 0x7a; public const int SQLDATETIM4 = 0x3a; public const int SQLDECIMALN = 0x6a; public const int SQLNUMERICN = 0x6c; public const int SQLUNIQUEID = 0x24; public const int SQLBIGCHAR = 0xaf; public const int SQLBIGVARCHAR = 0xa7; public const int SQLBIGBINARY = 0xad; public const int SQLBIGVARBINARY = 0xa5; public const int SQLBITN = 0x68; public const int SQLNCHAR = 0xef; public const int SQLNVARCHAR = 0xe7; public const int SQLNTEXT = 0x63; public const int SQLUDT = 0xF0; // aggregate operator type TDS tokens, used by compute statements: public const int AOPCNTB = 0x09; public const int AOPSTDEV = 0x30; public const int AOPSTDEVP = 0x31; public const int AOPVAR = 0x32; public const int AOPVARP = 0x33; public const int AOPCNT = 0x4b; public const int AOPSUM = 0x4d; public const int AOPAVG = 0x4f; public const int AOPMIN = 0x51; public const int AOPMAX = 0x52; public const int AOPANY = 0x53; public const int AOPNOOP = 0x56; // SQL Server user-defined type tokens we care about public const int SQLTIMESTAMP = 0x50; public const int MAX_NUMERIC_LEN = 0x11; // 17 bytes of data for max numeric/decimal length public const int DEFAULT_NUMERIC_PRECISION = 0x1D; // 29 is the default max numeric precision(Decimal.MaxValue) if not user set public const int SPHINX_DEFAULT_NUMERIC_PRECISION = 0x1C; // 28 is the default max numeric precision for Sphinx(Decimal.MaxValue doesn't work for sphinx) public const int MAX_NUMERIC_PRECISION = 0x26; // 38 is max numeric precision; public const byte UNKNOWN_PRECISION_SCALE = 0xff; // -1 is value for unknown precision or scale // The following datatypes are specific to SHILOH (version 8) and later. public const int SQLINT8 = 0x7f; public const int SQLVARIANT = 0x62; // The following datatypes are specific to Yukon (version 9) or later public const int SQLXMLTYPE = 0xf1; public const int XMLUNICODEBOM = 0xfeff; public static readonly byte[] XMLUNICODEBOMBYTES = { 0xff, 0xfe }; // The following datatypes are specific to Katmai (version 10) or later public const int SQLTABLE = 0xf3; public const int SQLDATE = 0x28; public const int SQLTIME = 0x29; public const int SQLDATETIME2 = 0x2a; public const int SQLDATETIMEOFFSET = 0x2b; public const int DEFAULT_VARTIME_SCALE = 7; //Partially length prefixed datatypes constants. These apply to XMLTYPE, BIGVARCHRTYPE, // NVARCHARTYPE, and BIGVARBINTYPE. Valid for Yukon or later public const ulong SQL_PLP_NULL = 0xffffffffffffffff; // Represents null value public const ulong SQL_PLP_UNKNOWNLEN = 0xfffffffffffffffe; // Data coming in chunks, total length unknown public const int SQL_PLP_CHUNK_TERMINATOR = 0x00000000; // Represents end of chunked data. public const ushort SQL_USHORTVARMAXLEN = 0xffff; // Second ushort in TDS stream is this value if one of max types // TVPs require some new in-value control tokens: public const byte TVP_ROWCOUNT_ESTIMATE = 0x12; public const byte TVP_ROW_TOKEN = 0x01; public const byte TVP_END_TOKEN = 0x00; public const ushort TVP_NOMETADATA_TOKEN = 0xFFFF; public const byte TVP_ORDER_UNIQUE_TOKEN = 0x10; // TvpColumnMetaData flags public const int TVP_DEFAULT_COLUMN = 0x200; // TVP_ORDER_UNIQUE_TOKEN flags public const byte TVP_ORDERASC_FLAG = 0x1; public const byte TVP_ORDERDESC_FLAG = 0x2; public const byte TVP_UNIQUE_FLAG = 0x4; // RPC function names public const string SP_EXECUTESQL = "sp_executesql"; // used against 7.0 servers public const string SP_PREPEXEC = "sp_prepexec"; // used against 7.5 servers public const string SP_PREPARE = "sp_prepare"; // used against 7.0 servers public const string SP_EXECUTE = "sp_execute"; public const string SP_UNPREPARE = "sp_unprepare"; public const string SP_PARAMS = "sp_procedure_params_rowset"; public const string SP_PARAMS_MANAGED = "sp_procedure_params_managed"; public const string SP_PARAMS_MGD10 = "sp_procedure_params_100_managed"; // RPC ProcID's // NOTE: It is more efficient to call these procs using ProcID's instead of names public const ushort RPC_PROCID_CURSOR = 1; public const ushort RPC_PROCID_CURSOROPEN = 2; public const ushort RPC_PROCID_CURSORPREPARE = 3; public const ushort RPC_PROCID_CURSOREXECUTE = 4; public const ushort RPC_PROCID_CURSORPREPEXEC = 5; public const ushort RPC_PROCID_CURSORUNPREPARE = 6; public const ushort RPC_PROCID_CURSORFETCH = 7; public const ushort RPC_PROCID_CURSOROPTION = 8; public const ushort RPC_PROCID_CURSORCLOSE = 9; public const ushort RPC_PROCID_EXECUTESQL = 10; public const ushort RPC_PROCID_PREPARE = 11; public const ushort RPC_PROCID_EXECUTE = 12; public const ushort RPC_PROCID_PREPEXEC = 13; public const ushort RPC_PROCID_PREPEXECRPC = 14; public const ushort RPC_PROCID_UNPREPARE = 15; // For Transactions public const string TRANS_BEGIN = "BEGIN TRANSACTION"; public const string TRANS_COMMIT = "COMMIT TRANSACTION"; public const string TRANS_ROLLBACK = "ROLLBACK TRANSACTION"; public const string TRANS_IF_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION"; public const string TRANS_SAVE = "SAVE TRANSACTION"; // For Transactions - isolation levels public const string TRANS_READ_COMMITTED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; public const string TRANS_READ_UNCOMMITTED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; public const string TRANS_REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"; public const string TRANS_SERIALIZABLE = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"; public const string TRANS_SNAPSHOT = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT"; // Batch RPC flags public const byte SHILOH_RPCBATCHFLAG = 0x80; public const byte YUKON_RPCBATCHFLAG = 0xFF; // RPC flags public const byte RPC_RECOMPILE = 0x1; public const byte RPC_NOMETADATA = 0x2; // RPC parameter class public const byte RPC_PARAM_BYREF = 0x1; public const byte RPC_PARAM_DEFAULT = 0x2; public const byte RPC_PARAM_IS_LOB_COOKIE = 0x8; // SQL parameter list text public const string PARAM_OUTPUT = "output"; // SQL Parameter constants public const int MAX_PARAMETER_NAME_LENGTH = 128; // metadata options (added around an existing sql statement) // prefixes public const string FMTONLY_ON = " SET FMTONLY ON;"; public const string FMTONLY_OFF = " SET FMTONLY OFF;"; // suffixes public const string BROWSE_ON = " SET NO_BROWSETABLE ON;"; public const string BROWSE_OFF = " SET NO_BROWSETABLE OFF;"; // generic table name public const string TABLE = "Table"; public const int EXEC_THRESHOLD = 0x3; // if the number of commands we execute is > than this threshold, than do prep/exec/unprep instead // of executesql. // dbnetlib error values public const short TIMEOUT_EXPIRED = -2; public const short ENCRYPTION_NOT_SUPPORTED = 20; // CAUTION: These are not error codes returned by SNI. This is used for backward compatibility // since netlib (now removed from sqlclient) returned these codes. // SQL error values (from sqlerrorcodes.h) public const int LOGON_FAILED = 18456; public const int PASSWORD_EXPIRED = 18488; public const int IMPERSONATION_FAILED = 1346; public const int P_TOKENTOOLONG = 103; // SNI\Win32 error values // NOTE: these are simply windows system error codes, not SNI specific public const uint SNI_UNINITIALIZED = unchecked((uint)-1); public const uint SNI_SUCCESS = 0; // The operation completed successfully. public const uint SNI_ERROR = 1; // Error public const uint SNI_WAIT_TIMEOUT = 258; // The wait operation timed out. public const uint SNI_SUCCESS_IO_PENDING = 997; // Overlapped I/O operation is in progress. // Windows Sockets Error Codes public const short SNI_WSAECONNRESET = 10054; // An existing connection was forcibly closed by the remote host. // SNI internal errors (shouldn't overlap with Win32 / socket errors) public const uint SNI_QUEUE_FULL = 1048576; // Packet queue is full // SNI flags public const uint SNI_SSL_VALIDATE_CERTIFICATE = 1; // This enables validation of server certificate public const uint SNI_SSL_USE_SCHANNEL_CACHE = 2; // This enables schannel session cache public const uint SNI_SSL_IGNORE_CHANNEL_BINDINGS = 0x10; // Used with SSL Provider, sent to SNIAddProvider in case of SQL Authentication & Encrypt. public const string DEFAULT_ENGLISH_CODE_PAGE_STRING = "iso_1"; public const short DEFAULT_ENGLISH_CODE_PAGE_VALUE = 1252; public const short CHARSET_CODE_PAGE_OFFSET = 2; internal const int MAX_SERVERNAME = 255; // Sql Statement Tokens in the DONE packet // (see ntdbms\ntinc\tokens.h) // internal const ushort SELECT = 0xc1; internal const ushort INSERT = 0xc3; internal const ushort DELETE = 0xc4; internal const ushort UPDATE = 0xc5; internal const ushort ABORT = 0xd2; internal const ushort BEGINXACT = 0xd4; internal const ushort ENDXACT = 0xd5; internal const ushort BULKINSERT = 0xf0; internal const ushort OPENCURSOR = 0x20; internal const ushort MERGE = 0x117; // Login data validation Rules // internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name internal const ushort MAXLEN_USERNAME = 128; // the client user id internal const ushort MAXLEN_PASSWORD = 128; // the password supplied by the client internal const ushort MAXLEN_APPNAME = 128; // the client application name internal const ushort MAXLEN_SERVERNAME = 128; // the server name internal const ushort MAXLEN_CLIENTINTERFACE = 128; // the interface library name internal const ushort MAXLEN_LANGUAGE = 128; // the initial language internal const ushort MAXLEN_DATABASE = 128; // the initial database internal const ushort MAXLEN_ATTACHDBFILE = 260; // the filename for a database that is to be attached during the connection process internal const ushort MAXLEN_NEWPASSWORD = 128; // new password for the specified login. // array copied directly from tdssort.h from luxor public static readonly ushort[] CODE_PAGE_FROM_SORT_ID = { 0, /* 0 */ 0, /* 1 */ 0, /* 2 */ 0, /* 3 */ 0, /* 4 */ 0, /* 5 */ 0, /* 6 */ 0, /* 7 */ 0, /* 8 */ 0, /* 9 */ 0, /* 10 */ 0, /* 11 */ 0, /* 12 */ 0, /* 13 */ 0, /* 14 */ 0, /* 15 */ 0, /* 16 */ 0, /* 17 */ 0, /* 18 */ 0, /* 19 */ 0, /* 20 */ 0, /* 21 */ 0, /* 22 */ 0, /* 23 */ 0, /* 24 */ 0, /* 25 */ 0, /* 26 */ 0, /* 27 */ 0, /* 28 */ 0, /* 29 */ 437, /* 30 */ 437, /* 31 */ 437, /* 32 */ 437, /* 33 */ 437, /* 34 */ 0, /* 35 */ 0, /* 36 */ 0, /* 37 */ 0, /* 38 */ 0, /* 39 */ 850, /* 40 */ 850, /* 41 */ 850, /* 42 */ 850, /* 43 */ 850, /* 44 */ 0, /* 45 */ 0, /* 46 */ 0, /* 47 */ 0, /* 48 */ 850, /* 49 */ 1252, /* 50 */ 1252, /* 51 */ 1252, /* 52 */ 1252, /* 53 */ 1252, /* 54 */ 850, /* 55 */ 850, /* 56 */ 850, /* 57 */ 850, /* 58 */ 850, /* 59 */ 850, /* 60 */ 850, /* 61 */ 0, /* 62 */ 0, /* 63 */ 0, /* 64 */ 0, /* 65 */ 0, /* 66 */ 0, /* 67 */ 0, /* 68 */ 0, /* 69 */ 0, /* 70 */ 1252, /* 71 */ 1252, /* 72 */ 1252, /* 73 */ 1252, /* 74 */ 1252, /* 75 */ 0, /* 76 */ 0, /* 77 */ 0, /* 78 */ 0, /* 79 */ 1250, /* 80 */ 1250, /* 81 */ 1250, /* 82 */ 1250, /* 83 */ 1250, /* 84 */ 1250, /* 85 */ 1250, /* 86 */ 1250, /* 87 */ 1250, /* 88 */ 1250, /* 89 */ 1250, /* 90 */ 1250, /* 91 */ 1250, /* 92 */ 1250, /* 93 */ 1250, /* 94 */ 1250, /* 95 */ 1250, /* 96 */ 1250, /* 97 */ 1250, /* 98 */ 0, /* 99 */ 0, /* 100 */ 0, /* 101 */ 0, /* 102 */ 0, /* 103 */ 1251, /* 104 */ 1251, /* 105 */ 1251, /* 106 */ 1251, /* 107 */ 1251, /* 108 */ 0, /* 109 */ 0, /* 110 */ 0, /* 111 */ 1253, /* 112 */ 1253, /* 113 */ 1253, /* 114 */ 0, /* 115 */ 0, /* 116 */ 0, /* 117 */ 0, /* 118 */ 0, /* 119 */ 1253, /* 120 */ 1253, /* 121 */ 1253, /* 122 */ 0, /* 123 */ 1253, /* 124 */ 0, /* 125 */ 0, /* 126 */ 0, /* 127 */ 1254, /* 128 */ 1254, /* 129 */ 1254, /* 130 */ 0, /* 131 */ 0, /* 132 */ 0, /* 133 */ 0, /* 134 */ 0, /* 135 */ 1255, /* 136 */ 1255, /* 137 */ 1255, /* 138 */ 0, /* 139 */ 0, /* 140 */ 0, /* 141 */ 0, /* 142 */ 0, /* 143 */ 1256, /* 144 */ 1256, /* 145 */ 1256, /* 146 */ 0, /* 147 */ 0, /* 148 */ 0, /* 149 */ 0, /* 150 */ 0, /* 151 */ 1257, /* 152 */ 1257, /* 153 */ 1257, /* 154 */ 1257, /* 155 */ 1257, /* 156 */ 1257, /* 157 */ 1257, /* 158 */ 1257, /* 159 */ 1257, /* 160 */ 0, /* 161 */ 0, /* 162 */ 0, /* 163 */ 0, /* 164 */ 0, /* 165 */ 0, /* 166 */ 0, /* 167 */ 0, /* 168 */ 0, /* 169 */ 0, /* 170 */ 0, /* 171 */ 0, /* 172 */ 0, /* 173 */ 0, /* 174 */ 0, /* 175 */ 0, /* 176 */ 0, /* 177 */ 0, /* 178 */ 0, /* 179 */ 0, /* 180 */ 0, /* 181 */ 0, /* 182 */ 1252, /* 183 */ 1252, /* 184 */ 1252, /* 185 */ 1252, /* 186 */ 0, /* 187 */ 0, /* 188 */ 0, /* 189 */ 0, /* 190 */ 0, /* 191 */ 932, /* 192 */ 932, /* 193 */ 949, /* 194 */ 949, /* 195 */ 950, /* 196 */ 950, /* 197 */ 936, /* 198 */ 936, /* 199 */ 932, /* 200 */ 949, /* 201 */ 950, /* 202 */ 936, /* 203 */ 874, /* 204 */ 874, /* 205 */ 874, /* 206 */ 0, /* 207 */ 0, /* 208 */ 0, /* 209 */ 1252, /* 210 */ 1252, /* 211 */ 1252, /* 212 */ 1252, /* 213 */ 1252, /* 214 */ 1252, /* 215 */ 1252, /* 216 */ 1252, /* 217 */ 0, /* 218 */ 0, /* 219 */ 0, /* 220 */ 0, /* 221 */ 0, /* 222 */ 0, /* 223 */ 0, /* 224 */ 0, /* 225 */ 0, /* 226 */ 0, /* 227 */ 0, /* 228 */ 0, /* 229 */ 0, /* 230 */ 0, /* 231 */ 0, /* 232 */ 0, /* 233 */ 0, /* 234 */ 0, /* 235 */ 0, /* 236 */ 0, /* 237 */ 0, /* 238 */ 0, /* 239 */ 0, /* 240 */ 0, /* 241 */ 0, /* 242 */ 0, /* 243 */ 0, /* 244 */ 0, /* 245 */ 0, /* 246 */ 0, /* 247 */ 0, /* 248 */ 0, /* 249 */ 0, /* 250 */ 0, /* 251 */ 0, /* 252 */ 0, /* 253 */ 0, /* 254 */ 0, /* 255 */ }; internal enum TransactionManagerRequestType { Begin = 5, Commit = 7, Rollback = 8, Save = 9 }; internal enum TransactionManagerIsolationLevel { Unspecified = 0x00, ReadUncommitted = 0x01, ReadCommitted = 0x02, RepeatableRead = 0x03, Serializable = 0x04, Snapshot = 0x05 } internal enum GenericType { MultiSet = 131, }; // Date, Time, DateTime2, DateTimeOffset specific constants internal static readonly long[] TICKS_FROM_SCALE = { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, }; internal const int WHIDBEY_DATE_LENGTH = 10; internal static readonly int[] WHIDBEY_TIME_LENGTH = { 8, 10, 11, 12, 13, 14, 15, 16 }; internal static readonly int[] WHIDBEY_DATETIME2_LENGTH = { 19, 21, 22, 23, 24, 25, 26, 27 }; internal static readonly int[] WHIDBEY_DATETIMEOFFSET_LENGTH = { 26, 28, 29, 30, 31, 32, 33, 34 }; } internal enum SniContext { Undefined = 0, Snix_Connect, Snix_PreLoginBeforeSuccessfullWrite, Snix_PreLogin, Snix_LoginSspi, Snix_ProcessSspi, Snix_Login, Snix_EnableMars, Snix_AutoEnlist, Snix_GetMarsSession, Snix_Execute, Snix_Read, Snix_Close, Snix_SendRows, } }
using System.Diagnostics; using System.Threading.Tasks; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Internal methods internal async Task< int > ReadContentAsBase64Async( byte[] buffer, int index, int count ) { // check arguments if ( buffer == null ) { throw new ArgumentNullException( "buffer" ); } if ( count < 0 ) { throw new ArgumentOutOfRangeException( "count" ); } if ( index < 0 ) { throw new ArgumentOutOfRangeException( "index" ); } if ( buffer.Length - index < count ) { throw new ArgumentOutOfRangeException( "count" ); } switch ( state ) { case State.None: if ( !reader.CanReadContentAs() ) { throw reader.CreateReadContentAsException( "ReadContentAsBase64" ); } if ( !await InitAsync().ConfigureAwait(false) ) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if ( decoder == base64Decoder ) { // read more binary data return await ReadContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } Debug.Assert( state == State.InReadContent ); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } internal async Task< int > ReadContentAsBinHexAsync( byte[] buffer, int index, int count ) { // check arguments if ( buffer == null ) { throw new ArgumentNullException( "buffer" ); } if ( count < 0 ) { throw new ArgumentOutOfRangeException( "count" ); } if ( index < 0 ) { throw new ArgumentOutOfRangeException( "index" ); } if ( buffer.Length - index < count ) { throw new ArgumentOutOfRangeException( "count" ); } switch ( state ) { case State.None: if ( !reader.CanReadContentAs() ) { throw reader.CreateReadContentAsException( "ReadContentAsBinHex" ); } if ( !await InitAsync().ConfigureAwait(false) ) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if ( decoder == binHexDecoder ) { // read more binary data return await ReadContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); default: Debug.Assert( false ); return 0; } Debug.Assert( state == State.InReadContent ); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } internal async Task< int > ReadElementContentAsBase64Async( byte[] buffer, int index, int count ) { // check arguments if ( buffer == null ) { throw new ArgumentNullException( "buffer" ); } if ( count < 0 ) { throw new ArgumentOutOfRangeException( "count" ); } if ( index < 0 ) { throw new ArgumentOutOfRangeException( "index" ); } if ( buffer.Length - index < count ) { throw new ArgumentOutOfRangeException( "count" ); } switch ( state ) { case State.None: if ( reader.NodeType != XmlNodeType.Element ) { throw reader.CreateReadElementContentAsException( "ReadElementContentAsBase64" ); } if ( !await InitOnElementAsync().ConfigureAwait(false) ) { return 0; } break; case State.InReadContent: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); case State.InReadElementContent: // if we have a correct decoder, go read if ( decoder == base64Decoder ) { // read more binary data return await ReadElementContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } break; default: Debug.Assert( false ); return 0; } Debug.Assert( state == State.InReadElementContent ); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadElementContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } internal async Task< int > ReadElementContentAsBinHexAsync( byte[] buffer, int index, int count ) { // check arguments if ( buffer == null ) { throw new ArgumentNullException( "buffer" ); } if ( count < 0 ) { throw new ArgumentOutOfRangeException( "count" ); } if ( index < 0 ) { throw new ArgumentOutOfRangeException( "index" ); } if ( buffer.Length - index < count ) { throw new ArgumentOutOfRangeException( "count" ); } switch ( state ) { case State.None: if ( reader.NodeType != XmlNodeType.Element ) { throw reader.CreateReadElementContentAsException( "ReadElementContentAsBinHex" ); } if ( !await InitOnElementAsync().ConfigureAwait(false) ) { return 0; } break; case State.InReadContent: throw new InvalidOperationException( Res.GetString( Res.Xml_MixingBinaryContentMethods ) ); case State.InReadElementContent: // if we have a correct decoder, go read if ( decoder == binHexDecoder ) { // read more binary data return await ReadElementContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } break; default: Debug.Assert( false ); return 0; } Debug.Assert( state == State.InReadElementContent ); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadElementContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); } internal async Task FinishAsync() { if ( state != State.None ) { while ( await MoveToNextContentNodeAsync( true ).ConfigureAwait(false) ) ; if ( state == State.InReadElementContent ) { if ( reader.NodeType != XmlNodeType.EndElement ) { throw new XmlException( Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo ); } // move off the EndElement await reader.ReadAsync().ConfigureAwait(false); } } Reset(); } // Private methods private async Task< bool > InitAsync() { // make sure we are on a content node if ( !await MoveToNextContentNodeAsync( false ).ConfigureAwait(false) ) { return false; } state = State.InReadContent; isEnd = false; return true; } private async Task< bool > InitOnElementAsync() { Debug.Assert( reader.NodeType == XmlNodeType.Element ); bool isEmpty = reader.IsEmptyElement; // move to content or off the empty element await reader.ReadAsync().ConfigureAwait(false); if ( isEmpty ) { return false; } // make sure we are on a content node if ( !await MoveToNextContentNodeAsync( false ).ConfigureAwait(false) ) { if ( reader.NodeType != XmlNodeType.EndElement ) { throw new XmlException( Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo ); } // move off end element await reader.ReadAsync().ConfigureAwait(false); return false; } state = State.InReadElementContent; isEnd = false; return true; } private async Task< int > ReadContentAsBinaryAsync( byte[] buffer, int index, int count ) { Debug.Assert( decoder != null ); if ( isEnd ) { Reset(); return 0; } decoder.SetNextOutputBuffer( buffer, index, count ); for (;;) { // use streaming ReadValueChunk if the reader supports it if ( canReadValueChunk ) { for (;;) { if ( valueOffset < valueChunkLength ) { int decodedCharsCount = decoder.Decode( valueChunk, valueOffset, valueChunkLength - valueOffset ); valueOffset += decodedCharsCount; } if ( decoder.IsFull ) { return decoder.DecodedCount; } Debug.Assert( valueOffset == valueChunkLength ); if ( ( valueChunkLength = await reader.ReadValueChunkAsync( valueChunk, 0, ChunkSize ).ConfigureAwait(false) ) == 0 ) { break; } valueOffset = 0; } } else { // read what is reader.Value string value = await reader.GetValueAsync().ConfigureAwait(false); int decodedCharsCount = decoder.Decode( value, valueOffset, value.Length - valueOffset ); valueOffset += decodedCharsCount; if ( decoder.IsFull ) { return decoder.DecodedCount; } } valueOffset = 0; // move to next textual node in the element content; throw on sub elements if ( !await MoveToNextContentNodeAsync( true ).ConfigureAwait(false) ) { isEnd = true; return decoder.DecodedCount; } } } private async Task< int > ReadElementContentAsBinaryAsync( byte[] buffer, int index, int count ) { if ( count == 0 ) { return 0; } // read binary int decoded = await ReadContentAsBinaryAsync( buffer, index, count ).ConfigureAwait(false); if ( decoded > 0 ) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if ( reader.NodeType != XmlNodeType.EndElement ) { throw new XmlException( Res.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo ); } // move off the EndElement await reader.ReadAsync().ConfigureAwait(false); state = State.None; return 0; } async Task< bool > MoveToNextContentNodeAsync( bool moveIfOnContentNode ) { do { switch ( reader.NodeType ) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if ( !moveIfOnContentNode ) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if ( reader.CanResolveEntity ) { reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while ( await reader.ReadAsync().ConfigureAwait(false) ); return false; } } }
using System; using System.Linq; using FluentMigrator.Builder.Create.Index; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure.Extensions; using FluentMigrator.Model; using FluentMigrator.Postgres; using FluentMigrator.Runner.Generators.Postgres; using FluentMigrator.Runner.Processors.Postgres; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Generators.Postgres { [TestFixture] public class PostgresIndexTests : BaseIndexTests { protected PostgresGenerator Generator; [SetUp] public void Setup() { var quoter = new PostgresQuoter(new PostgresOptions()); Generator = CreateGenerator(quoter); } protected virtual PostgresGenerator CreateGenerator(PostgresQuoter quoter) { return new PostgresGenerator(quoter); } [Test] public override void CanCreateIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateIndexExpression(); expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"TestSchema\".\"TestTable1\" (\"TestColumn1\" ASC);"); } [Test] public override void CanCreateIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateIndexExpression(); var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC);"); } [Test] public override void CanCreateMultiColumnIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnCreateIndexExpression(); expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"TestSchema\".\"TestTable1\" (\"TestColumn1\" ASC,\"TestColumn2\" DESC);"); } [Test] public override void CanCreateMultiColumnIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateMultiColumnCreateIndexExpression(); var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC,\"TestColumn2\" DESC);"); } [Test] public override void CanCreateMultiColumnUniqueIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateUniqueMultiColumnIndexExpression(); expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE INDEX \"TestIndex\" ON \"TestSchema\".\"TestTable1\" (\"TestColumn1\" ASC,\"TestColumn2\" DESC);"); } [Test] public override void CanCreateMultiColumnUniqueIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateUniqueMultiColumnIndexExpression(); var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC,\"TestColumn2\" DESC);"); } [Test] public override void CanCreateUniqueIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetCreateUniqueIndexExpression(); expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE INDEX \"TestIndex\" ON \"TestSchema\".\"TestTable1\" (\"TestColumn1\" ASC);"); } [Test] public override void CanCreateUniqueIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetCreateUniqueIndexExpression(); var result = Generator.Generate(expression); result.ShouldBe("CREATE UNIQUE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC);"); } [Test] public override void CanDropIndexWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteIndexExpression(); expression.Index.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("DROP INDEX \"TestSchema\".\"TestIndex\";"); } [Test] public override void CanDropIndexWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteIndexExpression(); var result = Generator.Generate(expression); result.ShouldBe("DROP INDEX \"public\".\"TestIndex\";"); } // This index method doesn't support ASC/DES neither NULLS sort [TestCase(Algorithm.Brin)] [TestCase(Algorithm.Gin)] [TestCase(Algorithm.Gist)] [TestCase(Algorithm.Hash)] [TestCase(Algorithm.Spgist)] public void CanCreateIndexUsingIndexAlgorithm(Algorithm algorithm) { var expression = GetCreateIndexWithExpression(x => { var definition = x.Index.GetAdditionalFeature(PostgresExtensions.IndexAlgorithm, () => new PostgresIndexAlgorithmDefinition()); definition.Algorithm = algorithm; }); var result = Generator.Generate(expression); result.ShouldBe($"CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" USING {algorithm.ToString().ToUpper()} (\"TestColumn1\");"); } [Test] public void CanCreateIndexWithFilter() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexFilter, () => "\"TestColumn1\" > 100"); }); var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC) WHERE \"TestColumn1\" > 100;"); } protected static CreateIndexExpression GetCreateIndexWithExpression(Action<CreateIndexExpression> additionalFeature) { var expression = new CreateIndexExpression { Index = { Name = GeneratorTestHelper.TestIndexName, TableName = GeneratorTestHelper.TestTableName1 } }; expression.Index.Columns.Add(new IndexColumnDefinition { Direction = Direction.Ascending, Name = GeneratorTestHelper.TestColumnName1 }); additionalFeature(expression); return expression; } [Test] public void CanCreateIndexAsConcurrently() { var expression = GetCreateIndexWithExpression( x => { var definitionIsOnly = x.Index.GetAdditionalFeature(PostgresExtensions.Concurrently, () => new PostgresIndexConcurrentlyDefinition()); definitionIsOnly.IsConcurrently = true; }); var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX CONCURRENTLY \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC);"); } [Test] public virtual void CanCreateIndexAsOnly() { var expression = GetCreateIndexWithExpression( x => { var definitionIsOnly = x.Index.GetAdditionalFeature(PostgresExtensions.Only, () => new PostgresIndexOnlyDefinition()); definitionIsOnly.IsOnly = true; }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [TestCase(NullSort.First)] [TestCase(NullSort.Last)] public void CanCreateIndexWithNulls(NullSort sort) { var expression = GetCreateIndexWithExpression(x => { x.Index.Columns.First().GetAdditionalFeature( PostgresExtensions.NullsSort, () => new PostgresIndexNullsSort { Sort = sort }); }); var result = Generator.Generate(expression); result.ShouldBe($"CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC NULLS {sort.ToString().ToUpper()});"); } [Test] public void CanCreateIndexWithFillfactor() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexFillFactor, () => 90); }); var result = Generator.Generate(expression); result.ShouldBe($"CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC) WITH ( FILLFACTOR = 90 );"); } [TestCase(true)] [TestCase(false)] public void CanCreateIndexWithFastUpdate(bool fastUpdate) { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexFastUpdate, () => fastUpdate); }); var onOff = fastUpdate ? "ON" : "OFF"; var result = Generator.Generate(expression); result.ShouldBe($"CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC) WITH ( FASTUPDATE = {onOff} );"); } [Test] public virtual void CanCreateIndexWithVacuumCleanupIndexScaleFactor() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexVacuumCleanupIndexScaleFactor, () => (float)0.1); }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [TestCase(GistBuffering.Auto)] [TestCase(GistBuffering.On)] [TestCase(GistBuffering.Off)] public virtual void CanCreateIndexWithBuffering(GistBuffering buffering) { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexBuffering, () => buffering); }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [Test] public virtual void CanCreateIndexWithGinPendingListLimit() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexGinPendingListLimit, () => (long)128); }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [Test] public virtual void CanCreateIndexWithPagesPerRange() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexPagesPerRange, () => 128); }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [TestCase(true)] [TestCase(false)] public virtual void CanCreateIndexWithAutosummarize(bool autosummarize) { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexAutosummarize, () => autosummarize); }); Assert.Throws<NotSupportedException>(() => Generator.Generate(expression)); } [Test] public void CanCreateIndexWithTablespace() { var expression = GetCreateIndexWithExpression(x => { x.Index.GetAdditionalFeature(PostgresExtensions.IndexTablespace, () => "indexspace"); }); var result = Generator.Generate(expression); result.ShouldBe("CREATE INDEX \"TestIndex\" ON \"public\".\"TestTable1\" (\"TestColumn1\" ASC) TABLESPACE indexspace;"); } } }
using System; using System.Collections.Generic; using System.Linq; using Should; using Xunit; namespace AutoMapper.UnitTests { namespace BidirectionalRelationships { public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship : AutoMapperSpecBase { private ParentDto _dto; protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<ParentModel, ParentDto>().PreserveReferences(); cfg.CreateMap<ChildModel, ChildDto>(); }); protected override void Because_of() { var parent = new ParentModel { ID = "PARENT_ONE" }; parent.AddChild(new ChildModel { ID = "CHILD_ONE" }); parent.AddChild(new ChildModel { ID = "CHILD_TWO" }); _dto = Mapper.Map<ParentModel, ParentDto>(parent); } [Fact] public void Should_preserve_the_parent_child_relationship_on_the_destination() { _dto.Children[0].Parent.ShouldBeSameAs(_dto); _dto.Children[1].Parent.ShouldBeSameAs(_dto); } public class ParentModel { public ParentModel() { Children = new List<ChildModel>(); } public string ID { get; set; } public IList<ChildModel> Children { get; private set; } public void AddChild(ChildModel child) { child.Parent = this; Children.Add(child); } } public class ChildModel { public string ID { get; set; } public ParentModel Parent { get; set; } } public class ParentDto { public string ID { get; set; } public IList<ChildDto> Children { get; set; } } public class ChildDto { public string ID { get; set; } public ParentDto Parent { get; set; } } } //public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship_using_CustomMapper_StackOverflow : AutoMapperSpecBase //{ // private ParentDto _dto; // private ParentModel _parent; // protected override void Establish_context() // { // _parent = new ParentModel // { // ID = 2 // }; // List<ChildModel> childModels = new List<ChildModel> // { // new ChildModel // { // ID = 1, // Parent = _parent // } // }; // Dictionary<int, ParentModel> parents = childModels.ToDictionary(x => x.ID, x => x.Parent); // Mapper.CreateMap<int, ParentDto>().ConvertUsing(new ChildIdToParentDtoConverter(parents)); // Mapper.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels)); // Mapper.CreateMap<ParentModel, ParentDto>() // .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.ID)); // Mapper.CreateMap<ChildModel, ChildDto>(); // config.AssertConfigurationIsValid(); // } // protected override void Because_of() // { // _dto = Mapper.Map<ParentModel, ParentDto>(_parent); // } // [Fact(Skip = "This test breaks the Test Runner")] // public void Should_preserve_the_parent_child_relationship_on_the_destination() // { // _dto.Children[0].Parent.ID.ShouldEqual(_dto.ID); // } // public class ChildIdToParentDtoConverter : ITypeConverter<int, ParentDto> // { // private readonly Dictionary<int, ParentModel> _parentModels; // public ChildIdToParentDtoConverter(Dictionary<int, ParentModel> parentModels) // { // _parentModels = parentModels; // } // public ParentDto Convert(int childId) // { // ParentModel parentModel = _parentModels[childId]; // MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; // return mappingEngine.Map<ParentModel, ParentDto>(parentModel); // } // } // public class ParentIdToChildDtoListConverter : ITypeConverter<int, List<ChildDto>> // { // private readonly IList<ChildModel> _childModels; // public ParentIdToChildDtoListConverter(IList<ChildModel> childModels) // { // _childModels = childModels; // } // protected override List<ChildDto> ConvertCore(int childId) // { // List<ChildModel> childModels = _childModels.Where(x => x.Parent.ID == childId).ToList(); // MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; // return mappingEngine.Map<List<ChildModel>, List<ChildDto>>(childModels); // } // } // public class ParentModel // { // public int ID { get; set; } // } // public class ChildModel // { // public int ID { get; set; } // public ParentModel Parent { get; set; } // } // public class ParentDto // { // public int ID { get; set; } // public List<ChildDto> Children { get; set; } // } // public class ChildDto // { // public int ID { get; set; } // public ParentDto Parent { get; set; } // } //} public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship_using_CustomMapper_with_context : AutoMapperSpecBase { private ParentDto _dto; private static ParentModel _parent; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { _parent = new ParentModel { ID = 2 }; List<ChildModel> childModels = new List<ChildModel> { new ChildModel { ID = 1, Parent = _parent } }; Dictionary<int, ParentModel> parents = childModels.ToDictionary(x => x.ID, x => x.Parent); cfg.CreateMap<int, ParentDto>().ConvertUsing(new ChildIdToParentDtoConverter(parents)); cfg.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels)); cfg.CreateMap<ParentModel, ParentDto>() .PreserveReferences() .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.ID)); cfg.CreateMap<ChildModel, ChildDto>(); }); protected override void Because_of() { _dto = Mapper.Map<ParentModel, ParentDto>(_parent); } [Fact] public void Should_preserve_the_parent_child_relationship_on_the_destination() { _dto.Children[0].Parent.ID.ShouldEqual(_dto.ID); } public class ChildIdToParentDtoConverter : ITypeConverter<int, ParentDto> { private readonly Dictionary<int, ParentModel> _parentModels; public ChildIdToParentDtoConverter(Dictionary<int, ParentModel> parentModels) { _parentModels = parentModels; } public ParentDto Convert(int source, ResolutionContext resolutionContext) { ParentModel parentModel = _parentModels[source]; return (ParentDto) resolutionContext.Mapper.Map(parentModel, null, typeof(ParentModel), typeof(ParentDto), resolutionContext); } } public class ParentIdToChildDtoListConverter : ITypeConverter<int, List<ChildDto>> { private readonly IList<ChildModel> _childModels; public ParentIdToChildDtoListConverter(IList<ChildModel> childModels) { _childModels = childModels; } public List<ChildDto> Convert(int source, ResolutionContext resolutionContext) { List<ChildModel> childModels = _childModels.Where(x => x.Parent.ID == source).ToList(); return (List<ChildDto>)resolutionContext.Mapper.Map(childModels, null, typeof(List<ChildModel>), typeof(List<ChildDto>), resolutionContext); } } public class ParentModel { public int ID { get; set; } } public class ChildModel { public int ID { get; set; } public ParentModel Parent { get; set; } } public class ParentDto { public int ID { get; set; } public List<ChildDto> Children { get; set; } } public class ChildDto { public int ID { get; set; } public ParentDto Parent { get; set; } } } public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_one_child_relationship : AutoMapperSpecBase { private FooDto _dto; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Foo, FooDto>().PreserveReferences(); cfg.CreateMap<Bar, BarDto>(); }); protected override void Because_of() { var foo = new Foo { Bar = new Bar { Value = "something" } }; foo.Bar.Foo = foo; _dto = Mapper.Map<Foo, FooDto>(foo); } [Fact] public void Should_preserve_the_parent_child_relationship_on_the_destination() { _dto.Bar.Foo.ShouldBeSameAs(_dto); } public class Foo { public Bar Bar { get; set; } } public class Bar { public Foo Foo { get; set; } public string Value { get; set; } } public class FooDto { public BarDto Bar { get; set; } } public class BarDto { public FooDto Foo { get; set; } public string Value { get; set; } } } public class When_mapping_to_a_destination_containing_two_dtos_mapped_from_the_same_source : AutoMapperSpecBase { private FooContainerModel _dto; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<FooModel, FooScreenModel>(); cfg.CreateMap<FooModel, FooInputModel>(); cfg.CreateMap<FooModel, FooContainerModel>() .PreserveReferences() .ForMember(dest => dest.Input, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Screen, opt => opt.MapFrom(src => src)); }); protected override void Because_of() { var model = new FooModel { Id = 3 }; _dto = Mapper.Map<FooModel, FooContainerModel>(model); } [Fact] public void Should_not_preserve_identity_when_destinations_are_incompatible() { _dto.ShouldBeType<FooContainerModel>(); _dto.Input.ShouldBeType<FooInputModel>(); _dto.Screen.ShouldBeType<FooScreenModel>(); _dto.Input.Id.ShouldEqual(3); _dto.Screen.Id.ShouldEqual("3"); } public class FooContainerModel { public FooInputModel Input { get; set; } public FooScreenModel Screen { get; set; } } public class FooScreenModel { public string Id { get; set; } } public class FooInputModel { public long Id { get; set; } } public class FooModel { public long Id { get; set; } } } public class When_mapping_with_a_bidirectional_relationship_that_includes_arrays : AutoMapperSpecBase { private ParentDto _dtoParent; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Parent, ParentDto>().PreserveReferences(); cfg.CreateMap<Child, ChildDto>(); }); protected override void Because_of() { var parent1 = new Parent { Name = "Parent 1" }; var child1 = new Child { Name = "Child 1" }; parent1.Children.Add(child1); child1.Parents.Add(parent1); _dtoParent = Mapper.Map<Parent, ParentDto>(parent1); } [Fact] public void Should_map_successfully() { object.ReferenceEquals(_dtoParent.Children[0].Parents[0], _dtoParent).ShouldBeTrue(); } public class Parent { public Guid Id { get; private set; } public string Name { get; set; } public List<Child> Children { get; set; } public Parent() { Id = Guid.NewGuid(); Children = new List<Child>(); } public bool Equals(Parent other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Id.Equals(Id); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Parent)) return false; return Equals((Parent) obj); } public override int GetHashCode() { return Id.GetHashCode(); } } public class Child { public Guid Id { get; private set; } public string Name { get; set; } public List<Parent> Parents { get; set; } public Child() { Id = Guid.NewGuid(); Parents = new List<Parent>(); } public bool Equals(Child other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Id.Equals(Id); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Child)) return false; return Equals((Child) obj); } public override int GetHashCode() { return Id.GetHashCode(); } } public class ParentDto { public Guid Id { get; set; } public string Name { get; set; } public List<ChildDto> Children { get; set; } public ParentDto() { Children = new List<ChildDto>(); } } public class ChildDto { public Guid Id { get; set; } public string Name { get; set; } public List<ParentDto> Parents { get; set; } public ChildDto() { Parents = new List<ParentDto>(); } } } } }
using NBitcoin; using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Web3.Accounts; using System; using Xunit; using Nethereum.Util; namespace Nethereum.HdWallet.UnitTests { //To validate use https://iancoleman.github.io/bip39/#english public class WalletTests { public const string Words = "ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal"; public const string Password = "TREZOR"; [Theory] [InlineData("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979")] [InlineData("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47")] [InlineData("0xA4267Fb4d2300e82E16441A740996d75402a2140")] [InlineData("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310")] [InlineData("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1")] [InlineData("0x9Fab8f2E3b4a9E514Ae27bDabA628E8E2840823B")] [InlineData("0xC876B10D76857eCaB086d75d59d6FEE28C48285c")] [InlineData("0xe2027d3Bc6a2507490eFc2b8397b464bFA47AA57")] [InlineData("0x584A9ac0491371F066c9cbbc795d0D1aD5d08267")] [InlineData("0x9e019Ee5D24132bddBBA857407667c0e3Ce82a90")] [InlineData("0x6bE280E6aD7F8fBd40b5Bf12e28dCbA87E328499")] [InlineData("0x2556f135C21A4FB2aeF401bA804666268e2fb4EC")] [InlineData("0x7c62c432D56d5eA704C9cEC73Af3Bb183EF8B952")] [InlineData("0x4c592d1A0BcA11eC447c56Fc7ee2858Bc3aDDe51")] [InlineData("0x2C3B76bF48275378041cA7dF9B8E6aA8c0664847")] [InlineData("0xeb8C5D6575C704A4bEcDd41a3592dF89389568E2")] [InlineData("0x94050231B601A6906C80BfEd468D8C32fa7792A7")] [InlineData("0x76933C9e4C1B635EaBB6F5273d4bd2DdFcc4379a")] [InlineData("0x7cFfb4E2fdF3F40c210b21A972E73Df1cC3806B3")] [InlineData("0xF07fB895F441C46264d1FABD6eb3C757A2E7f9e0")] public void ShouldFindAccountUsingAddress(string address) { var wallet = new Wallet(Words, Password); var account = wallet.GetAccount(address); Assert.NotNull(account); } [Theory] [InlineData("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", 0)] [InlineData("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", 1)] [InlineData("0xA4267Fb4d2300e82E16441A740996d75402a2140", 2)] [InlineData("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310", 3)] [InlineData("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1", 4)] [InlineData("0x9Fab8f2E3b4a9E514Ae27bDabA628E8E2840823B", 5)] [InlineData("0xC876B10D76857eCaB086d75d59d6FEE28C48285c", 6)] [InlineData("0xe2027d3Bc6a2507490eFc2b8397b464bFA47AA57", 7)] [InlineData("0x584A9ac0491371F066c9cbbc795d0D1aD5d08267", 8)] [InlineData("0x9e019Ee5D24132bddBBA857407667c0e3Ce82a90", 9)] [InlineData("0x6bE280E6aD7F8fBd40b5Bf12e28dCbA87E328499", 10)] [InlineData("0x2556f135C21A4FB2aeF401bA804666268e2fb4EC", 11)] [InlineData("0x7c62c432D56d5eA704C9cEC73Af3Bb183EF8B952", 12)] [InlineData("0x4c592d1A0BcA11eC447c56Fc7ee2858Bc3aDDe51", 13)] [InlineData("0x2C3B76bF48275378041cA7dF9B8E6aA8c0664847", 14)] [InlineData("0xeb8C5D6575C704A4bEcDd41a3592dF89389568E2", 15)] [InlineData("0x94050231B601A6906C80BfEd468D8C32fa7792A7", 16)] [InlineData("0x76933C9e4C1B635EaBB6F5273d4bd2DdFcc4379a", 17)] [InlineData("0x7cFfb4E2fdF3F40c210b21A972E73Df1cC3806B3", 18)] [InlineData("0xF07fB895F441C46264d1FABD6eb3C757A2E7f9e0", 19)] public void ShouldFindAccountUsingIndex(string address, int index) { var wallet = new Wallet(Words, Password); var account = wallet.GetAccount(index); Assert.Equal(address, account.Address); } [Theory] [InlineData("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", 0)] [InlineData("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", 1)] [InlineData("0xA4267Fb4d2300e82E16441A740996d75402a2140", 2)] [InlineData("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310", 3)] [InlineData("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1", 4)] [InlineData("0x9Fab8f2E3b4a9E514Ae27bDabA628E8E2840823B", 5)] [InlineData("0xC876B10D76857eCaB086d75d59d6FEE28C48285c", 6)] [InlineData("0xe2027d3Bc6a2507490eFc2b8397b464bFA47AA57", 7)] [InlineData("0x584A9ac0491371F066c9cbbc795d0D1aD5d08267", 8)] [InlineData("0x9e019Ee5D24132bddBBA857407667c0e3Ce82a90", 9)] [InlineData("0x6bE280E6aD7F8fBd40b5Bf12e28dCbA87E328499", 10)] [InlineData("0x2556f135C21A4FB2aeF401bA804666268e2fb4EC", 11)] [InlineData("0x7c62c432D56d5eA704C9cEC73Af3Bb183EF8B952", 12)] [InlineData("0x4c592d1A0BcA11eC447c56Fc7ee2858Bc3aDDe51", 13)] [InlineData("0x2C3B76bF48275378041cA7dF9B8E6aA8c0664847", 14)] [InlineData("0xeb8C5D6575C704A4bEcDd41a3592dF89389568E2", 15)] [InlineData("0x94050231B601A6906C80BfEd468D8C32fa7792A7", 16)] [InlineData("0x76933C9e4C1B635EaBB6F5273d4bd2DdFcc4379a", 17)] [InlineData("0x7cFfb4E2fdF3F40c210b21A972E73Df1cC3806B3", 18)] [InlineData("0xF07fB895F441C46264d1FABD6eb3C757A2E7f9e0", 19)] public void ShouldFindPublicKeysAccountUsingIndex(string address, int index) { var wallet = new Wallet(Words, Password); var publicWallet = wallet.GetMasterPublicWallet(); var account = publicWallet.GetAddress(index); Assert.Equal(address, account); } [Theory] [InlineData("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", 0)] [InlineData("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", 1)] [InlineData("0xA4267Fb4d2300e82E16441A740996d75402a2140", 2)] [InlineData("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310", 3)] [InlineData("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1", 4)] [InlineData("0x9Fab8f2E3b4a9E514Ae27bDabA628E8E2840823B", 5)] [InlineData("0xC876B10D76857eCaB086d75d59d6FEE28C48285c", 6)] [InlineData("0xe2027d3Bc6a2507490eFc2b8397b464bFA47AA57", 7)] [InlineData("0x584A9ac0491371F066c9cbbc795d0D1aD5d08267", 8)] [InlineData("0x9e019Ee5D24132bddBBA857407667c0e3Ce82a90", 9)] [InlineData("0x6bE280E6aD7F8fBd40b5Bf12e28dCbA87E328499", 10)] [InlineData("0x2556f135C21A4FB2aeF401bA804666268e2fb4EC", 11)] [InlineData("0x7c62c432D56d5eA704C9cEC73Af3Bb183EF8B952", 12)] [InlineData("0x4c592d1A0BcA11eC447c56Fc7ee2858Bc3aDDe51", 13)] [InlineData("0x2C3B76bF48275378041cA7dF9B8E6aA8c0664847", 14)] [InlineData("0xeb8C5D6575C704A4bEcDd41a3592dF89389568E2", 15)] [InlineData("0x94050231B601A6906C80BfEd468D8C32fa7792A7", 16)] [InlineData("0x76933C9e4C1B635EaBB6F5273d4bd2DdFcc4379a", 17)] [InlineData("0x7cFfb4E2fdF3F40c210b21A972E73Df1cC3806B3", 18)] [InlineData("0xF07fB895F441C46264d1FABD6eb3C757A2E7f9e0", 19)] public void ShouldFindPublicKeysAccountUsingIndexInitialisingWithPublicKey(string address, int index) { var wallet = new Wallet(Words, Password); var bytes = wallet.GetMasterExtPubKey().ToBytes(); var hex = bytes.ToHex(); Console.WriteLine(hex); var publicWallet = new PublicWallet(hex); var account = publicWallet.GetAddress(index); Assert.Equal(address, account); } [Theory] [InlineData("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", 0)] [InlineData("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", 1)] [InlineData("0xA4267Fb4d2300e82E16441A740996d75402a2140", 2)] [InlineData("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310", 3)] [InlineData("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1", 4)] [InlineData("0x9Fab8f2E3b4a9E514Ae27bDabA628E8E2840823B", 5)] [InlineData("0xC876B10D76857eCaB086d75d59d6FEE28C48285c", 6)] [InlineData("0xe2027d3Bc6a2507490eFc2b8397b464bFA47AA57", 7)] [InlineData("0x584A9ac0491371F066c9cbbc795d0D1aD5d08267", 8)] [InlineData("0x9e019Ee5D24132bddBBA857407667c0e3Ce82a90", 9)] [InlineData("0x6bE280E6aD7F8fBd40b5Bf12e28dCbA87E328499", 10)] [InlineData("0x2556f135C21A4FB2aeF401bA804666268e2fb4EC", 11)] [InlineData("0x7c62c432D56d5eA704C9cEC73Af3Bb183EF8B952", 12)] [InlineData("0x4c592d1A0BcA11eC447c56Fc7ee2858Bc3aDDe51", 13)] [InlineData("0x2C3B76bF48275378041cA7dF9B8E6aA8c0664847", 14)] [InlineData("0xeb8C5D6575C704A4bEcDd41a3592dF89389568E2", 15)] [InlineData("0x94050231B601A6906C80BfEd468D8C32fa7792A7", 16)] [InlineData("0x76933C9e4C1B635EaBB6F5273d4bd2DdFcc4379a", 17)] [InlineData("0x7cFfb4E2fdF3F40c210b21A972E73Df1cC3806B3", 18)] [InlineData("0xF07fB895F441C46264d1FABD6eb3C757A2E7f9e0", 19)] public void ShouldFindPublicKeysAccountUsingIndexInitialisingWithWif(string address, int index) { var wallet = new Wallet(Words, Password); var wif = wallet.GetMasterExtPubKey().GetWif(Network.Main).ToWif(); var extPubKey = ExtPubKey.Parse(wif, Network.Main); Console.WriteLine(wif); var publicWallet = new PublicWallet(extPubKey); var account = publicWallet.GetAddress(index); Assert.Equal(address, account); } [Theory] [InlineData("0xc4f77b4a9f5a0db3a7ffc3599e61bef986037ae9a7cc1972a10d55c030270020", 0)] [InlineData("0xb4ede783358d19073b53c7dab99c63265e5b5d863c133fa6ee7894c2ba53c2d8", 1)] [InlineData("0x8fe23ea66d3dcc6edf07c9a580f8026ea1c1ddd6774a923c2b30e9a44d8c11b5", 2)] [InlineData("0xd54936b42aa4e0604608fe8c2427ec1562b1e6fd0f3c1f1a56668ddb8aee99fb", 3)] [InlineData("0xd216a168a12c0a46d4b07b1b62cd55283d708de17dcfaf1be7c60fa31b91f180", 4)] [InlineData("0x27be39998ca88ca666ab33aa8e2def1da837a19d38e70f066e77132e13345e58", 5)] [InlineData("0x18a44a4891648f6455fe84e94cfacc1d8a9829b349499eef7653f3aff43b9b29", 6)] [InlineData("0xaf1a3b0ee759cc98a106eea3ed3af57ba8ceeecf1f6a050f1d6c0c36e2a4e0ee", 7)] [InlineData("0x993072842865e1db03605515a17a883e887db9bb12fead41c5391e535e22044c", 8)] [InlineData("0xd38a6a11873c939d87bf45b107ac66697ff241fa98ad5a09ff052ffdc58b42ff", 9)] [InlineData("0x02a1b9a345f52f216bf0dd2eabda542467825068b8d114a6cb9516ced16ad8ae", 10)] [InlineData("0xe48018a421e7d5100ace0d8df8064b32c4829e5490c33b5e2d49e39a72e2bc92", 11)] [InlineData("0x8bdb46ef9f2ff0fb021392c368b59a1188c77c12d6db561f154b869ecdd98731", 12)] [InlineData("0x9082bbac96a2720203b190db9c8618a8b33d6531302f29d677d95e48d96ce73c", 13)] [InlineData("0x4ed48e0e8320e002a928e8b84ba416823f3331177253879ec4524206bd52421b", 14)] [InlineData("0xe646377dc06e6b5846fa2584b98a60d7a11a24c42ed007b5ca0ba905cab9b0b2", 15)] [InlineData("0xe9458b547b02ad8d86c66454596269936325afb6c90c1d2fc5262bb3d0ebda6f", 16)] [InlineData("0x26abdeb81020564be9f79f590eaa5a730cf11aaf02b74d149858501322cc1baa", 17)] [InlineData("0x47b07eae780b300fa49d9a1a347df28ca35ddb3a41af2d796be32684f9b96136", 18)] [InlineData("0x3e9c766279c9f8e23fa03e170e41531566d1e77b338a756dc83348906d35ca8f", 19)] public void ShouldFindPrivateKeyUsingIndex(string privateKey, int index) { var wallet = new Wallet(Words, Password); var key = wallet.GetPrivateKey(index); Assert.Equal(privateKey, key.ToHex(true)); } [Fact] public void ShouldCreateTheDefaultWalletUsingGivenWords() { var wallet = new Wallet(Words, Password); Assert.Equal( "7ae6f661157bda6492f6162701e570097fc726b6235011ea5ad09bf04986731ed4d92bc43cbdee047b60ea0dd1b1fa4274377c9bf5bd14ab1982c272d8076f29", wallet.Seed); var account = wallet.GetAccount(0); Assert.Equal("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", account.Address); } [Fact] public void ShouldFindAddressesUsingGivenWords() { var wallet = new Wallet(Words, Password); var addresses = wallet.GetAddresses(5); Assert.Equal("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", addresses[0]); Assert.Equal("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", addresses[1]); Assert.Equal("0xA4267Fb4d2300e82E16441A740996d75402a2140", addresses[2]); Assert.Equal("0xD6D7a427d6fd40B4109ACD5a5AF455E7c02a3310", addresses[3]); Assert.Equal("0xd94C2F0Ae3E5cc074668a4D220801C0Ab96082E1", addresses[4]); } [Fact] public void ShouldMeeeeew() { var wallet = new Wallet("stem true medal chronic lion machine mask road rabbit process movie account", null, "m/44'/60'/0'/0'/x"); var account = wallet.GetAccount(0); Assert.True(account.Address.IsTheSameAddress("0xd9B924d064C8D0ECFf3307e929f5a941b6A56C2D")); } [Fact] public void ShouldAllowDeriviationSeed() { var mnemo = new Mnemonic("stem true medal chronic lion machine mask road rabbit process movie account", Wordlist.English); var seed = mnemo.DeriveSeed(); var ethWallet = new Wallet(seed); var account = new Account(ethWallet.GetPrivateKey(0)); account = ethWallet.GetAccount(account.Address); Assert.True(account.Address.IsTheSameAddress("0x03dd02C038e15fcFbBdc372c71D595BD241E0898")); } } }
//#define DEBUG using System; using System.Collections.Generic; using System.Text; namespace ICSimulator { public enum MemoryRequestType { RD, DAT, WB, } public class MemoryRequest { public Request request; public MemoryRequestType type; public int memoryRequesterID; //summary>LLC node</summary> public ulong timeOfArrival; public bool isMarked; public ulong creationTime; public int m_index; //summary>memory index pertaining to the block address</summary> public int b_index; //summary>bank index pertaining to the block address</summary> public ulong r_index; //summary>row index pertaining to the block address</summary> public int glob_b_index; //summary>global bank index (for central arbiter)</summary> //scheduling related public MemSched sched; //summary>the memory scheduler this request is destined to; determined by memory index</summary> public int buf_index; //summary>within the memory scheduler, this request's index in the buffer; saves the effort of searching through entire buffer</summary> //public int bufferSlot; // that is just an optimization that I don't need to search over the buffer anymore! public Simulator.Ready cb; // completion callback public static void mapAddr(ulong block, out int m_index, out int b_index, out ulong r_index, out int glob_b_index) { ulong shift_row; ulong shift_mem; ulong shift_bank; int groupID = (int)(block >> (48 - Config.cache_block)); switch (Config.memory.address_mapping) { case AddressMap.BMR: /** * row-level striping (inter-mem): default * RMS (BMR; really original) */ shift_row = block >> Config.memory.row_bit; m_index = (int)((shift_row ^ (ulong)groupID) % (ulong)Config.memory.mem_max); //Console.WriteLine("Common/Request.cs : m_index:{0}, groupID:{1}, mem_max:{2}", m_index, groupID, Config.memory.mem_max); shift_mem = (ulong)(shift_row >> Config.memory.mem_bit); b_index = (int)((shift_mem ^ (ulong)groupID) % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_mem >> Config.memory.bank_bit); break; case AddressMap.BRM: /** * block-level striping (inter-mem) * BMS (BRM; original) */ m_index = (int)(block % (ulong)Config.memory.mem_max); shift_mem = block >> Config.memory.mem_bit; shift_row = shift_mem >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_row >> Config.memory.bank_bit); break; case AddressMap.MBR: /** * row-level striping (inter-bank) * RBS (MBR; new) */ shift_row = block >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); shift_bank = (ulong)(shift_row >> Config.memory.bank_bit); m_index = (int)(shift_bank % (ulong)Config.memory.mem_max); r_index = (ulong)(shift_bank >> Config.memory.mem_bit); break; case AddressMap.MRB: /** * block-level striping (inter-bank) * BBS */ //Console.WriteLine(block.ToString("x")); b_index = (int)(block % (ulong)Config.memory.bank_max_per_mem); shift_bank = block >> Config.memory.bank_bit; shift_row = shift_bank >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); r_index = shift_row >> Config.memory.mem_bit; //Console.WriteLine("bmpm:{0} bb:{1} b:{2} m:{3} r:{4}", Config.memory.bank_max_per_mem, Config.memory.bank_bit, b_index.ToString("x"), m_index.ToString("x"), r_index.ToString("x")); break; default: throw new Exception("Unknown address map!"); } //central arbiter related if (Config.memory.is_shared_MC) { glob_b_index = m_index * Config.memory.bank_max_per_mem + b_index; } else { glob_b_index = b_index; } } public static int mapMC(ulong block) { int m, b, glob_b; ulong r; mapAddr(block, out m, out b, out r, out glob_b); return m; } public MemoryRequest(Request req, Simulator.Ready cb) { this.cb = cb; request = req; req.beenToMemory = true; mapAddr(req.blockAddress, out m_index, out b_index, out r_index, out glob_b_index); //scheduling related //sched = Config.memory.mem[m_index].sched; sched = null; isMarked = false; } } public class Request { /// <summary> Reasons for a request to be delayed, such as addr packet transmission, data packet injection, memory queueing, etc. </summary> public enum DelaySources { //TODO: this (with coherency awareness) UNKNOWN, COHERENCE, MEMORY, LACK_OF_MSHRS, ADDR_PACKET, DATA_PACKET, MC_ADDR_PACKET, MC_DATA_PACKET, INJ_ADDR_PACKET, INJ_DATA_PACKET, INJ_MC_ADDR_PACKET, INJ_MC_DATA_PACKET } public bool write { get { return _write; } } private bool _write; ulong _interferenceCycle; public ulong interferenceCycle { get { return _interferenceCycle; } set { _interferenceCycle = value; } } //ulong _issueTimeIntf; // the interference cycle at issue time public ulong blockAddress { get { return _address >> Config.cache_block; } } public ulong address { get { return _address; } } private ulong _address; public int requesterID { get { return _requesterID; } } private int _requesterID; public ulong creationTime { get { return _creationTime; } } private ulong _creationTime; public int mshr; /// <summary> Packet/MemoryRequest/CoherentDir.Entry on the critical path of the serving of this request. </summary> // e.g. the address packet, then data pack on the way back // or addr, mc_addr, mc_request, mc_data and then data // or upgrade(to dir), release(to owner), release_data(to dir), data_exclusive(to requestor) //object _carrier; public void setCarrier(object carrier) { // _carrier = carrier; } // Statistics gathering /// <summary> Records cycles spent in each portion of its path (see Request.TimeSources) </summary> //private ulong[] cyclesPerLocation; /// <summary> Record number of stalls caused by this request while it's the oldest in the inst window </summary> public double backStallsCaused; public Request(int requesterID, ulong address, bool write) { this._requesterID = requesterID; this._address = address; this._write = write; this._creationTime = Simulator.CurrentRound; } public Request(int requesterID, ulong address, bool write, ulong interference) { this._requesterID = requesterID; this._address = address; this._write = write; this._creationTime = Simulator.CurrentRound; //this._issueTimeIntf = (ulong)Simulator.stats.non_overlap_penalty[requesterID].Count; this._interferenceCycle = interference; //if (interference != 0) // Console.WriteLine("Req at {0} is issued with Init intf cycle {1} at TIME = {2}", requesterID, interference, Simulator.CurrentRound); } public override string ToString() { return String.Format("Request: address {0:X} (block {1:X}), write {2}, requestor {3}", _address, blockAddress, _write, _requesterID); } private ulong _serviceCycle = ulong.MaxValue; public void service() { if (_serviceCycle != ulong.MaxValue) throw new Exception("Retired request serviced twice!"); _serviceCycle = Simulator.CurrentRound; } public bool beenToNetwork = false; public bool beenToMemory = false; public ulong computePenalty(ulong last_retire, ulong max_intf_cycle){ // set ready first, and commit in the next cycle long slack = (long) (Simulator.CurrentRound - _serviceCycle - 1); //long slack = (long) (Simulator.CurrentRound - _serviceCycle); // using slack to determine what is the position in the ROB when the current insturction is set to ready. ulong intf_cycle = ulong.MaxValue; /* if (slack < 0) //intf_cycle = 0; // local L2 access has 0 interference cycle. It will be serviced intermediately upon issuing the request. throw new Exception("Impossible: service after commit!"); else if (slack > 0) // instruction is serviced earlier than it should, even with interference. So intf is hidden completely. */ if (slack != 0) intf_cycle = max_intf_cycle; else{ #if DEBUG //Console.WriteLine ("PENALTY: at node {0}, addr = {1}, _intf = {2}, time = {3} ", _requesterID, _address, _interferenceCycle, Simulator.CurrentRound); #endif ulong est_serviceCycle_no_intf = _serviceCycle - _interferenceCycle; ulong actual_intf_cycle; // goal: estimate when there is no interference, what is the time for retiring the current instruction if (est_serviceCycle_no_intf < last_retire) { actual_intf_cycle = _serviceCycle - last_retire; intf_cycle = Math.Min (max_intf_cycle, actual_intf_cycle); } else intf_cycle = Math.Min (max_intf_cycle, _interferenceCycle); #if DEBUG //Console.WriteLine ("PENALTY: at node {0}, _intf = {1}, time = {2} ", _requesterID, intf_cycle, Simulator.CurrentRound); #endif } return intf_cycle; } public void retire() { if (_serviceCycle == ulong.MaxValue) throw new Exception("Retired request never serviced!"); ulong slack = Simulator.CurrentRound - _serviceCycle; Simulator.stats.all_slack_persrc[requesterID].Add(slack); Simulator.stats.all_slack.Add(slack); Simulator.stats.all_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.all_stall.Add(backStallsCaused); if (beenToNetwork) { Simulator.stats.net_slack_persrc[requesterID].Add(slack); Simulator.stats.net_slack.Add(slack); Simulator.stats.net_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.net_stall.Add(backStallsCaused); } if (beenToMemory) { Simulator.stats.mem_slack_persrc[requesterID].Add(slack); Simulator.stats.mem_slack.Add(slack); Simulator.stats.mem_stall_persrc[requesterID].Add(backStallsCaused); Simulator.stats.mem_stall.Add(backStallsCaused); } if (beenToNetwork) { Simulator.stats.req_rtt.Add(_serviceCycle - _creationTime); } } } //For reference: public enum OldInstructionType { Read, Write }; public class OldRequest { public ulong blockAddress; public ulong timeOfArrival; public int threadID; public bool isMarked; public OldInstructionType type; public ulong associatedAddressPacketInjectionTime; public ulong associatedAddressPacketCreationTime; public Packet carrier; // this is the packet which is currently moving the request through the system //members copied from Req class of FairMemSim for use in MCs public int m_index; ///<memory index pertaining to the block address public int b_index; ///<bank index pertaining to the block address public ulong r_index; ///<row index pertaining to the block address public int glob_b_index; ///<global bank index (for central arbiter) //scheduling related public MemSched sched; ///<the memory scheduler this request is destined to; determined by memory index public int buf_index; ///<within the memory scheduler, this request's index in the buffer; saves the effort of searching through entire buffer public int bufferSlot; // that is just an optimization that I don't need to search over the buffer anymore! private double frontStallsCaused; private double backStallsCaused; private ulong[] locationCycles; // record how many cycles spent in each Request.TimeSources location public OldRequest() { isMarked = false; } public override string ToString() { return "Request: ProcID=" + threadID + " IsMarked=" + isMarked + /*" Bank=" + bankIndex.ToString() + " Row=" + rowIndex.ToString() + */" Block=" + (blockAddress).ToString() + " " + type.ToString(); } public void initialize(ulong blockAddress) { this.blockAddress = blockAddress; frontStallsCaused = 0; backStallsCaused = 0; locationCycles = new ulong[Enum.GetValues(typeof(Request.DelaySources)).Length]; if (Config.PerfectLastLevelCache) return; ulong shift_row; ulong shift_mem; ulong shift_bank; switch (Config.memory.address_mapping) { case AddressMap.BMR: /** * row-level striping (inter-mem): default * RMS (BMR; really original) */ shift_row = blockAddress >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); shift_mem = (ulong)(shift_row >> Config.memory.mem_bit); b_index = (int)(shift_mem % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_mem >> Config.memory.bank_bit); break; case AddressMap.BRM: /** * block-level striping (inter-mem) * BMS (BRM; original) */ m_index = (int)(blockAddress % (ulong)Config.memory.mem_max); shift_mem = blockAddress >> Config.memory.mem_bit; shift_row = shift_mem >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); r_index = (ulong)(shift_row >> Config.memory.bank_bit); break; case AddressMap.MBR: /** * row-level striping (inter-bank) * RBS (MBR; new) */ shift_row = blockAddress >> Config.memory.row_bit; b_index = (int)(shift_row % (ulong)Config.memory.bank_max_per_mem); shift_bank = (ulong)(shift_row >> Config.memory.bank_bit); m_index = (int)(shift_bank % (ulong)Config.memory.mem_max); r_index = (ulong)(shift_bank >> Config.memory.mem_bit); break; case AddressMap.MRB: /** * block-level striping (inter-bank) * BBS */ //Console.WriteLine(blockAddress.ToString("x")); b_index = (int)(blockAddress % (ulong)Config.memory.bank_max_per_mem); shift_bank = blockAddress >> Config.memory.bank_bit; shift_row = shift_bank >> Config.memory.row_bit; m_index = (int)(shift_row % (ulong)Config.memory.mem_max); r_index = shift_row >> Config.memory.mem_bit; //Console.WriteLine("bmpm:{0} bb:{1} b:{2} m:{3} r:{4}", Config.memory.bank_max_per_mem, Config.memory.bank_bit, b_index.ToString("x"), m_index.ToString("x"), r_index.ToString("x")); break; default: throw new Exception("Unknown address map!"); } //scheduling related //sched = Config.memory.mem[m_index].sched; sched = null; isMarked = false; glob_b_index = b_index; } public void blameFrontStall(double weight) { frontStallsCaused += weight; } public void blameBackStall(double weight) { backStallsCaused += weight; } /* public void blameCycle() { Request.DelaySources staller = Request.DelaySources.UNKNOWN; if (carrier.GetType() == typeof(MemoryRequest)) staller = Request.DelaySources.MEMORY; else if (carrier.GetType() == typeof(Packet)) { bool injected = ((Packet)carrier).injectionTime != ulong.MaxValue; if (carrier.GetType() == typeof(CachePacket)) { CachePacket carrierPacket = (CachePacket)carrier; switch (carrierPacket.type) { case CachePacketType.RD: staller = injected ? Request.DelaySources.ADDR_PACKET : Request.DelaySources.INJ_ADDR_PACKET; break; case CachePacketType.DAT_EX: case CachePacketType.DAT_SHR: staller = injected ? Request.DelaySources.DATA_PACKET : Request.DelaySources.INJ_DATA_PACKET; break; default: throw new Exception("Unsupported packet type carrying request"); } } else if (carrier.GetType() == typeof(MemoryPacket)) { MemoryPacket carrierPacket = (MemoryPacket)carrier; switch (carrierPacket.type) { case MemoryRequestType.RD: if (m_index == int.MaxValue) { staller = Request.DelaySources.MEMORY; break; } staller = injected ? Request.DelaySources.MC_ADDR_PACKET : Request.DelaySources.INJ_MC_ADDR_PACKET; break; case MemoryRequestType.DAT: staller = injected ? Request.DelaySources.MC_DATA_PACKET : Request.DelaySources.INJ_MC_DATA_PACKET; break; default: throw new Exception("Unsupported packet type carrying request"); } } else { //unknown! staller = Request.DelaySources.UNKNOWN; } locationCycles[(int)staller]++; } } */ public void storeStats() { double sum = 0; foreach (double d in locationCycles) sum += d; for (int i = 0; i < locationCycles.Length; i++) { //Simulator.stats.front_stalls_persrc[threadID].Add(i, frontStallsCaused * locationCycles[i] / sum); //Simulator.stats.back_stalls_persrc[threadID].Add(i, backStallsCaused * locationCycles[i] / sum); } } } }
using System; using System.Collections.Generic; using System.Web.Routing; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Plugins; using Nop.Plugin.Payments.PurchaseOrder.Controllers; using Nop.Services.Configuration; using Nop.Services.Localization; using Nop.Services.Orders; using Nop.Services.Payments; namespace Nop.Plugin.Payments.PurchaseOrder { /// <summary> /// PurchaseOrder payment processor /// </summary> public class PurchaseOrderPaymentProcessor : BasePlugin, IPaymentMethod { #region Fields private readonly PurchaseOrderPaymentSettings _purchaseOrderPaymentSettings; private readonly ISettingService _settingService; private readonly IOrderTotalCalculationService _orderTotalCalculationService; #endregion #region Ctor public PurchaseOrderPaymentProcessor(PurchaseOrderPaymentSettings purchaseOrderPaymentSettings, ISettingService settingService, IOrderTotalCalculationService orderTotalCalculationService) { this._purchaseOrderPaymentSettings = purchaseOrderPaymentSettings; this._settingService = settingService; this._orderTotalCalculationService = orderTotalCalculationService; } #endregion #region Methods /// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.NewPaymentStatus = PaymentStatus.Pending; return result; } /// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { //nothing } /// <summary> /// Returns a value indicating whether payment method should be hidden during checkout /// </summary> /// <param name="cart">Shoping cart</param> /// <returns>true - hide; false - display.</returns> public bool HidePaymentMethod(IList<ShoppingCartItem> cart) { //you can put any logic here //for example, hide this payment method if all products in the cart are downloadable //or hide this payment method if current customer is from certain country if (_purchaseOrderPaymentSettings.ShippableProductRequired && !cart.RequiresShipping()) return true; return false; } /// <summary> /// Gets additional handling fee /// </summary> /// <param name="cart">Shoping cart</param> /// <returns>Additional handling fee</returns> public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart) { var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart, _purchaseOrderPaymentSettings.AdditionalFee, _purchaseOrderPaymentSettings.AdditionalFeePercentage); return result; } /// <summary> /// Captures payment /// </summary> /// <param name="capturePaymentRequest">Capture payment request</param> /// <returns>Capture payment result</returns> public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest) { var result = new CapturePaymentResult(); result.AddError("Capture method not supported"); return result; } /// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); result.AddError("Refund method not supported"); return result; } /// <summary> /// Voids a payment /// </summary> /// <param name="voidPaymentRequest">Request</param> /// <returns>Result</returns> public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest) { var result = new VoidPaymentResult(); result.AddError("Void method not supported"); return result; } /// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.AddError("Recurring payment not supported"); return result; } /// <summary> /// Cancels a recurring payment /// </summary> /// <param name="cancelPaymentRequest">Request</param> /// <returns>Result</returns> public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest) { var result = new CancelRecurringPaymentResult(); result.AddError("Recurring payment not supported"); return result; } /// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //it's not a redirection payment method. So we always return false return false; } /// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "PaymentPurchaseOrder"; routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } }; } /// <summary> /// Gets a route for payment info /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "PaymentInfo"; controllerName = "PaymentPurchaseOrder"; routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } }; } public Type GetControllerType() { return typeof(PaymentPurchaseOrderController); } /// <summary> /// Install plugin /// </summary> public override void Install() { //settings var settings = new PurchaseOrderPaymentSettings { AdditionalFee = 0, }; _settingService.SaveSetting(settings); //locales this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber", "PO Number"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee", "Additional fee"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint", "The additional fee."); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage", "Additional fee. Use percentage"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used."); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired", "Shippable product required"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired.Hint", "An option indicating whether shippable products are required in order to display this payment method during checkout."); base.Install(); } public override void Uninstall() { //settings _settingService.DeleteSetting<PurchaseOrderPaymentSettings>(); //locales this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired.Hint"); base.Uninstall(); } #endregion #region Properties /// <summary> /// Gets a value indicating whether capture is supported /// </summary> public bool SupportCapture { get { return false; } } /// <summary> /// Gets a value indicating whether partial refund is supported /// </summary> public bool SupportPartiallyRefund { get { return false; } } /// <summary> /// Gets a value indicating whether refund is supported /// </summary> public bool SupportRefund { get { return false; } } /// <summary> /// Gets a value indicating whether void is supported /// </summary> public bool SupportVoid { get { return false; } } /// <summary> /// Gets a recurring payment type of payment method /// </summary> public RecurringPaymentType RecurringPaymentType { get { return RecurringPaymentType.NotSupported; } } /// <summary> /// Gets a payment method type /// </summary> public PaymentMethodType PaymentMethodType { get { return PaymentMethodType.Standard; } } /// <summary> /// Gets a value indicating whether we should display a payment information page for this plugin /// </summary> public bool SkipPaymentInfo { get { return false; } } #endregion } }
using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace CSScripting { class Directives { public const string compiler = "//css_engine"; public const string compiler_csc = "csc"; public const string compiler_csc_inproc = "csc-inproc"; public const string compiler_dotnet = "dotnet"; public const string compiler_roslyn = "roslyn"; public const string compiler_roslyn_inproc = "roslyn-inproc"; } /// <summary> /// Various Reflection extensions for implementing assembly unloading /// </summary> public static class AssemblyUnloadingExtensions { /// <summary> /// Retrieves <see cref="AssemblyLoadContext"/> associated with the assembly and unloads it. /// <para>It will throw an exception if the <see cref="AssemblyLoadContext"/> is not created as /// unloadable ('IsCollectible').</para> /// <para>Use <see cref="CSScriptLib.IEvaluator.IsAssemblyUnloadingEnabled"/> to control /// how the assemblies (compiled scripts) are loaded.</para> /// <para> /// Note, unloading of assembly is implemented by CLR not CS-Script. This method extension is simply /// redirecting the call to the .NET <see cref="System.Runtime.Loader.AssemblyLoadContext.Unload"/> /// . Thus it is subject of the /// underlying limitations. Thus an AssemblyLoadContext can only be unloaded if it is collectible. And /// Unloading will occur asynchronously. /// </para> /// <para> /// Note, using 'dynamic` completely breaks CLR unloading mechanism. Most likely it triggers /// an accidental referencing of the assembly or <see /// cref="System.Runtime.Loader.AssemblyLoadContext"/>. Meaning that if you are planing to /// use assembly unloading you need to use interface based scripting. See `Test_Unloading` /// (https://github.com/oleg-shilo/cs-script/blob/master/src/CSScriptLib/src/Client.NET-Core/Program.cs) /// sample for details. /// </para> /// </summary> /// <param name="asm"></param> public static void Unload(this Assembly asm) { dynamic context = AssemblyLoadContext.GetLoadContext(asm); try { context.Unload(); } catch (System.InvalidOperationException e) { var error = IsUnloadingSupported ? "The problem may be caused by the assembly loaded with non-collectible `AssemblyLoadContext` (default CLR behavior)." : "Your runtime version may not support unloading assemblies. The host application needs to target .NET 5 and higher."; throw new NotImplementedException(error, e); } } #if class_lib static ConstructorInfo AssemblyLoadContextConstructor = typeof(AssemblyLoadContext).GetConstructor(new Type[] { typeof(string), typeof(bool) }); static bool IsUnloadingSupported = AssemblyLoadContextConstructor != null; static AssemblyUnloadingExtensions() { if (IsUnloadingSupported) CSScriptLib.Runtime.CreateUnloadableAssemblyLoadContext = () => (AssemblyLoadContext)AssemblyLoadContextConstructor.Invoke(new object[] { Guid.NewGuid().ToString(), true }); } #else static bool IsUnloadingSupported = false; #endif internal static Assembly LoadCollectableAssemblyFrom(this AppDomain appDomain, string assembly) { #if !class_lib return Assembly.LoadFrom(assembly); #else if (CSScriptLib.Runtime.CreateUnloadableAssemblyLoadContext == null) return Assembly.LoadFrom(assembly); else return CSScriptLib.Runtime.CreateUnloadableAssemblyLoadContext() .LoadFromAssemblyPath(assembly); #endif } internal static Assembly LoadCollectableAssembly(this AppDomain appDomain, byte[] assembly, byte[] assemblySymbols = null) { Assembly asm = null; Assembly legacy_load() => (assemblySymbols != null) ? appDomain.Load(assembly, assemblySymbols) : appDomain.Load(assembly); #if !class_lib asm = legacy_load(); #else if (CSScriptLib.Runtime.CreateUnloadableAssemblyLoadContext == null) { asm = legacy_load(); } else { using (var stream = new MemoryStream(assembly)) { var context = CSScriptLib.Runtime.CreateUnloadableAssemblyLoadContext(); if (assemblySymbols != null) { using (var symbols = new MemoryStream(assemblySymbols)) asm = context.LoadFromStream(stream, symbols); } else { asm = context.LoadFromStream(stream); } } } #endif return asm; } } /// <summary> /// Various Reflection extensions /// </summary> public static class ReflectionExtensions { /// <summary> /// Returns directory where the specified assembly file is. /// </summary> /// <param name="asm">The asm.</param> /// <returns>The directory path</returns> public static string Directory(this Assembly asm) { var file = asm.Location(); if (file.IsNotEmpty()) return Path.GetDirectoryName(file); else return ""; } /// <summary> /// Returns location of the specified assembly. Avoids throwing an exception in case /// of dynamic assembly. /// </summary> /// <param name="asm">The asm.</param> /// <returns>The path to the assembly file</returns> public static string Location(this Assembly asm) { if (asm.IsDynamic()) { string location = Environment.GetEnvironmentVariable("location:" + asm.GetHashCode()); if (location == null) { // Note assembly can contain only single AssemblyDescriptionAttribute var locationFromDescAttr = asm .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), true)? .Cast<AssemblyDescriptionAttribute>() .FirstOrDefault()? .Description; if (locationFromDescAttr.FileExists()) return locationFromDescAttr; #pragma warning disable SYSLIB0012 var validPath = asm.CodeBase?.FromUriToPath(); #pragma warning restore SYSLIB0012 if (validPath.FileExists()) return validPath; return ""; } else return location; } else return asm.Location; } internal static string FromUriToPath(this string uri) => new Uri(uri).LocalPath; /// <summary> /// Gets the name of the type. /// </summary> /// <param name="type">The type.</param> /// <returns>Thew name of the type.</returns> public static string GetName(this Type type) { return type.GetTypeInfo().Name; } /// <summary> /// Creates instance of a class from underlying assembly. /// </summary> /// <param name="asm">The asm.</param> /// <param name="typeName">The 'Type' full name of the type to create. (see Assembly.CreateInstance()). /// You can use wild card meaning the first type found. However only full wild card "*" is supported.</param> /// <param name="args">The non default constructor arguments.</param> /// <returns> /// Instance of the 'Type'. Throws an ApplicationException if the instance cannot be created. /// </returns> public static object CreateObject(this Assembly asm, string typeName, params object[] args) { return CreateInstance(asm, typeName, args); } /// <summary> /// Creates instance of a Type from underlying assembly. /// </summary> /// <param name="asm">The asm.</param> /// <param name="typeName">Name of the type to be instantiated. Allows wild card character (e.g. *.MyClass can be used to instantiate MyNamespace.MyClass).</param> /// <param name="args">The non default constructor arguments.</param> /// <returns> /// Created instance of the type. /// </returns> /// <exception cref="System.Exception">Type " + typeName + " cannot be found.</exception> private static object CreateInstance(Assembly asm, string typeName, params object[] args) { //note typeName for FindTypes does not include namespace if (typeName == "*") { //instantiate the user first type found (but not auto-generated types) //Ignore Roslyn internal root type: "Submission#0"; real script class will be Submission#0+Script var firstUserTypes = asm.OrderedUserTypes() .FirstOrDefault(); if (firstUserTypes != null) return Activator.CreateInstance(firstUserTypes, args); return null; } else { var name = typeName.Replace("*.", ""); Type[] types = asm.OrderedUserTypes() .Where(t => (t.FullName == name || t.FullName == ($"{Globals.RootClassName}+{name}") || t.Name == name)) .ToArray(); if (types.Length == 0) throw new Exception("Type " + typeName + " cannot be found."); return Activator.CreateInstance(types.First(), args); } } static bool IsRoslynInternalType(this Type type) => type.FullName.Contains("<<Initialize>>"); // Submission#0+<<Initialize>>d__0 static bool IsScriptRootClass(this Type type) => type.FullName.Contains($"{Globals.RootClassName}+"); // Submission#0+Script internal static IEnumerable<Type> OrderedUserTypes(this Assembly asm) => asm.ExportedTypes .Where(t => !t.IsRoslynInternalType()) .OrderBy(t => !t.IsScriptRootClass()); // ScriptRootClass will be on top internal static Type FirstUserTypeAssignableFrom<T>(this Assembly asm) => asm.OrderedUserTypes().FirstOrDefault(x => typeof(T).IsAssignableFrom(x)); /// <summary> /// Determines whether the assembly is dynamic. /// </summary> /// <param name="asm">The asm.</param> /// <returns> /// <c>true</c> if the specified asm is dynamic; otherwise, <c>false</c>. /// </returns> public static bool IsDynamic(this Assembly asm) { try { //http://bloggingabout.net/blogs/vagif/archive/2010/07/02/net-4-0-and-notsupportedexception-complaining-about-dynamic-assemblies.aspx //Will cover both System.Reflection.Emit.AssemblyBuilder and System.Reflection.Emit.InternalAssemblyBuilder return asm.GetType().FullName.EndsWith("AssemblyBuilder") || asm.Location == null || asm.Location == ""; } catch { return false; } } } }
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 dks3Api.Areas.HelpPage.ModelDescriptions; using dks3Api.Areas.HelpPage.Models; namespace dks3Api.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); } } } }
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace UnityTest { [Serializable] public partial class UnitTestView : EditorWindow { private static UnitTestView Instance; private static IUnitTestEngine testEngine = new NUnitTestEngine (); [SerializeField] private List<UnitTestResult> resultList = new List<UnitTestResult> (); [SerializeField] private string[] availableCategories = null; [SerializeField] private List<string> foldMarkers = new List<string> (); [SerializeField] private List<UnitTestRendererLine> selectedLines = new List<UnitTestRendererLine> (); UnitTestRendererLine testLines; #region runner steering vars private Vector2 testListScroll, testInfoScroll; private float horizontalSplitBarPosition = 200; private float verticalSplitBarPosition = 300; #endregion private UnitTestsRunnerSettings settings; #region GUI Contents private readonly GUIContent guiRunSelectedTestsIcon = new GUIContent (Icons.runImg, "Run selected tests"); private readonly GUIContent guiRunAllTestsIcon = new GUIContent (Icons.runAllImg, "Run all tests"); private readonly GUIContent guiRerunFailedTestsIcon = new GUIContent (Icons.runFailedImg, "Rerun failed tests"); private readonly GUIContent guiOptionButton = new GUIContent ("Options", Icons.gearImg); private readonly GUIContent guiHideButton = new GUIContent ("Hide", Icons.gearImg); private readonly GUIContent guiRunOnRecompile = new GUIContent ("Run on recompile", "Run all tests after recompilation"); private readonly GUIContent guiShowDetailsBelowTests = new GUIContent ("Show details below tests", "Show run details below test list"); private readonly GUIContent guiRunTestsOnNewScene = new GUIContent ("Run tests on a new scene", "Run tests on a new scene"); private readonly GUIContent guiAutoSaveSceneBeforeRun = new GUIContent ("Autosave scene", "The runner will automaticall save current scene changes before it starts"); private readonly GUIContent guiShowSucceededTests = new GUIContent ("Succeeded", Icons.successImg, "Show tests that succeeded"); private readonly GUIContent guiShowFailedTests = new GUIContent ("Failed", Icons.failImg, "Show tests that failed"); private readonly GUIContent guiShowIgnoredTests = new GUIContent ("Ignored", Icons.ignoreImg, "Show tests that are ignored"); private readonly GUIContent guiShowNotRunTests = new GUIContent ("Not Run", Icons.unknownImg, "Show tests that didn't run"); #endregion public UnitTestView () { title = "Unit Tests Runner"; resultList.Clear (); } public void OnEnable () { Instance = this; settings = ProjectSettingsBase.Load<UnitTestsRunnerSettings> (); RefreshTests (); EnableBackgroundRunner (settings.runOnRecompilation); } public void OnDestroy () { Instance = null; EnableBackgroundRunner (false); } public void Awake () { RefreshTests (); } public void OnGUI () { GUILayout.Space (10); EditorGUILayout.BeginVertical (); EditorGUILayout.BeginHorizontal (); var layoutOptions = new[] { GUILayout.Width(32), GUILayout.Height(24) }; if (GUILayout.Button (guiRunAllTestsIcon, Styles.buttonLeft, layoutOptions)) { RunTests(); GUIUtility.ExitGUI (); } if (GUILayout.Button (guiRunSelectedTestsIcon, Styles.buttonMid, layoutOptions)) { testLines.RunSelectedTests (); } if (GUILayout.Button (guiRerunFailedTestsIcon, Styles.buttonRight, layoutOptions)) { testLines.RunTests (resultList.Where(result => result.IsFailure || result.IsError).Select (l => l.FullName).ToArray ()); } GUILayout.FlexibleSpace (); if (GUILayout.Button (settings.optionsFoldout ? guiHideButton : guiOptionButton, GUILayout.Height (24), GUILayout.Width (80))) { settings.optionsFoldout = !settings.optionsFoldout; } EditorGUILayout.EndHorizontal (); if (settings.optionsFoldout) DrawOptions (); EditorGUILayout.BeginHorizontal (); EditorGUILayout.LabelField("Filter:", GUILayout.Width(35)); settings.testFilter = EditorGUILayout.TextField (settings.testFilter, EditorStyles.textField); if (availableCategories != null && availableCategories.Length > 1) settings.categoriesMask = EditorGUILayout.MaskField (settings.categoriesMask, availableCategories, GUILayout.MaxWidth (90)); if (GUILayout.Button (settings.filtersFoldout ? "Hide" : "Advanced", GUILayout.Width (80), GUILayout.Height (15))) settings.filtersFoldout = !settings.filtersFoldout; EditorGUILayout.EndHorizontal (); if (settings.filtersFoldout) DrawFilters (); if (settings.horizontalSplit) EditorGUILayout.BeginVertical (); else EditorGUILayout.BeginHorizontal (GUILayout.ExpandWidth (true)); RenderTestList (); RenderTestInfo (); if (settings.horizontalSplit) EditorGUILayout.EndVertical (); else EditorGUILayout.EndHorizontal (); EditorGUILayout.EndVertical (); } private string[] GetSelectedCategories () { var selectedCategories = new List<string> (); foreach (var availableCategory in availableCategories) { var idx = Array.FindIndex (availableCategories, ( a ) => a == availableCategory); var mask = 1 << idx; if ((settings.categoriesMask & mask) != 0) selectedCategories.Add (availableCategory); } return selectedCategories.ToArray (); } private void RenderTestList () { EditorGUILayout.BeginVertical (Styles.testList); testListScroll = EditorGUILayout.BeginScrollView (testListScroll, GUILayout.ExpandWidth (true), GUILayout.MaxWidth (2000)); if (testLines != null) { var options = new RenderingOptions (); options.showSucceeded = settings.showSucceeded; options.showFailed = settings.showFailed; options.showIgnored = settings.showIgnored; options.showNotRunned = settings.showNotRun; options.nameFilter = settings.testFilter; options.categories = GetSelectedCategories (); if (testLines.Render (options)) Repaint (); } EditorGUILayout.EndScrollView (); EditorGUILayout.EndVertical (); } private void RenderTestInfo () { var ctrlId = EditorGUIUtility.GetControlID (FocusType.Passive); var rect = GUILayoutUtility.GetLastRect (); if (settings.horizontalSplit) { rect.y = rect.height + rect.y - 1; rect.height = 3; } else { rect.x = rect.width + rect.x - 1; rect.width = 3; } EditorGUIUtility.AddCursorRect (rect, settings.horizontalSplit ? MouseCursor.ResizeVertical : MouseCursor.ResizeHorizontal); var e = Event.current; switch (e.type) { case EventType.MouseDown: if (EditorGUIUtility.hotControl == 0 && rect.Contains (e.mousePosition)) EditorGUIUtility.hotControl = ctrlId; break; case EventType.MouseDrag: if (EditorGUIUtility.hotControl == ctrlId) { horizontalSplitBarPosition -= e.delta.y; if (horizontalSplitBarPosition < 20) horizontalSplitBarPosition = 20; verticalSplitBarPosition -= e.delta.x; if (verticalSplitBarPosition < 20) verticalSplitBarPosition = 20; Repaint (); } break; case EventType.MouseUp: if (EditorGUIUtility.hotControl == ctrlId) EditorGUIUtility.hotControl = 0; break; } testInfoScroll = EditorGUILayout.BeginScrollView (testInfoScroll, settings.horizontalSplit ? GUILayout.MinHeight (horizontalSplitBarPosition) : GUILayout.Width (verticalSplitBarPosition)); var text = ""; if (selectedLines.Any ()) { text = selectedLines.First ().GetResultText (); } EditorGUILayout.TextArea (text, Styles.info); EditorGUILayout.EndScrollView (); } private void DrawFilters () { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal (); settings.showSucceeded = GUILayout.Toggle (settings.showSucceeded, guiShowSucceededTests, GUI.skin.FindStyle (GUI.skin.button.name + "left"), GUILayout.ExpandWidth (true)); settings.showFailed = GUILayout.Toggle (settings.showFailed, guiShowFailedTests, GUI.skin.FindStyle (GUI.skin.button.name + "mid")); settings.showIgnored = GUILayout.Toggle (settings.showIgnored, guiShowIgnoredTests, GUI.skin.FindStyle (GUI.skin.button.name + "mid")); settings.showNotRun = GUILayout.Toggle (settings.showNotRun, guiShowNotRunTests, GUI.skin.FindStyle (GUI.skin.button.name + "right"), GUILayout.ExpandWidth (true)); EditorGUILayout.EndHorizontal (); if (EditorGUI.EndChangeCheck()) settings.Save (); } private void DrawOptions () { EditorGUI.BeginChangeCheck (); EditorGUI.BeginChangeCheck (); settings.runOnRecompilation = EditorGUILayout.Toggle (guiRunOnRecompile, settings.runOnRecompilation); if (EditorGUI.EndChangeCheck ()) EnableBackgroundRunner (settings.runOnRecompilation); settings.runTestOnANewScene = EditorGUILayout.Toggle (guiRunTestsOnNewScene, settings.runTestOnANewScene); EditorGUI.BeginDisabledGroup (!settings.runTestOnANewScene); settings.autoSaveSceneBeforeRun = EditorGUILayout.Toggle (guiAutoSaveSceneBeforeRun, settings.autoSaveSceneBeforeRun); EditorGUI.EndDisabledGroup (); settings.horizontalSplit = EditorGUILayout.Toggle (guiShowDetailsBelowTests, settings.horizontalSplit); if (EditorGUI.EndChangeCheck ()) { settings.Save (); } EditorGUILayout.Space (); } private void RefreshTests () { UnitTestResult[] newResults; testLines = testEngine.GetTests (out newResults, out availableCategories); foreach (var newResult in newResults) { var result = resultList.Where (t => t.Test == newResult.Test && t.FullName == newResult.FullName).ToArray(); if (result.Count () != 1) continue; newResult.Update(result.Single(), true); } UnitTestRendererLine.SelectedLines = selectedLines; UnitTestRendererLine.RunTest = RunTests; GroupLine.FoldMarkers = foldMarkers; TestLine.GetUnitTestResult = FindTestResult; resultList = new List<UnitTestResult> (newResults); Repaint (); } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Text.RegularExpressions; namespace Equation { public class ExpressionCalculator { private class FunctionOrOperation { public FunctionOrOperation() { Parameters = 2; } internal string Term { get; set; } internal int Precedence { get; set; } internal string StopCondition { get; set; } internal Func<List<double>, double> Calc { get; set; } internal int Parameters { get; set; } internal AssociationEnum Association { get; set; } internal ContextEnum Context { get; set; } internal enum AssociationEnum { LEFT_TO_RIGHT, RIGHT_TO_LEFT } [Flags] internal enum ContextEnum { NONE = 1, STACK = 2, POP = 4 } public override string ToString() { return string.Format("[FunctionOrOperation: Term={0}, Context={1}, Association={2}]" , Term, Context, Association); } } public ExpressionCalculator(bool debug = false) { DEBUG = debug; _constants.Add("E", () => Math.E); _constants.Add("PI", () => Math.PI); _constants.Add("RAD", () => 180.0 / Math.PI); #region Brackets // left parenthesis _functionsOrOperations.Add(new FunctionOrOperation() { Term = "(", Precedence = 1000, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK | FunctionOrOperation.ContextEnum.NONE, }); // right parenthesis _functionsOrOperations.Add(new FunctionOrOperation() { Term = ")", Precedence = 1000, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.POP, StopCondition = "(" }); #endregion // division _functionsOrOperations.Add(new FunctionOrOperation() { Term = "/", Precedence = 100, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => arg[1] / arg[0] }); // multiplication _functionsOrOperations.Add(new FunctionOrOperation() { Term = "*", Precedence = 100, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => arg[0] * arg[1] }); /// addition _functionsOrOperations.Add(new FunctionOrOperation() { Term = "+", Precedence = 50, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => arg[0] + arg[1] }); /// subtraction _functionsOrOperations.Add(new FunctionOrOperation() { Term = "-", Precedence = 50, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => arg[1] - arg[0] }); /// power _functionsOrOperations.Add(new FunctionOrOperation() { Term = "^", Precedence = 100, Association = FunctionOrOperation.AssociationEnum.RIGHT_TO_LEFT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => Math.Pow(arg[1], arg[0]) }); // square root _functionsOrOperations.Add(new FunctionOrOperation() { Term = "SQRT", Precedence = 100, Association = FunctionOrOperation.AssociationEnum.RIGHT_TO_LEFT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => Math.Sqrt(arg[0]), Parameters = 1 }); // _functionsOrOperations.Add(new FunctionOrOperation() { Term = "ABS", Precedence = 110, Association = FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT, Context = FunctionOrOperation.ContextEnum.STACK, Calc = (List<double> arg) => Math.Abs(arg[0]), Parameters = 1 }); } Dictionary<string, Func<double>> _constants = new Dictionary<string, Func<double>>(); List<FunctionOrOperation> _functionsOrOperations = new List<FunctionOrOperation>(); Dictionary<string, FunctionOrOperation> _indexedFunctionOrOperation; private Dictionary<string,FunctionOrOperation> Indexed { get { if (_indexedFunctionOrOperation == null || _indexedFunctionOrOperation.Count != _functionsOrOperations.Count) _indexedFunctionOrOperation = _functionsOrOperations .ToDictionary(key => key.Term.ToLowerInvariant(), value => value); return _indexedFunctionOrOperation; } } readonly bool DEBUG = false; internal bool Solve(string expression, out double result) { var parsed = true; result = 0.0; try { // remove all spaces expression = Regex.Replace(expression, @"\s+", string.Empty); // add spaces before and after signal, operators and brackets expression = Regex.Replace(expression, @"[\-\+\*\/\(\)\^]", " $& "); // adjust unary signals, as before brackets expression = Regex.Replace(expression, @"[\-\+](?=\s*\()", @"+ ( $&1 ) * "); // adjust unary signals, as before functions expression = Regex.Replace(expression, @"[\-\+](?=\s*[a-z]+)", @"+ ( $&1 ) * ", RegexOptions.IgnoreCase); // adjust unary signals, as equation beginning expression = Regex.Replace(expression, @"^\s*([\-\+])\s*([0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)", @" $1$2 "); // adjust unary signals, as operators and signas followed by number expression = Regex.Replace(expression, @"(?<=[\+\/\*\-\^]\s*)([-+])\s*([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)", @" $1$2 "); // finally, adjust expression to postfix var values = ExpressionToPostFix(expression); if (DEBUG) { Console.WriteLine("prepared:"); Console.WriteLine(expression); Console.WriteLine("postfixed:"); foreach (var item in values) Console.Write("{0} ", item is FunctionOrOperation ? ((FunctionOrOperation)item).Term : item); Console.WriteLine(); Console.WriteLine(); } result = Calculate(values); } catch { parsed = false; } return parsed; } List<object> ExpressionToPostFix(string expression) { var output = new List<object>(); var stack = new Stack<FunctionOrOperation>(); var token = new char[] { ' ' }; var tokens = expression.Split(token, StringSplitOptions.RemoveEmptyEntries); foreach (var item in tokens) { FunctionOrOperation op; Func<double> value = null; if (IsVariableOrConstant(item, out value)) { if (value != null) output.Add(value()); else output.Add(item); } else if (IsFunctionOrOperation(item, out op)) { if (op.Context.HasFlag(FunctionOrOperation.ContextEnum.STACK)) { while (stack.Count > 0 && !stack.Peek().Context.HasFlag(FunctionOrOperation.ContextEnum.NONE) && ((op.Association == FunctionOrOperation.AssociationEnum.LEFT_TO_RIGHT && op.Precedence <= stack.Peek().Precedence) || op.Association == FunctionOrOperation.AssociationEnum.RIGHT_TO_LEFT && op.Precedence < stack.Peek().Precedence)) { var poped = stack.Pop(); if (!poped.Context.HasFlag(FunctionOrOperation.ContextEnum.NONE)) output.Add(poped); } stack.Push(op); } else if (op.Context.HasFlag(FunctionOrOperation.ContextEnum.POP)) { var found = false; while (stack.Count > 0 && !found) { var poped = stack.Pop(); if (Equals(op.StopCondition, poped.Term)) found = true; else output.Add(poped); } } } } while (stack.Count > 0) { output.Add(stack.Pop()); } return output; } double Calculate(List<object> output) { var stack = new Stack<double>(); foreach (var item in output) { if (item is FunctionOrOperation) { if(DEBUG) Console.WriteLine("Found? FunctionOrOperation."); var op = item as FunctionOrOperation; var parameters = new List<double>(); for (int aux = 0; aux < op.Parameters; aux++) { var value = stack.Pop(); parameters.Add(value); if (DEBUG) Console.WriteLine("Pop: {0}", value); } var result = op.Calc(parameters); if (DEBUG) { foreach (var parameter in parameters) { Console.Write("[{0}] ", parameter); } Console.Write("{0} ", op.Term); Console.WriteLine(" = {0}", result); Console.Write("Pushing result: {0} => [{0}]", result); foreach (var stacked in stack) Console.Write("{0} ", stacked); Console.WriteLine(); } stack.Push(Convert.ToDouble(result)); } else { if (DEBUG) { Console.WriteLine("Found? VariableOrConstant."); Console.Write("Pushing: {0} => [{0}]", item); foreach (var stacked in stack) Console.Write("{0} ", stacked); Console.WriteLine(); } stack.Push(Convert.ToDouble(item)); } } return stack.Pop(); } bool IsFunctionOrOperation(string item, out FunctionOrOperation op) { op = null; if (Indexed.TryGetValue(item.ToLowerInvariant(), out op)) { return true; } return false; } bool IsVariableOrConstant(string item, out Func<double> value) { value = null; if (_constants.TryGetValue(item.ToUpperInvariant(), out value)) { return true; } if (Regex.IsMatch(item, @"^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$")) { return true; } return false; } } }
using UnityEngine; using System.Collections; /// <summary> /// Base game script. /// </summary> public class BaseGameScript : MonoBehaviour { /// <summary> /// The current number of points /// </summary> protected int m_points = 0; /// <summary> /// The current round. /// </summary> protected int m_round = 1; /// <summary> /// The deafeat light intensity. /// </summary> public float deafeatLightIntensity = 1f; /// <summary> /// The deafeat light intensity. /// </summary> public float victoryLightIntensity = 1f; /// <summary> /// The next round Audio clip. /// </summary> public AudioClip nextRoundAC; /// <summary> /// The next round floating text time to live. /// </summary> public float nextRoundTTL = 1; /// <summary> /// The floating text gameObject. /// </summary> public GameObject floatingTextGO; /// <summary> /// The round prefix. /// </summary> public string roundPrefix = "Round:"; /// <summary> /// The audio to play when an enemy dies. /// </summary> public AudioClip onEnemyDeathAC; /// <summary> /// The sound to play when the player loses /// </summary> public AudioClip onDefeatAC; /// <summary> /// The sound to play when the player wins /// </summary> public AudioClip onVictoryAC; /// <summary> /// The ammomount of kills before saying a 1 liner. /// </summary> public int oneLinerKillLimit = 3; public int m_oneLinerKillLimit = 0; public string victorySTR = "Victory!"; public string defeatSTR = "Defeat!"; /// <summary> /// The ref to the one liners. /// </summary> protected bool m_gameover=false; private bool m_victory = false; /// <summary> /// The target framerate. /// </summary> public int framerate = 60; public int initalGold = 100; protected float m_gold; private AudioClip m_onHealthPickUpAC; private AudioClip m_onManaPickUpAC; private AudioClip m_onGemCollectAC; /// <summary> /// The score G. /// </summary> public GUIText scoreGT; /// <summary> /// The score prefix. /// </summary> public string scorePrefix = "Score: "; /// <summary> /// The score leading zeroes. /// </summary> public string scoreLeadingZeroes = "0000"; /// <summary> /// The on gem collect A. /// </summary> public AudioClip onGemCollectAC; /// <summary> /// The on gem collect message. /// </summary> public string onGemCollectMessage = "Gem Collected!"; public int gemBonus = 100; protected bool m_started = false; public void Awake() { Application.targetFrameRate = framerate; m_gold = initalGold; BaseGameManager.setNomEnemies(0); Time.timeScale=0; } private NoiseEffect m_noiseEffect; public bool wantToDisableGrayScaleOnStart = true; protected GrayscaleEffect m_grayScale; public virtual void Start() { m_grayScale = (GrayscaleEffect)Object.FindObjectOfType(typeof(GrayscaleEffect)); if(m_grayScale==null){ m_grayScale = Camera.main.gameObject.AddComponent<GrayscaleEffect>(); m_grayScale.shader = Shader.Find("Hidden/Grayscale Effect"); } myStart(); } public virtual void myStart(){ } public virtual void OnEnable() { BaseGameManager.onPlayerHit += onPlayerHit; BaseGameManager.onNextRound += onNextRound; BaseGameManager.onPushString += onPushString; BaseGameManager.onGameOver += onGameOver; BaseGameManager.onGameStart += onGameStart; BaseGameManager.onAddPoints+=onAddPoints; } public virtual void OnDisable() { BaseGameManager.onPlayerHit -= onPlayerHit; BaseGameManager.onNextRound -= onNextRound; BaseGameManager.onGameOver -= onGameOver; BaseGameManager.onGameStart -= onGameStart; BaseGameManager.onAddPoints-=onAddPoints; BaseGameManager.onPushString -= onPushString; } public void setPointsGT(int points) { if(scoreGT) { scoreGT.text = scorePrefix + " " + m_points.ToString(scoreLeadingZeroes); } } public void onPushString(string str) { pushText(str); } public void onGemCollect() { playAudioClip(m_onGemCollectAC); pushText( onGemCollectMessage ); m_points += gemBonus; setPointsGT( m_points ); } public virtual void onAddPoints(int points) { m_points += points; } public virtual void onGameStart() { if(wantToDisableGrayScaleOnStart) { if(m_grayScale) { m_grayScale.enabled = false; } } Time.timeScale=1; m_started=true; } public void pushText(string str) { } public virtual void onNextRound(int round) { m_round++; pushText(roundPrefix + round); if(GetComponent<AudioSource>()) { GetComponent<AudioSource>().PlayOneShot( nextRoundAC ); } } public void hideGUITexts() { GUIText[] texts = (GUIText[])GameObject.FindObjectsOfType(typeof(GUIText)); for(int i=0; i<texts.Length; i++) { texts[i].gameObject.SetActive(false); } } public virtual void onGameOver(bool vic) { hideGUITexts(); m_gameover = true; m_victory = vic; if(m_grayScale) { m_grayScale.enabled = true; } if(vic) { playAudioClip(onVictoryAC); setLightIntensity(victoryLightIntensity); }else { playAudioClip(onDefeatAC); setLightIntensity(deafeatLightIntensity); } } public virtual void setLightIntensity(float intensity) { Light l0 = (Light)GameObject.FindObjectOfType(typeof(Light)); if(l0) { l0.intensity = intensity; } } public virtual void onPlayerHit(float playerHealthAsScalar) { } public void playAudioClip(AudioClip ac) { if(GetComponent<AudioSource>()) { GetComponent<AudioSource>().PlayOneShot( ac ); } } public string getResultGameString() { string str = defeatSTR; if(m_victory) { str = victorySTR; } str += "\n\n"; str += getResultValues(); return str; } public virtual string getResultValues() { return "Score: " + m_points.ToString("0000"); } public virtual bool isPlayState() { return true; } public int getGold() { return (int)m_gold; } public virtual void addGold(int gold) { m_gold += gold; } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class FormHandlingTests : DriverTestFixture { [Test] public void ShouldClickOnSubmitInputElements() { driver.Url = formsPage; driver.FindElement(By.Id("submitButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ClickingOnUnclickableElementsDoesNothing() { driver.Url = formsPage; driver.FindElement(By.XPath("//body")).Click(); } [Test] public void ShouldBeAbleToClickImageButtons() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToSubmitForms() { driver.Url = formsPage; driver.FindElement(By.Name("login")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.Id("checky")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.XPath("//form/p")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.PhantomJS)] [IgnoreBrowser(Browser.Safari)] public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.Url = formsPage; Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("SearchableText")).Submit()); } [Test] public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "Brie and cheddar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void SendKeysKeepsCapitalization() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "BrIe And CheDdar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void ShouldSubmitAFormUsingTheNewlineLiteral() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys("\n"); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldSubmitAFormUsingTheEnterKey() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys(Keys.Enter); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldEnterDataIntoFormFields() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.GetAttribute("value"); Assert.AreEqual(originalValue, "change"); element.Clear(); element.SendKeys("some text"); element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.GetAttribute("value"); Assert.AreEqual(newFormValue, "some text"); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() { // IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to // download it if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = xhtmlFormPage; IWebElement uploadElement = driver.FindElement(By.Id("file")); Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value")); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToUploadTheSameFileTwice() { string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); driver.Url = formsPage; uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); // If we get this far, then we're all good. } [Test] public void SendingKeyboardEventsShouldAppendTextInInputs() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Some"); element.SendKeys(" text"); value = element.GetAttribute("value"); Assert.AreEqual(value, "Some text"); } [Test] public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("inputWithText")); element.SendKeys(". Some text"); string value = element.GetAttribute("value"); Assert.AreEqual("Example text. Some text", value); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")] public void SendingKeyboardEventsShouldAppendTextInTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys(". Some text"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Example text. Some text"); } [Test] public void ShouldBeAbleToClearTextFromInputElements() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.Url = formsPage; IWebElement emptyTextBox = driver.FindElement(By.Id("working")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); } [Test] public void ShouldBeAbleToClearTextFromTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] [IgnoreBrowser(Browser.IE, "Hangs")] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Opera, "Untested")] [IgnoreBrowser(Browser.PhantomJS, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support alert handling")] public void HandleFormWithJavascriptAction() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("form_handling_js_submit.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("theForm")); element.Submit(); IAlert alert = driver.SwitchTo().Alert(); string text = alert.Text; alert.Dismiss(); Assert.AreEqual("Tasty cheese", text); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnASubmitButton() { CheckSubmitButton("internal_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnAnImplicitSubmitButton() { CheckSubmitButton("internal_implicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalSubmitButton() { CheckSubmitButton("external_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalImplicitSubmitButton() { CheckSubmitButton("external_implicit_submit"); } private void CheckSubmitButton(string buttonId) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/html5_submit_buttons.html"); string name = "Gromit"; driver.FindElement(By.Id("name")).SendKeys(name); driver.FindElement(By.Id(buttonId)).Click(); WaitFor(TitleToBe("Submitted Successfully!"), "Browser title is not 'Submitted Successfully!'"); Assert.That(driver.Url.Contains("name=" + name), "URL does not contain 'name=" + name + "'. Actual URL:" + driver.Url); } private Func<bool> TitleToBe(string desiredTitle) { return () => { return driver.Title == desiredTitle; }; } } }
using EPiServer.Logging; using Mediachase.Commerce.Engine; using Mediachase.Commerce.Orders; using Mediachase.Commerce.Orders.Dto; using Mediachase.Commerce.Orders.Exceptions; using Mediachase.Commerce.Orders.Managers; using Mediachase.Commerce.WorkflowCompatibility; using System; using System.Collections.Generic; namespace Mediachase.Commerce.Workflow.Cart { /// <summary> /// This activity handles processing different types of payments. It will call the appropriate /// payment handler configured in the database and raise exceptions if something goes wrong. /// It also deals with removing sensitive data for credit card types of payments depending on the /// configuration settings. /// </summary> public class ProcessPaymentActivity : CartActivityBase { private const string EventsCategory = "Handlers"; // Define private constants for the Validation Errors private const int TotalPaymentMismatch = 1; [NonSerialized] private readonly ILogger Logger; /// <summary> /// Gets or sets the payment. /// </summary> /// <value>The payment.</value> [ActivityFlowContextProperty] public Payment Payment { get; set; } /// <summary> /// Gets or sets the shipment. /// </summary> /// <value>The shipment.</value> [ActivityFlowContextProperty] public Shipment Shipment { get; set; } #region Public Events /// <summary> /// Occurs when [processing payment]. /// </summary> public static string ProcessingPaymentEvent = "ProcessingPayment"; /// <summary> /// Occurs when [processed payment]. /// </summary> public static string ProcessedPaymentEvent = "ProcessedPayment"; #endregion /// <summary> /// Initializes a new instance of the <see cref="ProcessPaymentActivity"/> class. /// </summary> public ProcessPaymentActivity() { Logger = LogManager.GetLogger(GetType()); } /// <summary> /// Executes the specified execution context. /// </summary> /// <param name="executionContext">The execution context.</param> /// <returns></returns> protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // Raise the ProcessingPaymentEvent event to the parent workflow RaiseEvent(ProcessingPaymentEvent, EventArgs.Empty); // Validate the properties at runtime ValidateRuntime(); // Process payment now ProcessPayment(); // Raise the ProcessedPaymentEvent event to the parent workflow RaiseEvent(ProcessedPaymentEvent, EventArgs.Empty); // Retun the closed status indicating that this activity is complete. return ActivityExecutionStatus.Closed; } /// <summary> /// Validates the order properties. /// </summary> /// <param name="validationErrors">The validation errors.</param> protected override void ValidateOrderProperties(ValidationErrorCollection validationErrors) { base.ValidateOrderProperties(validationErrors); if (Payment == null) { // Cycle through all Order Forms and check total, it should be equal to total of all payments decimal paymentTotal = 0; foreach (OrderForm orderForm in OrderGroup.OrderForms) { foreach (Payment payment in orderForm.Payments) { paymentTotal += payment.Amount; } } if (paymentTotal < OrderGroup.Total) { Logger.Error(string.Format("Payment total is less than order total.")); var validationError = new ValidationError("The payment total and the order total do not not match. Please adjust your payment.", TotalPaymentMismatch, false); validationErrors.Add(validationError); } } } /// <summary> /// Processes the payment. /// </summary> private void ProcessPayment() { // If total is 0, we do not need to proceed if (OrderGroup.Total == 0 || OrderGroup is PaymentPlan) return; // Start Charging! PaymentMethodDto methods = PaymentManager.GetPaymentMethods(/*Thread.CurrentThread.CurrentCulture.Name*/String.Empty); foreach (OrderForm orderForm in OrderGroup.OrderForms) { foreach (Payment payment in orderForm.Payments) { if (Payment != null && !Payment.Equals(payment)) continue; //Do not process payments with status Processing and Fail var paymentStatus = PaymentStatusManager.GetPaymentStatus(payment); if (paymentStatus != PaymentStatus.Pending) continue; PaymentMethodDto.PaymentMethodRow paymentMethod = methods.PaymentMethod.FindByPaymentMethodId(payment.PaymentMethodId); // If we couldn't find payment method specified, generate an error if (paymentMethod == null) { throw new MissingMethodException(String.Format("Specified payment method \"{0}\" has not been defined.", payment.PaymentMethodId)); } Logger.Debug(String.Format("Getting the type \"{0}\".", paymentMethod.ClassName)); Type type = Type.GetType(paymentMethod.ClassName); if (type == null) throw new TypeLoadException(String.Format("Specified payment method class \"{0}\" can not be created.", paymentMethod.ClassName)); Logger.Debug(String.Format("Creating instance of \"{0}\".", type.Name)); IPaymentGateway provider = (IPaymentGateway)Activator.CreateInstance(type); provider.Settings = CreateSettings(paymentMethod); string message = ""; Logger.Debug(String.Format("Processing the payment.")); var processPaymentResult = false; var splitPaymentProvider = provider as ISplitPaymentGateway; try { if (splitPaymentProvider != null) { processPaymentResult = splitPaymentProvider.ProcessPayment(payment, Shipment, ref message); } else { processPaymentResult = provider.ProcessPayment(payment, ref message); } } catch (Exception ex) { if (ex is PaymentException) { throw; } // throw a payment exception for all providers exception throw new PaymentException(PaymentException.ErrorType.ProviderError, "", String.Format(ex.Message)); } // update payment status if (processPaymentResult) { Mediachase.Commerce.Orders.Managers.PaymentStatusManager.ProcessPayment(payment); } else { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", String.Format(message)); } Logger.Debug(String.Format("Payment processed.")); } } } /// <summary> /// Creates the settings. /// </summary> /// <param name="methodRow">The method row.</param> /// <returns></returns> private Dictionary<string, string> CreateSettings(PaymentMethodDto.PaymentMethodRow methodRow) { Dictionary<string, string> settings = new Dictionary<string, string>(); PaymentMethodDto.PaymentMethodParameterRow[] rows = methodRow.GetPaymentMethodParameterRows(); foreach (PaymentMethodDto.PaymentMethodParameterRow row in rows) { settings.Add(row.Parameter, row.Value); } return settings; } } }
using System.ComponentModel; using System.Windows.Forms; using System.Collections; using System.Diagnostics; using System.Reflection; using Microsoft.Win32; using System.Drawing; using System.IO; using System; namespace EarLab { /// <summary> /// Summary description for TreeView. /// </summary> public class TreeView : System.Windows.Forms.Form { private System.Windows.Forms.TreeView treeView1; private System.ComponentModel.IContainer components; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.ContextMenu runContextMenu; private System.Windows.Forms.MenuItem contextMenuRun; private RunFile theRunFile; private TreeNode SelectedNode, HoverNode; private System.Windows.Forms.MenuItem contextMenuOpenSimulation; private System.Windows.Forms.MenuItem menuBrowseViewFolder; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.MenuItem menuFileOpenRunfile; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem menuFileExit; private string RunFileName; private RegistryKey theKey, mApplicationKey; private RegistryString theRunfileName; private RegistryBool mEnableSuperuserMode; private const int RunCommand = 0; private const int Description = 1; private const int DiagramFile = 2; private const int ParameterFile = 3; private const int InputDirectory = 4; private const int OutputDirectory = 5; private const int CochleaIcon = 0; private const int CochleaIconSelected = 0; private const int QuestionIcon = 1; private const int QuestionIconSelected = 1; private const int TextIcon = 2; private const int TextIconSelected = 2; private const int FolderIcon = 3; private const int FolderIconSelected = 3; private const int PlayIcon = 4; private System.Windows.Forms.MenuItem menuBrowseDeleteFolder; private System.Windows.Forms.ContextMenu browseOutputContext; private System.Windows.Forms.ContextMenu browseInputContext; private System.Windows.Forms.MenuItem menuItem2; private const int PlayIconSelected = 4; private System.Windows.Forms.MenuItem menuHelp; private System.Windows.Forms.MenuItem menuHelpFile; private System.Windows.Forms.MenuItem menuHelpAbout; Process p; public TreeView(string RunFileName) { // // Required for Windows Form Designer support // InitializeComponent(); RegistryInit(); RunFile = RunFileName; } public TreeView() { // // Required for Windows Form Designer support // InitializeComponent(); RegistryInit(); RunFile = theRunfileName.Value; } private void RegistryInit() { theKey = Registry.LocalMachine.CreateSubKey(@"Software\EarLab"); theRunfileName = new RegistryString(theKey, "RunfileName", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"EarLab\runfile.xml")); mApplicationKey = Registry.CurrentUser.CreateSubKey(@"Software\EarLab\EarLab GUI"); mEnableSuperuserMode = new RegistryBool(mApplicationKey, "SuperuserMode", false); } public string RunFile { get {return RunFileName;} set { RunFileName = value; OpenRunFile(); } } private void OpenRunFile() { NodeInfo theInfo; if (!File.Exists(RunFileName)) return; theRunfileName.Value = RunFileName; theRunFile = new RunFile(RunFileName); treeView1.BeginUpdate(); treeView1.Nodes.Clear(); ImageList myImageList = new ImageList(); Stream resourceStream; timer1.Enabled = true; resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.Cochlea.bmp"); myImageList.Images.Add(Image.FromStream(resourceStream)); resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.QuestionMark.bmp"); myImageList.Images.Add(Image.FromStream(resourceStream)); resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.TextDocument.bmp"); myImageList.Images.Add(Image.FromStream(resourceStream)); resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.Folder.bmp"); myImageList.Images.Add(Image.FromStream(resourceStream)); resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.PlayIcon.bmp"); myImageList.Images.Add(Image.FromStream(resourceStream)); treeView1.ImageList = myImageList; for (int CurRun = 0; CurRun < theRunFile.Run.Length; CurRun++) { treeView1.Nodes.Insert(CurRun, new TreeNode(theRunFile.Run[CurRun].Name)); treeView1.Nodes[CurRun].ImageIndex = CochleaIcon; treeView1.Nodes[CurRun].SelectedImageIndex = CochleaIconSelected; theInfo = new NodeInfo(); theInfo.ToolTipType = ToolTipType.Static; theInfo.NodeInfoType = NodeInfoType.ContextMenu; theInfo.ContextMenu = runContextMenu; theInfo.ToolTip = "Right click for options"; theInfo.RunRecord = theRunFile.Run[CurRun]; theInfo.ProgramName = "Simulator.exe"; treeView1.Nodes[CurRun].Tag = theInfo; treeView1.Nodes[CurRun].Nodes.Insert(RunCommand, new TreeNode("Double click to run this simulation")); treeView1.Nodes[CurRun].Nodes[RunCommand].ForeColor = Color.Black; treeView1.Nodes[CurRun].Nodes[RunCommand].ImageIndex = PlayIcon; treeView1.Nodes[CurRun].Nodes[RunCommand].SelectedImageIndex = PlayIconSelected; theInfo = new NodeInfo(); theInfo.ToolTipType = ToolTipType.Static; theInfo.NodeInfoType = NodeInfoType.RunSimulation; theInfo.ToolTip = "Double click to run the simulation"; theInfo.RunRecord = theRunFile.Run[CurRun]; theInfo.ProgramName = "Simulator.exe"; treeView1.Nodes[CurRun].Nodes[RunCommand].Tag = theInfo; treeView1.Nodes[CurRun].Nodes.Insert(Description, new TreeNode("Description: " + theRunFile.Run[CurRun].Description)); treeView1.Nodes[CurRun].Nodes[Description].ForeColor = Color.MediumSlateBlue; treeView1.Nodes[CurRun].Nodes[Description].ImageIndex = QuestionIcon; treeView1.Nodes[CurRun].Nodes[Description].SelectedImageIndex = QuestionIconSelected; treeView1.Nodes[CurRun].Nodes[Description].NodeFont = new Font(treeView1.Font, FontStyle.Italic); treeView1.Nodes[CurRun].Nodes[Description].Tag = null; treeView1.Nodes[CurRun].Nodes.Insert(DiagramFile, new TreeNode("Diagram File: " + theRunFile.Run[CurRun].DiagramFileName)); treeView1.Nodes[CurRun].Nodes[DiagramFile].ImageIndex = TextIcon; treeView1.Nodes[CurRun].Nodes[DiagramFile].SelectedImageIndex = TextIconSelected; theInfo = new NodeInfo(); theInfo.ToolTipType = ToolTipType.FilenameDependent; theInfo.NodeInfoType = NodeInfoType.TextViewer; theInfo.ToolTip = "Double click to open the file"; theInfo.ProgramName = "notepad.exe"; theInfo.FileName = theRunFile.Run[CurRun].DiagramFileName; treeView1.Nodes[CurRun].Nodes[DiagramFile].Tag = theInfo; treeView1.Nodes[CurRun].Nodes.Insert(ParameterFile, new TreeNode("Parameter File: " + theRunFile.Run[CurRun].ParameterFileName)); treeView1.Nodes[CurRun].Nodes[ParameterFile].ImageIndex = TextIcon; treeView1.Nodes[CurRun].Nodes[ParameterFile].SelectedImageIndex = TextIconSelected; theInfo = new NodeInfo(); theInfo.NodeInfoType = NodeInfoType.TextViewer; theInfo.ToolTipType = ToolTipType.FilenameDependent; theInfo.ToolTip = "Double click to open the file"; theInfo.ProgramName = "notepad.exe"; theInfo.FileName = theRunFile.Run[CurRun].ParameterFileName; treeView1.Nodes[CurRun].Nodes[ParameterFile].Tag = theInfo; treeView1.Nodes[CurRun].Nodes.Insert(InputDirectory, new TreeNode("Input Directory: " + theRunFile.Run[CurRun].InputDirectoryPath)); treeView1.Nodes[CurRun].Nodes[InputDirectory].ImageIndex = FolderIcon; treeView1.Nodes[CurRun].Nodes[InputDirectory].SelectedImageIndex = FolderIconSelected; theInfo = new NodeInfo(); theInfo.NodeInfoType = NodeInfoType.ContextMenu; theInfo.ToolTip = "Right click for more options"; theInfo.ToolTipType = ToolTipType.Static; theInfo.ContextMenu = browseInputContext; theInfo.ProgramName = "explorer.exe"; theInfo.FileName = theRunFile.Run[CurRun].InputDirectoryPath; treeView1.Nodes[CurRun].Nodes[InputDirectory].Tag = theInfo; treeView1.Nodes[CurRun].Nodes.Insert(OutputDirectory, new TreeNode("Output Directory: " + theRunFile.Run[CurRun].OutputDirectoryPath)); treeView1.Nodes[CurRun].Nodes[OutputDirectory].ImageIndex = FolderIcon; treeView1.Nodes[CurRun].Nodes[OutputDirectory].SelectedImageIndex = FolderIconSelected; theInfo = new NodeInfo(); theInfo.NodeInfoType = NodeInfoType.ContextMenu; theInfo.ToolTip = "Right click for more options"; theInfo.ToolTipType = ToolTipType.Static; theInfo.ContextMenu = browseOutputContext; theInfo.ProgramName = "explorer.exe"; theInfo.FileName = theRunFile.Run[CurRun].OutputDirectoryPath; treeView1.Nodes[CurRun].Nodes[OutputDirectory].Tag = theInfo; for (int InputFile = 0; InputFile < theRunFile.Run[CurRun].SourceFileNames.Length; InputFile++) { treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes.Insert(InputFile, new TreeNode(theRunFile.Run[CurRun].SourceFileNames[InputFile])); treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].ImageIndex = TextIcon; treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].SelectedImageIndex = TextIconSelected; theInfo = new NodeInfo(); theInfo.ToolTipType = ToolTipType.FilenameDependent; theInfo.NodeInfoType = NodeInfoType.RunProgram; theInfo.ToolTip = "Double click to open the file"; theInfo.ProgramName = "explorer.exe"; theInfo.FileName = Path.Combine(theRunFile.Run[CurRun].InputDirectoryPath, theRunFile.Run[CurRun].SourceFileNames[InputFile]); if (Path.GetExtension(theInfo.FileName) == ".wav") { theInfo.ProgramName = "wmplayer.exe"; } treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].Tag = theInfo; if (File.Exists(((NodeInfo)(treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].Tag)).FileName)) treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].ForeColor = Color.Black; else treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].ForeColor = Color.LightGray; } for (int OutputFile = 0; OutputFile < theRunFile.Run[CurRun].OutputFileNames.Length; OutputFile++) { treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes.Insert(OutputFile, new TreeNode(theRunFile.Run[CurRun].OutputFileNames[OutputFile])); treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].ImageIndex = TextIcon; treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].SelectedImageIndex = TextIconSelected; treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].Tag = Path.Combine(theRunFile.Run[CurRun].OutputDirectoryPath, theRunFile.Run[CurRun].OutputFileNames[OutputFile]); theInfo = new NodeInfo(); theInfo.ToolTipType = ToolTipType.FilenameDependent; theInfo.ToolTip = "Double click to open the file"; if ((Path.GetExtension(theRunFile.Run[CurRun].OutputFileNames[OutputFile]) == ".metadata") || (Path.GetExtension(theRunFile.Run[CurRun].OutputFileNames[OutputFile]) == ".index")) { theInfo.NodeInfoType = NodeInfoType.RunProgram; theInfo.ProgramName = @"C:\Program Files\EarLab\DataViewer\DataViewer.exe"; } else { theInfo.NodeInfoType = NodeInfoType.TextViewer; theInfo.ProgramName = @"notepad.exe"; } theInfo.FileName = Path.Combine(theRunFile.Run[CurRun].OutputDirectoryPath, theRunFile.Run[CurRun].OutputFileNames[OutputFile]); treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].Tag = theInfo; if (File.Exists(((NodeInfo)(treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].Tag)).FileName)) treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].ForeColor = Color.Black; else treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].ForeColor = Color.LightGray; } } treeView1.EndUpdate(); treeView1.Location = new Point(0, 0); treeView1.Size = this.ClientSize; toolTip1.SetToolTip(treeView1, "Test Tip"); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string [] args) { Application.EnableVisualStyles(); if (args.Length == 0) Application.Run(new TreeView()); else Application.Run(new TreeView(args[0])); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.treeView1 = new System.Windows.Forms.TreeView(); this.runContextMenu = new System.Windows.Forms.ContextMenu(); this.contextMenuRun = new System.Windows.Forms.MenuItem(); this.contextMenuOpenSimulation = new System.Windows.Forms.MenuItem(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuFileOpenRunfile = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.menuFileExit = new System.Windows.Forms.MenuItem(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.browseOutputContext = new System.Windows.Forms.ContextMenu(); this.menuBrowseViewFolder = new System.Windows.Forms.MenuItem(); this.menuBrowseDeleteFolder = new System.Windows.Forms.MenuItem(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.browseInputContext = new System.Windows.Forms.ContextMenu(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.menuHelp = new System.Windows.Forms.MenuItem(); this.menuHelpFile = new System.Windows.Forms.MenuItem(); this.menuHelpAbout = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // treeView1 // this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.treeView1.ImageIndex = -1; this.treeView1.Location = new System.Drawing.Point(0, 0); this.treeView1.Name = "treeView1"; this.treeView1.SelectedImageIndex = -1; this.treeView1.Size = new System.Drawing.Size(504, 307); this.treeView1.TabIndex = 0; this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown); this.treeView1.DoubleClick += new System.EventHandler(this.treeView1_DoubleClick); this.treeView1.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand); this.treeView1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseMove); // // runContextMenu // this.runContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.contextMenuRun, this.contextMenuOpenSimulation}); // // contextMenuRun // this.contextMenuRun.Index = 0; this.contextMenuRun.Text = "Run Simulation..."; this.contextMenuRun.Click += new System.EventHandler(this.contextMenuRun_Click); // // contextMenuOpenSimulation // this.contextMenuOpenSimulation.Index = 1; this.contextMenuOpenSimulation.Text = "Open Simulation..."; this.contextMenuOpenSimulation.Click += new System.EventHandler(this.contextMenuOpenSimulation_Click); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuHelp}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuFileOpenRunfile, this.menuItem3, this.menuFileExit}); this.menuItem1.Text = "&File"; // // menuFileOpenRunfile // this.menuFileOpenRunfile.Index = 0; this.menuFileOpenRunfile.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.menuFileOpenRunfile.Text = "&Open Run File..."; this.menuFileOpenRunfile.Click += new System.EventHandler(this.menuFileOpenRunfile_Click); // // menuItem3 // this.menuItem3.Index = 1; this.menuItem3.Text = "-"; // // menuFileExit // this.menuFileExit.Index = 2; this.menuFileExit.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.menuFileExit.Text = "E&xit"; this.menuFileExit.Click += new System.EventHandler(this.menuFileExit_Click); // // browseOutputContext // this.browseOutputContext.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuBrowseViewFolder, this.menuBrowseDeleteFolder}); // // menuBrowseViewFolder // this.menuBrowseViewFolder.Index = 0; this.menuBrowseViewFolder.Text = "View Folder..."; this.menuBrowseViewFolder.Click += new System.EventHandler(this.menuBrowseViewFolder_Click); // // menuBrowseDeleteFolder // this.menuBrowseDeleteFolder.Index = 1; this.menuBrowseDeleteFolder.Text = "Delete Folder..."; this.menuBrowseDeleteFolder.Click += new System.EventHandler(this.menuBrowseDeleteFolder_Click); // // timer1 // this.timer1.Interval = 1000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // openFileDialog1 // this.openFileDialog1.Filter = "XML run files (*.xml)|*.xml|All files (*.*)|*.*"; // // browseInputContext // this.browseInputContext.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2}); // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "View Folder..."; this.menuItem2.Click += new System.EventHandler(this.menuBrowseViewFolder_Click); // // menuHelp // this.menuHelp.Index = 1; this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuHelpFile, this.menuHelpAbout}); this.menuHelp.Text = "Help"; // // menuHelpFile // this.menuHelpFile.Index = 0; this.menuHelpFile.Shortcut = System.Windows.Forms.Shortcut.F1; this.menuHelpFile.Text = "ExperimentManager Help..."; this.menuHelpFile.Click += new System.EventHandler(this.menuHelpFile_Click); // // menuHelpAbout // this.menuHelpAbout.Index = 1; this.menuHelpAbout.Text = "About EarLab ExperimentManager..."; this.menuHelpAbout.Click += new System.EventHandler(this.menuHelpAbout_Click); // // TreeView // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 313); this.Controls.Add(this.treeView1); this.Menu = this.mainMenu1; this.Name = "TreeView"; this.Text = "EarLab ExperimentManager"; this.ResumeLayout(false); } #endregion private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { NodeInfo curInfo; switch (e.Button) { case MouseButtons.Left: SelectedNode = treeView1.GetNodeAt(e.X, e.Y); break; case MouseButtons.Right: SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if (SelectedNode != null) { if (SelectedNode.Tag != null) { curInfo = (NodeInfo)SelectedNode.Tag; if (curInfo.ContextMenu != null) curInfo.ContextMenu.Show(treeView1, new Point(e.X + 10, e.Y)); } } break; default: break; } } private void treeView1_DoubleClick(object sender, System.EventArgs e) { NodeInfo curInfo; RunRecord CurRunRecord; if (SelectedNode != null) { if (SelectedNode.Parent != null) { if (SelectedNode.Tag != null) { curInfo = (NodeInfo)SelectedNode.Tag; switch (curInfo.NodeInfoType) { case NodeInfoType.RunProgram: if (File.Exists(curInfo.FileName)) System.Diagnostics.Process.Start(curInfo.ProgramName, "\"" + curInfo.FileName + "\""); else MessageBox.Show("File does not exist. Perhaps you need to run the simulation?", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case NodeInfoType.RunSimulation: curInfo = (NodeInfo)SelectedNode.Tag; CurRunRecord = curInfo.RunRecord; p = System.Diagnostics.Process.Start(curInfo.ProgramName, "-n " + CurRunRecord.FrameCount + " -i \"" + CurRunRecord.InputDirectoryPath + "\" -o \"" + CurRunRecord.OutputDirectoryPath + "\" \"" + CurRunRecord.DiagramFileName + "\" \"" + CurRunRecord.ParameterFileName + "\""); p.Exited += new EventHandler(Simulation_Exited); break; case NodeInfoType.TextViewer: if (mEnableSuperuserMode.Value) { if (File.Exists(curInfo.FileName)) System.Diagnostics.Process.Start(curInfo.ProgramName, "\"" + curInfo.FileName + "\""); else MessageBox.Show("File does not exist. Perhaps you need to run the simulation?", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { if (File.Exists(curInfo.FileName)) new SimpleTextViewer(curInfo.FileName).Show(); else MessageBox.Show("File does not exist. Perhaps you need to run the simulation?", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } break; default: break; } } } } } private void Simulation_Exited(object sender, EventArgs e) { UpdateFileStatus(); } private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { NodeInfo curInfo; HoverNode = treeView1.GetNodeAt(e.X, e.Y); if (HoverNode != null) { curInfo = (NodeInfo)HoverNode.Tag; if ((curInfo != null) && (curInfo.ToolTip != null) && (curInfo.ToolTip != "")) { if (curInfo.ToolTipType == ToolTipType.FilenameDependent) { if (File.Exists(curInfo.FileName)) toolTip1.SetToolTip(treeView1, curInfo.ToolTip); else toolTip1.SetToolTip(treeView1, "File not found"); } else { toolTip1.SetToolTip(treeView1, curInfo.ToolTip); } toolTip1.Active = true; return; } } toolTip1.Active = false; } private void contextMenuRun_Click(object sender, System.EventArgs e) { NodeInfo curInfo; RunRecord curRunRecord; if (SelectedNode.Tag != null) { curInfo = (NodeInfo)SelectedNode.Tag; curRunRecord = curInfo.RunRecord; System.Diagnostics.Process.Start(curInfo.ProgramName, "-n " + curRunRecord.FrameCount + " -i \"" + curRunRecord.InputDirectoryPath + "\" -o \"" + curRunRecord.OutputDirectoryPath + "\" \"" + curRunRecord.DiagramFileName + "\" \"" + curRunRecord.ParameterFileName + "\""); } } private void contextMenuOpenSimulation_Click(object sender, System.EventArgs e) { RunRecord CurRunRecord; NodeInfo curInfo; curInfo = (NodeInfo)SelectedNode.Tag; CurRunRecord = curInfo.RunRecord; System.Diagnostics.Process.Start(curInfo.ProgramName, "-l -n " + CurRunRecord.FrameCount + " -i \"" + CurRunRecord.InputDirectoryPath + "\" -o \"" + CurRunRecord.OutputDirectoryPath + "\" \"" + CurRunRecord.DiagramFileName + "\" \"" + CurRunRecord.ParameterFileName + "\""); } private void UpdateFileStatus() { NodeInfo curInfo; for (int CurRun = 0; CurRun < treeView1.Nodes.Count; CurRun++) { for (int InputFile = 0; InputFile < theRunFile.Run[CurRun].SourceFileNames.Length; InputFile++) { curInfo = (NodeInfo)treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].Tag; if (File.Exists(curInfo.FileName)) treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].ForeColor = Color.Black; else treeView1.Nodes[CurRun].Nodes[InputDirectory].Nodes[InputFile].ForeColor = Color.LightGray; } for (int OutputFile = 0; OutputFile < theRunFile.Run[CurRun].OutputFileNames.Length; OutputFile++) { curInfo = (NodeInfo)treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].Tag; if (File.Exists(curInfo.FileName)) { //treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].IsVisible = true; treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].ForeColor = Color.Black; } else { //treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].IsVisible = false; treeView1.Nodes[CurRun].Nodes[OutputDirectory].Nodes[OutputFile].ForeColor = Color.LightGray; } } } } private void timer1_Tick(object sender, System.EventArgs e) { UpdateFileStatus(); } private void treeView1_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e) { NodeInfo curInfo = (NodeInfo)e.Node.Tag; for (int Subnodes = 0; Subnodes < e.Node.Nodes.Count; Subnodes++) { curInfo = (NodeInfo)e.Node.Nodes[Subnodes].Tag; if ((curInfo != null) && (curInfo.ToolTipType == ToolTipType.FilenameDependent)) { if (File.Exists(curInfo.FileName)) e.Node.Nodes[Subnodes].ForeColor = Color.Black; else e.Node.Nodes[Subnodes].ForeColor = Color.LightGray; } } } private void menuFileExit_Click(object sender, System.EventArgs e) { Application.Exit(); } private void menuFileOpenRunfile_Click(object sender, System.EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { RunFile = openFileDialog1.FileName; } } private void menuBrowseViewFolder_Click(object sender, System.EventArgs e) { NodeInfo curInfo; RunRecord curRunRecord; if (SelectedNode.Tag != null) { curInfo = (NodeInfo)SelectedNode.Tag; curRunRecord = curInfo.RunRecord; System.Diagnostics.Process.Start(curInfo.ProgramName, curInfo.FileName); } } private void menuBrowseDeleteFolder_Click(object sender, System.EventArgs e) { NodeInfo curInfo; RunRecord curRunRecord; if (SelectedNode.Tag != null) { if (MessageBox.Show("Really delete this output folder? You will have to run the simulation again to re-create the files.", "Confirm folder deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { curInfo = (NodeInfo)SelectedNode.Tag; curRunRecord = curInfo.RunRecord; Directory.Delete(curInfo.FileName, true); Directory.CreateDirectory(curInfo.FileName); UpdateFileStatus(); } } } private void menuHelpFile_Click(object sender, System.EventArgs e) { string HelpPath; HelpPath = Path.GetDirectoryName(Application.ExecutablePath); HelpPath = Path.Combine(HelpPath, "DesktopEarLab.chm"); Help.ShowHelp(this, HelpPath); } private void menuHelpAbout_Click(object sender, System.EventArgs e) { About AboutForm = new About(); AboutForm.ShowDialog(this); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API includes operations for managing the disks /// in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for /// more information) /// </summary> public partial interface IVirtualMachineDiskOperations { /// <summary> /// The Create Data Disk operation adds a data disk to a virtual /// machine. There are three ways to create the data disk using the /// Add Data Disk operation. Option 1 - Attach an empty data disk to /// the role by specifying the disk label and location of the disk /// image. Do not include the DiskName and SourceMediaLink elements in /// the request body. Include the MediaLink element and reference a /// blob that is in the same geographical region as the role. You can /// also omit the MediaLink element. In this usage, Azure will create /// the data disk in the storage account configured as default for the /// role. Option 2 - Attach an existing data disk that is in the image /// repository. Do not include the DiskName and SourceMediaLink /// elements in the request body. Specify the data disk to use by /// including the DiskName element. Note: If included the in the /// response body, the MediaLink and LogicalDiskSizeInGB elements are /// ignored. Option 3 - Specify the location of a blob in your storage /// account that contain a disk image to use. Include the /// SourceMediaLink element. Note: If the MediaLink element /// isincluded, it is ignored. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role to add the data disk to. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Data Disk /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginCreatingDataDiskAsync(string serviceName, string deploymentName, string roleName, VirtualMachineDataDiskCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Deleting Data Disk operation removes the specified data /// disk from a virtual machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role to delete the data disk from. /// </param> /// <param name='logicalUnitNumber'> /// The logical unit number of the disk. /// </param> /// <param name='deleteFromStorage'> /// Specifies that the source blob for the disk should also be deleted /// from storage. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginDeletingDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, bool deleteFromStorage, CancellationToken cancellationToken); /// <summary> /// The Create Data Disk operation adds a data disk to a virtual /// machine. There are three ways to create the data disk using the /// Add Data Disk operation. Option 1 - Attach an empty data disk to /// the role by specifying the disk label and location of the disk /// image. Do not include the DiskName and SourceMediaLink elements in /// the request body. Include the MediaLink element and reference a /// blob that is in the same geographical region as the role. You can /// also omit the MediaLink element. In this usage, Azure will create /// the data disk in the storage account configured as default for the /// role. Option 2 - Attach an existing data disk that is in the image /// repository. Do not include the DiskName and SourceMediaLink /// elements in the request body. Specify the data disk to use by /// including the DiskName element. Note: If included the in the /// response body, the MediaLink and LogicalDiskSizeInGB elements are /// ignored. Option 3 - Specify the location of a blob in your storage /// account that contain a disk image to use. Include the /// SourceMediaLink element. Note: If the MediaLink element /// isincluded, it is ignored. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role to add the data disk to. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Data Disk /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> CreateDataDiskAsync(string serviceName, string deploymentName, string roleName, VirtualMachineDataDiskCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Create Disk operation adds a disk to the user image repository. /// The disk can be an operating system disk or a data disk. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Disk operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A virtual machine disk associated with your subscription. /// </returns> Task<VirtualMachineDiskCreateResponse> CreateDiskAsync(VirtualMachineDiskCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Delete Data Disk operation removes the specified data disk from /// a virtual machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role to delete the data disk from. /// </param> /// <param name='logicalUnitNumber'> /// The logical unit number of the disk. /// </param> /// <param name='deleteFromStorage'> /// Specifies that the source blob for the disk should also be deleted /// from storage. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> DeleteDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, bool deleteFromStorage, CancellationToken cancellationToken); /// <summary> /// The Delete Disk operation deletes the specified data or operating /// system disk from your image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx /// for more information) /// </summary> /// <param name='name'> /// The name of the disk to delete. /// </param> /// <param name='deleteFromStorage'> /// Specifies that the source blob for the disk should also be deleted /// from storage. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> DeleteDiskAsync(string name, bool deleteFromStorage, CancellationToken cancellationToken); /// <summary> /// The Get Data Disk operation retrieves the specified data disk from /// a virtual machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role. /// </param> /// <param name='logicalUnitNumber'> /// The logical unit number of the disk. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Data Disk operation response. /// </returns> Task<VirtualMachineDataDiskGetResponse> GetDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, CancellationToken cancellationToken); /// <summary> /// The Get Disk operation retrieves a disk from the user image /// repository. The disk can be an operating system disk or a data /// disk. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx /// for more information) /// </summary> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A virtual machine disk associated with your subscription. /// </returns> Task<VirtualMachineDiskGetResponse> GetDiskAsync(string name, CancellationToken cancellationToken); /// <summary> /// The List Disks operation retrieves a list of the disks in your /// image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Disks operation response. /// </returns> Task<VirtualMachineDiskListResponse> ListDisksAsync(CancellationToken cancellationToken); /// <summary> /// The Update Data Disk operation updates the specified data disk /// attached to the specified virtual machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of your service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleName'> /// The name of the role to add the data disk to. /// </param> /// <param name='logicalUnitNumber'> /// The logical unit number of the disk. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine Data Disk /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> UpdateDataDiskAsync(string serviceName, string deploymentName, string roleName, int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Add Disk operation adds a disk to the user image repository. /// The disk can be an operating system disk or a data disk. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx /// for more information) /// </summary> /// <param name='name'> /// The name of the disk being updated. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine Disk operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A virtual machine disk associated with your subscription. /// </returns> Task<VirtualMachineDiskUpdateResponse> UpdateDiskAsync(string name, VirtualMachineDiskUpdateParameters parameters, CancellationToken cancellationToken); } }
using System; using System.Text; /// <summary> /// StringBuilder.ctor(String,Int32) /// </summary> public class StringBuilderctor5 { public static int Main() { StringBuilderctor5 sbctor5 = new StringBuilderctor5(); TestLibrary.TestFramework.BeginTestCase("StringBuilderctor5"); if (sbctor5.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize StringBuilder with capacity and string 1"); try { string strValue = null; int capacity = this.GetInt32(1, 256); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(String.Empty)) { TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = String.Empty, actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize StringBuilder with capacity and string 2"); try { string strValue = string.Empty; int capacity = this.GetInt32(1, 256); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("003.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("003.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize StringBuilder with capacity and string 3"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = this.GetInt32(1, strValue.Length); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("005.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("005.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:Initialize StringBuilder with capacity and string 4"); try { string strValue = string.Empty; int capacity = 0; StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5:Initialize StringBuilder with capacity and string 5"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = 0; StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("009.0", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("009.1", "Initializer string was "+strValue+", StringBuilder.ToString returned "+sb.ToString()); retVal = false; } else if (sb.Capacity == 0) { TestLibrary.TestFramework.LogError("009.2", "StringBuilder.Capacity returned 0 for non-empty string"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The capacity is less than zero"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = this.GetInt32(1, Int32.MaxValue) * (-1); StringBuilder sb = new StringBuilder(strValue, capacity); TestLibrary.TestFramework.LogError("N001", "The capacity is less than zero but not throw exception"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; namespace EntityFramework.Reflection { /// <summary> /// A class to support cloning, which creates a new instance of a class with the same value as an existing instance. /// </summary> public class ObjectCloner { // key is orginal object hashcode, value is cloned copy private readonly Dictionary<int, object> _objectReferences; /// <summary> /// Initializes a new instance of the <see cref="ObjectCloner"/> class. /// </summary> public ObjectCloner() { _objectReferences = new Dictionary<int, object>(); } /// <summary> /// Creates a new object that is a copy of the source instance. /// </summary> /// <param name="source">The source object to copy.</param> /// <returns>A new object that is a copy of the source instance.</returns> public object Clone(object source) { _objectReferences.Clear(); return CloneInstance(source); } private object CloneInstance(object source) { object target; // check if this object has already been cloned // using RuntimeHelpers.GetHashCode to get object identity int hashCode = RuntimeHelpers.GetHashCode(source); if (_objectReferences.TryGetValue(hashCode, out target)) return target; #if !SILVERLIGHT // using ICloneable if available if (source is ICloneable) { target = ((ICloneable)source).Clone(); // keep track of cloned instances _objectReferences.Add(hashCode, target); return target; } #endif var sourceType = source.GetType(); var sourceAccessor = TypeAccessor.GetAccessor(sourceType); target = sourceAccessor.Create(); // keep track of cloned instances _objectReferences.Add(hashCode, target); var sourceProperties = sourceAccessor.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (IMemberAccessor sourceProperty in sourceProperties) { if (!sourceProperty.HasGetter) continue; var originalValue = sourceProperty.GetValue(source); if (originalValue == null) continue; var propertyType = sourceProperty.MemberType.GetUnderlyingType(); if (propertyType.IsArray) CloneArray(sourceProperty, source, target); else if (originalValue is IDictionary) CloneDictionary(sourceProperty, originalValue, target); else if (originalValue is IList) CloneCollection(sourceProperty, originalValue, target); else if (!propertyType.IsValueType && propertyType != typeof(string)) CloneObject(sourceProperty, originalValue, target); else if (sourceProperty.HasSetter) sourceProperty.SetValue(target, originalValue); } return target; } private void CloneArray(IMemberAccessor accessor, object originalValue, object target) { var valueType = originalValue.GetType(); var sourceList = originalValue as IList; if (sourceList == null) return; var targetValue = Activator.CreateInstance(valueType, sourceList.Count); var targetList = targetValue as IList; if (targetList == null) return; for (int i = 0; i < sourceList.Count; i++) targetList[i] = CloneInstance(sourceList[i]); accessor.SetValue(target, targetList); } private void CloneCollection(IMemberAccessor accessor, object originalValue, object target) { // support readonly collections object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; var sourceList = originalValue as IEnumerable; if (sourceList == null) return; // must support IList var targetList = targetValue as IList; if (targetList == null) return; foreach (var sourceItem in sourceList) { var cloneItem = CloneInstance(sourceItem); targetList.Add(cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); } private void CloneDictionary(IMemberAccessor accessor, object originalValue, object target) { // support readonly dictionary object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; // must support IDictionary var sourceList = originalValue as IDictionary; if (sourceList == null) return; var targetList = targetValue as IDictionary; if (targetList == null) return; var e = sourceList.GetEnumerator(); while (e.MoveNext()) { var cloneItem = CloneInstance(e.Value); targetList.Add(e.Key, cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); } private void CloneObject(IMemberAccessor accessor, object originalValue, object target) { if (!accessor.HasSetter) return; object value = CloneInstance(originalValue); accessor.SetValue(target, value); } private object CreateTargetValue(IMemberAccessor accessor, object originalValue, object target) { var valueType = originalValue.GetType(); object targetValue; // check if this object has already been cloned // using RuntimeHelpers.GetHashCode to get object identity int hashCode = RuntimeHelpers.GetHashCode(originalValue); if (_objectReferences.TryGetValue(hashCode, out targetValue)) { accessor.SetValue(target, targetValue); return null; } targetValue = LateBinder.CreateInstance(valueType); // keep track of cloned instances _objectReferences.Add(hashCode, targetValue); return targetValue; } } }
//----------------------------------------------------------------------- // <copyright file="InstantPreviewBugReport.cs" company="Google LLC"> // // Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using UnityEditor; using UnityEngine; internal static class InstantPreviewBugReport { private const string k_FileNamePrefix = "arcore_unity_editor_bug_report_"; [MenuItem("Help/Capture ARCore Bug Report")] private static void CaptureBugReport() { string desktopPath = Environment.GetFolderPath( Environment.SpecialFolder.Desktop); DateTime timeStamp = DateTime.Now; string fileNameTimestamp = timeStamp.ToString("yyyyMMdd_hhmmss"); string filePath = Path.Combine( desktopPath, k_FileNamePrefix + fileNameTimestamp + ".txt"); StreamWriter writer; // Operating system and hardware info have to be handled separately based on OS switch (SystemInfo.operatingSystemFamily) { case OperatingSystemFamily.MacOSX: writer = File.CreateText(filePath); writer.WriteLine("*** GOOGLE ARCORE SDK FOR UNITY OSX BUG REPORT ***"); writer.WriteLine("Timestamp: " + timeStamp.ToString()); writer.WriteLine(); writer.WriteLine("*** OPERATING SYSTEM INFORMATION ***"); WriteCommand("system_profiler", "SPSoftwareDataType", writer); writer.WriteLine("*** GRAPHICS INFORMATION ***"); WriteCommand("system_profiler", "SPDisplaysDataType", writer); WriteOsIndependentFields(writer); string stdOut; string stdErr; // Get PATH directories to search for adb in. ShellHelper.RunCommand( "/bin/bash", "-c -l \"echo $PATH\"", out stdOut, out stdErr); stdOut.Trim(); writer.WriteLine("*** ADB VERSIONS ON PATH ***"); WriteAdbPathVersions(stdOut.Split(':'), writer); writer.WriteLine("*** TYPE -A ADB ***"); WriteCommand("/bin/bash", "-c -l \"type -a adb\"", writer); writer.WriteLine("*** RUNNING ADB PROCESSES ***"); WriteCommand( "/bin/bash", "-c -l \"ps -ef | grep -i adb | grep -v grep\"", writer); writer.WriteLine("*** RUNNING UNITY PROCESSES ***"); WriteCommand( "/bin/bash", "-c -l \"ps -ef | grep -i Unity | grep -v grep\"", writer); writer.Close(); Debug.Log( "ARCore bug report captured. File can be found here:\n" + Path.GetFullPath(filePath)); break; case OperatingSystemFamily.Windows: writer = File.CreateText(filePath); writer.WriteLine("*** GOOGLE ARCORE SDK FOR UNITY WINDOWS BUG REPORT ***"); writer.WriteLine("Timestamp: " + timeStamp.ToString()); writer.WriteLine("*** OPERATING SYSTEM INFORMATION ***"); WriteCommand("cmd.exe", "/C systeminfo", writer); writer.WriteLine("*** GRAPHICS INFORMATION ***"); WriteCommand( "cmd.exe", "/C wmic path win32_VideoController get /format:list", writer); WriteOsIndependentFields(writer); string pathStr = Environment.GetEnvironmentVariable("PATH").Trim(); writer.WriteLine("*** ADB VERSIONS ON PATH ***"); WriteAdbPathVersions(pathStr.Split(';'), writer); writer.WriteLine("*** RUNNING ADB PROCESSES ***"); WriteCommand("cmd.exe", "/C TASKLIST | c:\\Windows\\System32\\findstr.exe \"adb\"", writer); writer.WriteLine("*** RUNNING UNITY PROCESSES ***"); WriteCommand("cmd.exe", "/C TASKLIST | c:\\Windows\\System32\\findstr.exe \"Unity\"", writer); writer.Close(); Debug.Log( "ARCore bug report captured. File can be found here:\n" + Path.GetFullPath(filePath)); break; default: string dialogMessage = "ARCore does not support capturing bug reports for " + SystemInfo.operatingSystemFamily + " at this time."; EditorUtility.DisplayDialog("ARCore Bug Report", dialogMessage, "OK"); break; } } // Writes the fields that don't have to be handled differently based on Operating System private static void WriteOsIndependentFields(StreamWriter writer) { writer.WriteLine("*** UNITY VERSION ***"); writer.WriteLine(Application.unityVersion); writer.WriteLine(); writer.WriteLine("*** UNITY RUNTIME PLATFORM ***"); writer.WriteLine(Application.platform); writer.WriteLine(); writer.WriteLine("*** ARCORE SDK FOR UNITY VERSION ***"); writer.WriteLine(GoogleARCore.VersionInfo.Version); writer.WriteLine(); // Can be null string adbPath = ShellHelper.GetAdbPath(); writer.WriteLine("*** ARCORE APP VERSION ***"); WritePackageVersionString(adbPath, "com.google.ar.core", writer); writer.WriteLine("*** INSTANT PREVIEW APP VERSION ***"); WritePackageVersionString(adbPath, "com.google.ar.core.instantpreview", writer); StringBuilder instantPreviewPluginVer = new StringBuilder(64); // Get Instant preview version by running the server. NativeApi.InitializeInstantPreview( adbPath, instantPreviewPluginVer, instantPreviewPluginVer.Capacity); writer.WriteLine("*** INSTANT PREVIEW PLUGIN VERSION ***"); writer.WriteLine(instantPreviewPluginVer); writer.WriteLine(); writer.WriteLine("*** ADB DEVICES ***"); WriteCommand(adbPath, "devices -l", writer); writer.WriteLine("*** DEVICE FINGERPRINT ***"); WriteCommand(adbPath, "shell getprop ro.build.fingerprint", writer); writer.WriteLine("*** ADB VERSION USED BY UNITY ***"); WriteCommand(adbPath, "version", writer); } private static void WriteAdbPathVersions(string[] pathDirs, StreamWriter writer) { // Search through directories in PATH to find the version of adb used from PATH foreach (var path in pathDirs) { // Ignore paths that contain illegal characters. if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) { string fullAdbPath = Path.Combine(path, ShellHelper.GetAdbFileName()); if (File.Exists(fullAdbPath)) { WriteCommand(fullAdbPath, "version", writer); } } } } private static void WriteCommand(string program, string arguments, StreamWriter writer) { if (string.IsNullOrEmpty(program)) { writer.WriteLine("error: program path was null"); } else { string stdOut; string stdErr; ShellHelper.RunCommand(program, arguments, out stdOut, out stdErr); if (!string.IsNullOrEmpty(stdOut)) { writer.WriteLine(stdOut); } if (!string.IsNullOrEmpty(stdErr)) { writer.WriteLine(stdErr); } } writer.WriteLine(); } private static void WritePackageVersionString( string adbPath, string package, StreamWriter writer) { if (string.IsNullOrEmpty(adbPath)) { writer.WriteLine("error: adb path was null"); } else { string stdOut; string stdErr; string arguments = "shell pm dump " + package + " | " + "egrep -m 1 -i 'versionName' | sed -n 's/.*versionName=//p'"; ShellHelper.RunCommand(adbPath, arguments, out stdOut, out stdErr); // If stdOut is populated, the device is connected and the app is installed if (!string.IsNullOrEmpty(stdOut)) { writer.WriteLine(stdOut); } else { // If stdErr isn't empty, then either the device isn't connected or something // else went wrong, such as adb not being installed. if (!string.IsNullOrEmpty(stdErr)) { writer.WriteLine(stdErr); } else { // If stdErr is empty, then the device is connected and the app isn't // installed writer.WriteLine(package + " is not installed on device"); } } } writer.WriteLine(); } private struct NativeApi { #pragma warning disable 626 [DllImport(InstantPreviewManager.InstantPreviewNativeApi)] public static extern bool InitializeInstantPreview( string adbPath, StringBuilder version, int versionStringLength); #pragma warning restore 626 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; using static System.Buffers.Binary.BinaryPrimitives; namespace System.Buffers.Binary.Tests { public class BinaryReaderUnitTests { [Fact] public void SpanRead() { Assert.True(BitConverter.IsLittleEndian); ulong value = 0x8877665544332211; // [11 22 33 44 55 66 77 88] Span<byte> span; unsafe { span = new Span<byte>(&value, 8); } Assert.Equal<byte>(0x11, ReadMachineEndian<byte>(span)); Assert.True(TryReadMachineEndian(span, out byte byteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<sbyte>(0x11, ReadMachineEndian<sbyte>(span)); Assert.True(TryReadMachineEndian(span, out byte sbyteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<ushort>(0x1122, ReadUInt16BigEndian(span)); Assert.True(TryReadUInt16BigEndian(span, out ushort ushortValue)); Assert.Equal(0x1122, ushortValue); Assert.Equal<ushort>(0x2211, ReadUInt16LittleEndian(span)); Assert.True(TryReadUInt16LittleEndian(span, out ushortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<short>(0x1122, ReadInt16BigEndian(span)); Assert.True(TryReadInt16BigEndian(span, out short shortValue)); Assert.Equal(0x1122, shortValue); Assert.Equal<short>(0x2211, ReadInt16LittleEndian(span)); Assert.True(TryReadInt16LittleEndian(span, out shortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<uint>(0x11223344, ReadUInt32BigEndian(span)); Assert.True(TryReadUInt32BigEndian(span, out uint uintValue)); Assert.Equal<uint>(0x11223344, uintValue); Assert.Equal<uint>(0x44332211, ReadUInt32LittleEndian(span)); Assert.True(TryReadUInt32LittleEndian(span, out uintValue)); Assert.Equal<uint>(0x44332211, uintValue); Assert.Equal<int>(0x11223344, ReadInt32BigEndian(span)); Assert.True(TryReadInt32BigEndian(span, out int intValue)); Assert.Equal<int>(0x11223344, intValue); Assert.Equal<int>(0x44332211, ReadInt32LittleEndian(span)); Assert.True(TryReadInt32LittleEndian(span, out intValue)); Assert.Equal<int>(0x44332211, intValue); Assert.Equal<ulong>(0x1122334455667788, ReadUInt64BigEndian(span)); Assert.True(TryReadUInt64BigEndian(span, out ulong ulongValue)); Assert.Equal<ulong>(0x1122334455667788, ulongValue); Assert.Equal<ulong>(0x8877665544332211, ReadUInt64LittleEndian(span)); Assert.True(TryReadUInt64LittleEndian(span, out ulongValue)); Assert.Equal<ulong>(0x8877665544332211, ulongValue); Assert.Equal<long>(0x1122334455667788, ReadInt64BigEndian(span)); Assert.True(TryReadInt64BigEndian(span, out long longValue)); Assert.Equal<long>(0x1122334455667788, longValue); Assert.Equal<long>(unchecked((long)0x8877665544332211), ReadInt64LittleEndian(span)); Assert.True(TryReadInt64LittleEndian(span, out longValue)); Assert.Equal<long>(unchecked((long)0x8877665544332211), longValue); } [Fact] public void ReadOnlySpanRead() { Assert.True(BitConverter.IsLittleEndian); ulong value = 0x8877665544332211; // [11 22 33 44 55 66 77 88] ReadOnlySpan<byte> span; unsafe { span = new ReadOnlySpan<byte>(&value, 8); } Assert.Equal<byte>(0x11, ReadMachineEndian<byte>(span)); Assert.True(TryReadMachineEndian(span, out byte byteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<sbyte>(0x11, ReadMachineEndian<sbyte>(span)); Assert.True(TryReadMachineEndian(span, out byte sbyteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<ushort>(0x1122, ReadUInt16BigEndian(span)); Assert.True(TryReadUInt16BigEndian(span, out ushort ushortValue)); Assert.Equal(0x1122, ushortValue); Assert.Equal<ushort>(0x2211, ReadUInt16LittleEndian(span)); Assert.True(TryReadUInt16LittleEndian(span, out ushortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<short>(0x1122, ReadInt16BigEndian(span)); Assert.True(TryReadInt16BigEndian(span, out short shortValue)); Assert.Equal(0x1122, shortValue); Assert.Equal<short>(0x2211, ReadInt16LittleEndian(span)); Assert.True(TryReadInt16LittleEndian(span, out shortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<uint>(0x11223344, ReadUInt32BigEndian(span)); Assert.True(TryReadUInt32BigEndian(span, out uint uintValue)); Assert.Equal<uint>(0x11223344, uintValue); Assert.Equal<uint>(0x44332211, ReadUInt32LittleEndian(span)); Assert.True(TryReadUInt32LittleEndian(span, out uintValue)); Assert.Equal<uint>(0x44332211, uintValue); Assert.Equal<int>(0x11223344, ReadInt32BigEndian(span)); Assert.True(TryReadInt32BigEndian(span, out int intValue)); Assert.Equal<int>(0x11223344, intValue); Assert.Equal<int>(0x44332211, ReadInt32LittleEndian(span)); Assert.True(TryReadInt32LittleEndian(span, out intValue)); Assert.Equal<int>(0x44332211, intValue); Assert.Equal<ulong>(0x1122334455667788, ReadUInt64BigEndian(span)); Assert.True(TryReadUInt64BigEndian(span, out ulong ulongValue)); Assert.Equal<ulong>(0x1122334455667788, ulongValue); Assert.Equal<ulong>(0x8877665544332211, ReadUInt64LittleEndian(span)); Assert.True(TryReadUInt64LittleEndian(span, out ulongValue)); Assert.Equal<ulong>(0x8877665544332211, ulongValue); Assert.Equal<long>(0x1122334455667788, ReadInt64BigEndian(span)); Assert.True(TryReadInt64BigEndian(span, out long longValue)); Assert.Equal<long>(0x1122334455667788, longValue); Assert.Equal<long>(unchecked((long)0x8877665544332211), ReadInt64LittleEndian(span)); Assert.True(TryReadInt64LittleEndian(span, out longValue)); Assert.Equal<long>(unchecked((long)0x8877665544332211), longValue); } [Fact] public void SpanReadFail() { Span<byte> span = new byte[] { 1 }; Assert.Equal<byte>(1, ReadMachineEndian<byte>(span)); Assert.True(TryReadMachineEndian(span, out byte byteValue)); Assert.Equal(1, byteValue); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<short>(_span)); Assert.False(TryReadMachineEndian(span, out short shortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<int>(_span)); Assert.False(TryReadMachineEndian(span, out int intValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<long>(_span)); Assert.False(TryReadMachineEndian(span, out long longValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<ushort>(_span)); Assert.False(TryReadMachineEndian(span, out ushort ushortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<uint>(_span)); Assert.False(TryReadMachineEndian(span, out uint uintValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<ulong>(_span)); Assert.False(TryReadMachineEndian(span, out ulong ulongValue)); Span<byte> largeSpan = new byte[100]; TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => ReadMachineEndian<TestHelpers.TestValueTypeWithReference>(_span)); TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => TryReadMachineEndian(_span, out TestHelpers.TestValueTypeWithReference stringValue)); } [Fact] public void ReadOnlySpanReadFail() { ReadOnlySpan<byte> span = new byte[] { 1 }; Assert.Equal<byte>(1, ReadMachineEndian<byte>(span)); Assert.True(TryReadMachineEndian(span, out byte byteValue)); Assert.Equal(1, byteValue); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<short>(_span)); Assert.False(TryReadMachineEndian(span, out short shortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<int>(_span)); Assert.False(TryReadMachineEndian(span, out int intValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<long>(_span)); Assert.False(TryReadMachineEndian(span, out long longValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<ushort>(_span)); Assert.False(TryReadMachineEndian(span, out ushort ushortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<uint>(_span)); Assert.False(TryReadMachineEndian(span, out uint uintValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => ReadMachineEndian<ulong>(_span)); Assert.False(TryReadMachineEndian(span, out ulong ulongValue)); ReadOnlySpan<byte> largeSpan = new byte[100]; TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => ReadMachineEndian<TestHelpers.TestValueTypeWithReference>(_span)); TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => TryReadMachineEndian(_span, out TestHelpers.TestValueTypeWithReference stringValue)); } [Fact] public void ReverseByteDoesNothing() { byte valueMax = byte.MaxValue; byte valueMin = byte.MinValue; sbyte signedValueMax = sbyte.MaxValue; sbyte signedValueMin = sbyte.MinValue; Assert.Equal(valueMax, ReverseEndianness(valueMax)); Assert.Equal(valueMin, ReverseEndianness(valueMin)); Assert.Equal(signedValueMax, ReverseEndianness(signedValueMax)); Assert.Equal(signedValueMin, ReverseEndianness(signedValueMin)); } [Fact] public void SpanWriteAndReadBigEndianHeterogeneousStruct() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStruct>()]; WriteInt16BigEndian(spanBE, s_testStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), s_testStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), s_testStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), s_testStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), s_testStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), s_testStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), s_testStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), s_testStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), s_testStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), s_testStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), s_testStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), s_testStruct.UL1); ReadOnlySpan<byte> readOnlySpanBE = new ReadOnlySpan<byte>(spanBE.ToArray()); var readStruct = new TestStruct { S0 = ReadInt16BigEndian(spanBE), I0 = ReadInt32BigEndian(spanBE.Slice(2)), L0 = ReadInt64BigEndian(spanBE.Slice(6)), US0 = ReadUInt16BigEndian(spanBE.Slice(14)), UI0 = ReadUInt32BigEndian(spanBE.Slice(16)), UL0 = ReadUInt64BigEndian(spanBE.Slice(20)), S1 = ReadInt16BigEndian(spanBE.Slice(28)), I1 = ReadInt32BigEndian(spanBE.Slice(30)), L1 = ReadInt64BigEndian(spanBE.Slice(34)), US1 = ReadUInt16BigEndian(spanBE.Slice(42)), UI1 = ReadUInt32BigEndian(spanBE.Slice(44)), UL1 = ReadUInt64BigEndian(spanBE.Slice(48)) }; var readStructFromReadOnlySpan = new TestStruct { S0 = ReadInt16BigEndian(readOnlySpanBE), I0 = ReadInt32BigEndian(readOnlySpanBE.Slice(2)), L0 = ReadInt64BigEndian(readOnlySpanBE.Slice(6)), US0 = ReadUInt16BigEndian(readOnlySpanBE.Slice(14)), UI0 = ReadUInt32BigEndian(readOnlySpanBE.Slice(16)), UL0 = ReadUInt64BigEndian(readOnlySpanBE.Slice(20)), S1 = ReadInt16BigEndian(readOnlySpanBE.Slice(28)), I1 = ReadInt32BigEndian(readOnlySpanBE.Slice(30)), L1 = ReadInt64BigEndian(readOnlySpanBE.Slice(34)), US1 = ReadUInt16BigEndian(readOnlySpanBE.Slice(42)), UI1 = ReadUInt32BigEndian(readOnlySpanBE.Slice(44)), UL1 = ReadUInt64BigEndian(readOnlySpanBE.Slice(48)) }; Assert.Equal(s_testStruct, readStruct); Assert.Equal(s_testStruct, readStructFromReadOnlySpan); } [Fact] public void SpanWriteAndReadLittleEndianHeterogeneousStruct() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStruct>()]; WriteInt16LittleEndian(spanLE, s_testStruct.S0); WriteInt32LittleEndian(spanLE.Slice(2), s_testStruct.I0); WriteInt64LittleEndian(spanLE.Slice(6), s_testStruct.L0); WriteUInt16LittleEndian(spanLE.Slice(14), s_testStruct.US0); WriteUInt32LittleEndian(spanLE.Slice(16), s_testStruct.UI0); WriteUInt64LittleEndian(spanLE.Slice(20), s_testStruct.UL0); WriteInt16LittleEndian(spanLE.Slice(28), s_testStruct.S1); WriteInt32LittleEndian(spanLE.Slice(30), s_testStruct.I1); WriteInt64LittleEndian(spanLE.Slice(34), s_testStruct.L1); WriteUInt16LittleEndian(spanLE.Slice(42), s_testStruct.US1); WriteUInt32LittleEndian(spanLE.Slice(44), s_testStruct.UI1); WriteUInt64LittleEndian(spanLE.Slice(48), s_testStruct.UL1); ReadOnlySpan<byte> readOnlySpanLE = new ReadOnlySpan<byte>(spanLE.ToArray()); var readStruct = new TestStruct { S0 = ReadInt16LittleEndian(spanLE), I0 = ReadInt32LittleEndian(spanLE.Slice(2)), L0 = ReadInt64LittleEndian(spanLE.Slice(6)), US0 = ReadUInt16LittleEndian(spanLE.Slice(14)), UI0 = ReadUInt32LittleEndian(spanLE.Slice(16)), UL0 = ReadUInt64LittleEndian(spanLE.Slice(20)), S1 = ReadInt16LittleEndian(spanLE.Slice(28)), I1 = ReadInt32LittleEndian(spanLE.Slice(30)), L1 = ReadInt64LittleEndian(spanLE.Slice(34)), US1 = ReadUInt16LittleEndian(spanLE.Slice(42)), UI1 = ReadUInt32LittleEndian(spanLE.Slice(44)), UL1 = ReadUInt64LittleEndian(spanLE.Slice(48)) }; var readStructFromReadOnlySpan = new TestStruct { S0 = ReadInt16LittleEndian(readOnlySpanLE), I0 = ReadInt32LittleEndian(readOnlySpanLE.Slice(2)), L0 = ReadInt64LittleEndian(readOnlySpanLE.Slice(6)), US0 = ReadUInt16LittleEndian(readOnlySpanLE.Slice(14)), UI0 = ReadUInt32LittleEndian(readOnlySpanLE.Slice(16)), UL0 = ReadUInt64LittleEndian(readOnlySpanLE.Slice(20)), S1 = ReadInt16LittleEndian(readOnlySpanLE.Slice(28)), I1 = ReadInt32LittleEndian(readOnlySpanLE.Slice(30)), L1 = ReadInt64LittleEndian(readOnlySpanLE.Slice(34)), US1 = ReadUInt16LittleEndian(readOnlySpanLE.Slice(42)), UI1 = ReadUInt32LittleEndian(readOnlySpanLE.Slice(44)), UL1 = ReadUInt64LittleEndian(readOnlySpanLE.Slice(48)) }; Assert.Equal(s_testStruct, readStruct); Assert.Equal(s_testStruct, readStructFromReadOnlySpan); } [Fact] public void ReadingStructFieldByFieldOrReadAndReverseEndianness() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanBE = new byte[Unsafe.SizeOf<TestHelpers.TestStructExplicit>()]; var testExplicitStruct = new TestHelpers.TestStructExplicit { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; WriteInt16BigEndian(spanBE, testExplicitStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), testExplicitStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), testExplicitStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), testExplicitStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), testExplicitStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), testExplicitStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), testExplicitStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), testExplicitStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), testExplicitStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), testExplicitStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), testExplicitStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), testExplicitStruct.UL1); Assert.Equal(56, spanBE.Length); ReadOnlySpan<byte> readOnlySpanBE = new ReadOnlySpan<byte>(spanBE.ToArray()); TestHelpers.TestStructExplicit readStructAndReverse = ReadMachineEndian<TestHelpers.TestStructExplicit>(spanBE); if (BitConverter.IsLittleEndian) { readStructAndReverse.S0 = ReverseEndianness(readStructAndReverse.S0); readStructAndReverse.I0 = ReverseEndianness(readStructAndReverse.I0); readStructAndReverse.L0 = ReverseEndianness(readStructAndReverse.L0); readStructAndReverse.US0 = ReverseEndianness(readStructAndReverse.US0); readStructAndReverse.UI0 = ReverseEndianness(readStructAndReverse.UI0); readStructAndReverse.UL0 = ReverseEndianness(readStructAndReverse.UL0); readStructAndReverse.S1 = ReverseEndianness(readStructAndReverse.S1); readStructAndReverse.I1 = ReverseEndianness(readStructAndReverse.I1); readStructAndReverse.L1 = ReverseEndianness(readStructAndReverse.L1); readStructAndReverse.US1 = ReverseEndianness(readStructAndReverse.US1); readStructAndReverse.UI1 = ReverseEndianness(readStructAndReverse.UI1); readStructAndReverse.UL1 = ReverseEndianness(readStructAndReverse.UL1); } var readStructFieldByField = new TestHelpers.TestStructExplicit { S0 = ReadInt16BigEndian(spanBE), I0 = ReadInt32BigEndian(spanBE.Slice(2)), L0 = ReadInt64BigEndian(spanBE.Slice(6)), US0 = ReadUInt16BigEndian(spanBE.Slice(14)), UI0 = ReadUInt32BigEndian(spanBE.Slice(16)), UL0 = ReadUInt64BigEndian(spanBE.Slice(20)), S1 = ReadInt16BigEndian(spanBE.Slice(28)), I1 = ReadInt32BigEndian(spanBE.Slice(30)), L1 = ReadInt64BigEndian(spanBE.Slice(34)), US1 = ReadUInt16BigEndian(spanBE.Slice(42)), UI1 = ReadUInt32BigEndian(spanBE.Slice(44)), UL1 = ReadUInt64BigEndian(spanBE.Slice(48)) }; TestHelpers.TestStructExplicit readStructAndReverseFromReadOnlySpan = ReadMachineEndian<TestHelpers.TestStructExplicit>(readOnlySpanBE); if (BitConverter.IsLittleEndian) { readStructAndReverseFromReadOnlySpan.S0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.S0); readStructAndReverseFromReadOnlySpan.I0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.I0); readStructAndReverseFromReadOnlySpan.L0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.L0); readStructAndReverseFromReadOnlySpan.US0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.US0); readStructAndReverseFromReadOnlySpan.UI0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UI0); readStructAndReverseFromReadOnlySpan.UL0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UL0); readStructAndReverseFromReadOnlySpan.S1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.S1); readStructAndReverseFromReadOnlySpan.I1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.I1); readStructAndReverseFromReadOnlySpan.L1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.L1); readStructAndReverseFromReadOnlySpan.US1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.US1); readStructAndReverseFromReadOnlySpan.UI1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UI1); readStructAndReverseFromReadOnlySpan.UL1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UL1); } var readStructFieldByFieldFromReadOnlySpan = new TestHelpers.TestStructExplicit { S0 = ReadInt16BigEndian(readOnlySpanBE), I0 = ReadInt32BigEndian(readOnlySpanBE.Slice(2)), L0 = ReadInt64BigEndian(readOnlySpanBE.Slice(6)), US0 = ReadUInt16BigEndian(readOnlySpanBE.Slice(14)), UI0 = ReadUInt32BigEndian(readOnlySpanBE.Slice(16)), UL0 = ReadUInt64BigEndian(readOnlySpanBE.Slice(20)), S1 = ReadInt16BigEndian(readOnlySpanBE.Slice(28)), I1 = ReadInt32BigEndian(readOnlySpanBE.Slice(30)), L1 = ReadInt64BigEndian(readOnlySpanBE.Slice(34)), US1 = ReadUInt16BigEndian(readOnlySpanBE.Slice(42)), UI1 = ReadUInt32BigEndian(readOnlySpanBE.Slice(44)), UL1 = ReadUInt64BigEndian(readOnlySpanBE.Slice(48)) }; Assert.Equal(testExplicitStruct, readStructAndReverse); Assert.Equal(testExplicitStruct, readStructFieldByField); Assert.Equal(testExplicitStruct, readStructAndReverseFromReadOnlySpan); Assert.Equal(testExplicitStruct, readStructFieldByFieldFromReadOnlySpan); } private static TestStruct s_testStruct = new TestStruct { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; [StructLayout(LayoutKind.Sequential)] private struct TestStruct { public short S0; public int I0; public long L0; public ushort US0; public uint UI0; public ulong UL0; public short S1; public int I1; public long L1; public ushort US1; public uint UI1; public ulong UL1; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Operation_Cronos.IO; /************* Visual Component - How it works? ******************************************************* * * A VisualComponent is, esentially, a container for Sprites, SpriteTexts or other child VisualComponents. * Its two main features are given by the two interfaces it implements: IStackable and IPositionable. * * Let's start with IPositionable. First, this interface brings the X and Y properties. These coordinates * are the absolute coordinates of the VisualComponent, while XRelative and YRelative are the relative * coordinates (relative to the VisualComponent's parent). That means that a VisualComponent with an XRelative * of 50px will be positioned 50px to the right of its parent left margin. * Then, IPositionable brings Width and Height, which return 0, by default, but are marked as virtual, so they * can be overwritten in derived classes. The methods Collides and CollidesTile return true if the Point * supplied as parameter is contained by the VisualComponent. Both of these methods are marked virtual, * and by default they check subsequently for collisions the child components which implement IPositionable. * If one of the children collides with the Point, the method returns TRUE. The children are checked * according to their StackOrder (explained below). * * The IStackable interface brings two properties: Visible and StackOrder. The Visible property is obvious, * with one mention: if a VisualComponent is set invisible, all the child components are set invisible. * Next comes StackOrder. The idea behind is simple: the VisualComponent is considered a stack of child * components. StackOrder shows the order of the children in this stack (0 - bottom). Only the order is * important so, if there are gaps between StackOrders, there is no problem. * To implement this feature, there are two GameComponentCollections: one two keep the references to the * children, and another to sort temporarily the children. Also, there is a StartingDrawOrder value, which * can be considered the "DrawOrder" of the VisualComponent. In fact it is the DrawOrder of the bottom child. * Another property, NeededDrawOrders, is a number equal to the number of children. It is needed to compute * the StartingDrawOrder of the next VisualComponent on the stack. (Example: inside a VisualComponent, the * bottom child has the StartingDrawOrder = 25 and NeededDrawOrders = 10. The StartingDrawOrder of the * child on top of it will be 25+10+1 = 36.) * The catch is that these children can have children too... What to do? * * The solution is simple. It is easy to see that this structure of VisualComponents is nothing else than * a tree. The leaves of this tree are Sprites and SpriteTexts. It is easy to get the NeededDrawOrders for * the parents of these leaves, it's actually the number of Sprites and SpriteTexts contained. And if the * NeededDrawOrders for the parents of the leaves are known, it's easy to calculate the NeededDrawOrders of * the next level of VisualComponents. This leads, obviously, to recursive algorithms. * * So, the number of children can be computed only if the count starts from the bottom of the tree (from * the leaves). When a component is inside a VisualComponent, an event is generated. In the handler, the * new child is tested if it implements IDrawable (meaning it's either Sprite or SpriteText) or not. At * the bottom of the tree, the first VisualComponents contain only Sprites or SpriteTexts. When a new * IDrawable item is added, the NeededDrawOrders value is incremented with 1. That's how the NeededDrawOrders * is computed for the bottom VisualComponents. For those in higher levels, which have children that are also * VisualComponents, the NeededDrawOrders is already computed. * * Now comes the real catch: after a new component is added into a VisualComponent, and after NeededDrawOrders * is incremented in the handler of the event, a new event is generated, which tells the parent of the * VisualComponent that its stack was changed. When the parent receives that event it also generates the * OnStackChanged event, and the event travels all the way to the top (the root of the tree). The parent * of them all updates the DrawOrders of its children, calling the UpdateComponentsDrawOrders() method. * When a child's StackOrder or StartingDrawOrder is changed, it calls it's own UpdateComponentsDrawOrders() * method, so the tree rearranges itself, recursively. It is a resource-consuming process, but it happens * only when a component is created or removed, which is not very often (speaking in CPU terms). * * * The only thing remaining which needs explaining is the colliding mechanism. When the CollidesTile or the * Collides method is called, it calls the same method of the children components. Now, this is really expensive * for the CPU. To optimize this process, the child components are checked in top-to-bottom order, and when * one collision is found, the method returns TRUE, also stopping the process. * The most favorable case is when the topmost component collides with the point, and the least favorable, * when the colliding component is at the bottom. * * NOTICE: If the Collides method is called, the processing time increases tremendously, because this method * does a pixel-by-pixel search (in a 100x100 pixels texture, which is a medium size, there can be as much * as 10.000 tests, while a CollidesTile call will make just 1 test). * That's why the StrictCollision property exists: it is FALSE by default, which means that the called method * will be CollidesTile. If it's TRUE, the Collides method will be called. It should be used only when it's * absolutely necessary. * * */ namespace Operation_Cronos.Display { /// <summary> /// This is a game component that contains a userList of sprites, text sprites and/or other VisualComponents. /// It implements the IStackable and IPositionable interfaces. /// </summary> public class VisualComponent : GameComponent, IStackable, IPositionable { public event EventHandler OnStackChanged = delegate { }; public event EventHandler OnStackOrderChanged = delegate { }; public event EventHandler OnRelativePositionChanged = delegate { }; #region Fields private int x; private int y; private int xrel; private int yrel; private int stackOrder; private int startingDrawOrder; private Boolean visible; private Boolean isVisible; private GameComponentCollection components; private GameComponentCollection sortedComponents; private int neededDrawOrders; #endregion #region Properties #region IPositionable Members /// <summary> /// The absolute X positions. /// </summary> public int X { get { return x; } set { x = value; UpdateComponentsX(); } } /// <summary> /// The absolute Y positions. /// </summary> public int Y { get { return y; } set { y = value; UpdateComponentsY(); } } public int XRelative { get { return xrel; } set { xrel = value; OnRelativePositionChanged(this, new EventArgs()); UpdateComponentsX(); } } public int YRelative { get { return yrel; } set { yrel = value; OnRelativePositionChanged(this, new EventArgs()); UpdateComponentsY(); } } public virtual int Width { get { return 0; } set { } } public virtual int Height { get { return 0; } set { } } #endregion #region IStackable /// <summary> /// The order of this VisualComponent in its layer's visual stack. /// </summary> public int StackOrder { get { return stackOrder; } set { stackOrder = value; OnStackOrderChanged(this, new EventArgs()); } } public Boolean Visible { get { return visible; } set { visible = value; UpdateComponentsVisibility(); } } public Boolean IsVisible { get { return isVisible; } set { isVisible = value; Visible = value; visible = value; UpdateComponentsVisibility(); } } #endregion public int StartingDrawOrder { get { return startingDrawOrder; } set { startingDrawOrder = value; UpdateComponentsDrawOrder(); } } public int NeededDrawOrders { get { return neededDrawOrders; } } /// <summary> /// Contains all the components of this VisualComponent. /// </summary> public GameComponentCollection Components { get { return components; } } public GameComponentCollection SortedComponents { get { return sortedComponents; } } #endregion #region Services protected GraphicsCollection GraphicsCollection { get { return (GraphicsCollection)Game.Services.GetService(typeof(GraphicsCollection)); } } protected FontsCollection FontsCollection { get { return (FontsCollection)Game.Services.GetService(typeof(FontsCollection)); } } #endregion public VisualComponent(Game game) : base(game) { Game.Components.Add(this); components = new GameComponentCollection(); sortedComponents = new GameComponentCollection(); components.ComponentAdded += new EventHandler<GameComponentCollectionEventArgs>(components_ComponentAdded); components.ComponentRemoved += new EventHandler<GameComponentCollectionEventArgs>(components_ComponentRemoved); StackOrder = 0; neededDrawOrders = 0; Visible = true; isVisible = true; } #region Event Handlers void components_ComponentAdded(object sender, GameComponentCollectionEventArgs e) { UpdateComponentsX(); UpdateComponentsY(); SortComponentsByStackOrder(); if (e.GameComponent is VisualComponent) { neededDrawOrders += ((VisualComponent)e.GameComponent).NeededDrawOrders; ((VisualComponent)e.GameComponent).OnStackOrderChanged += new EventHandler(VisualComponent_OnStackOrderChanged); ((VisualComponent)e.GameComponent).OnStackChanged += new EventHandler(VisualComponent_OnStackChanged); ((VisualComponent)e.GameComponent).OnRelativePositionChanged += new EventHandler(VisualComponent_OnRelativePositionChanged); } else { if (e.GameComponent is IDrawable) { neededDrawOrders++; } } OnStackChanged(this, new EventArgs()); } void VisualComponent_OnRelativePositionChanged(object sender, EventArgs e) { UpdateComponentsX(); UpdateComponentsY(); } void VisualComponent_OnStackChanged(object sender, EventArgs e) { OnStackChanged(this, new EventArgs()); } void VisualComponent_OnStackOrderChanged(object sender, EventArgs e) { SortComponentsByStackOrder(); UpdateComponentsDrawOrder(); } void components_ComponentRemoved(object sender, GameComponentCollectionEventArgs e) { SortComponentsByStackOrder(); if (e.GameComponent is VisualComponent) { neededDrawOrders -= ((VisualComponent)e.GameComponent).NeededDrawOrders; } else { if (e.GameComponent is IDrawable) { neededDrawOrders--; } } OnStackChanged(this, new EventArgs()); } #endregion #region Methods #region Public public virtual Boolean Collides(Point mouseWorldPosition) { Point relativeMousePosition = new Point(); relativeMousePosition.X = mouseWorldPosition.X - this.X; relativeMousePosition.Y = mouseWorldPosition.Y - this.Y; if (this.Enabled) { foreach (IPositionable component in components) { if (component is IDrawable) { Point transformedPosition = new Point(); transformedPosition.X = relativeMousePosition.X - component.XRelative; transformedPosition.Y = relativeMousePosition.Y - component.YRelative; if (component.Collides(transformedPosition)) { return true; } } else if (component is VisualComponent) { if (component.Collides(mouseWorldPosition)) { return true; } } } } return false; } public virtual Boolean CollidesTile(Point mouseWorldPosition) { Point relativeMousePosition = new Point(); relativeMousePosition.X = mouseWorldPosition.X - this.X; relativeMousePosition.Y = mouseWorldPosition.Y - this.Y; if (this.Enabled) { foreach (IPositionable component in components) { if (component is IDrawable) { Point transformedPosition = new Point(); transformedPosition.X = relativeMousePosition.X - component.XRelative; transformedPosition.Y = relativeMousePosition.Y - component.YRelative; if (component.CollidesTile(transformedPosition)) { return true; } } else if (component is VisualComponent) { if (component.CollidesTile(mouseWorldPosition)) { return true; } } } } return false; } public void AddChild(GameComponent component) { components.Add(component); } public void RemoveChild(GameComponent component) { if (component is VisualComponent) { ((VisualComponent)component).Remove(); } components.Remove(component); Game.Components.Remove(component); } public void Remove() { foreach (GameComponent component in Components) { Game.Components.Remove(component); if (component is VisualComponent) ((VisualComponent)component).Remove(); } Game.Components.Remove(this); } #endregion #region Protected protected void SortComponentsByStackOrder() { IEnumerable<IGameComponent> query = components.OrderBy(comp => ((IStackable)comp).StackOrder); sortedComponents.Clear(); for (int i = 0; i < query.Count(); i++) { sortedComponents.Add(query.ElementAt(i)); } } protected void UpdateComponentsDrawOrder() { int nextDrawOrder = StartingDrawOrder; foreach (GameComponent item in sortedComponents) { if (item is IDrawable) { ((DrawableGameComponent)item).DrawOrder = nextDrawOrder++; } else { if (item is VisualComponent) { ((VisualComponent)item).StartingDrawOrder = nextDrawOrder; nextDrawOrder += ((VisualComponent)item).NeededDrawOrders; } } } } protected virtual void UpdateComponentsX() { foreach (IPositionable component in components) { component.X = this.X + component.XRelative; } } protected virtual void UpdateComponentsY() { foreach (IPositionable component in components) { component.Y = this.Y + component.YRelative; } } protected void UpdateComponentsVisibility() { foreach (IStackable component in components) { if (Visible == true) { if (IsVisible == true) { component.Visible = true; } else { component.Visible = false; } } else { component.Visible = false; } //component.Visible = Visible; } } #endregion #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.StreamAnalytics.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace StreamAnalytics.Tests { // Anything being asserted as Assert.NotNull should be of the format Assert.NotNull(actual.{propertyName}) // This means we assume/expect that the property is always returned in the response // This is also done for properties that you cannot easily verify the value for, but we expect to be in the response // For example, the JobId property is expected to be returned for all responses, but on initial creation of the resource // we don't know what the expected value of the JobId will be since it is generated on the service side. Therefore, the best // we can do is validate that a non-null JobId is returned. public static class ValidationHelper { public static void ValidateStreamingJob(StreamingJob expected, StreamingJob actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.NotNull(actual.Id); Assert.NotNull(actual.Name); Assert.NotNull(actual.Type); Assert.Equal(expected.Location, actual.Location); if (actual.Tags != null) { Assert.NotNull(expected.Tags); Assert.NotNull(actual.Tags); Assert.Equal(expected.Tags.Count, actual.Tags.Count); foreach (var pair in actual.Tags) { Assert.True(expected.Tags.ContainsKey(pair.Key)); Assert.Equal(expected.Tags[pair.Key], pair.Value); } } else { Assert.Null(expected.Tags); Assert.Null(actual.Tags); } if (actual.Sku != null) { Assert.NotNull(expected.Sku); Assert.NotNull(actual.Sku); Assert.Equal(expected.Sku.Name, actual.Sku.Name); } else { Assert.Null(expected.Sku); Assert.Null(actual.Sku); } Assert.NotNull(actual.JobId); Guid.Parse(actual.JobId); Assert.NotNull(actual.ProvisioningState); Assert.NotNull(actual.JobState); Assert.Equal(expected.OutputStartMode, actual.OutputStartMode); Assert.Equal(expected.OutputStartTime, actual.OutputStartTime); Assert.Equal(expected.LastOutputEventTime, actual.LastOutputEventTime); Assert.Equal(expected.EventsOutOfOrderPolicy, actual.EventsOutOfOrderPolicy); Assert.Equal(expected.OutputErrorPolicy, actual.OutputErrorPolicy); Assert.Equal(expected.EventsOutOfOrderMaxDelayInSeconds, actual.EventsOutOfOrderMaxDelayInSeconds); Assert.Equal(expected.EventsLateArrivalMaxDelayInSeconds, actual.EventsLateArrivalMaxDelayInSeconds); Assert.Equal(expected.DataLocale, actual.DataLocale); Assert.Equal(expected.CompatibilityLevel, actual.CompatibilityLevel); Assert.NotNull(actual.CreatedDate); if (actual.Inputs != null) { Assert.NotNull(expected.Inputs); Assert.NotNull(actual.Inputs); Assert.Equal(expected.Inputs.Count, actual.Inputs.Count); foreach (var actualInput in actual.Inputs) { Assert.NotNull(actualInput); var expectedInput = expected.Inputs.Single(input => string.Equals(input.Id, actualInput.Id)); Assert.NotNull(expectedInput); ValidateInput(expectedInput, actualInput, validateReadOnlyProperties); } } else { Assert.Null(expected.Inputs); Assert.Null(actual.Inputs); } ValidateTransformation(expected.Transformation, actual.Transformation, validateReadOnlyProperties); if (actual.Outputs != null) { Assert.NotNull(expected.Outputs); Assert.NotNull(actual.Outputs); Assert.Equal(expected.Outputs.Count, actual.Outputs.Count); foreach (var actualOutput in actual.Outputs) { Assert.NotNull(actualOutput); var expectedOutput = expected.Outputs.Single(output => string.Equals(output.Id, actualOutput.Id)); Assert.NotNull(expectedOutput); ValidateOutput(expectedOutput, actualOutput, validateReadOnlyProperties); } } else { Assert.Null(expected.Outputs); Assert.Null(actual.Outputs); } if (actual.Functions != null) { Assert.NotNull(expected.Functions); Assert.NotNull(actual.Functions); Assert.Equal(expected.Functions.Count, actual.Functions.Count); foreach (var actualFunction in actual.Functions) { Assert.NotNull(actualFunction); var expectedFunction = expected.Functions.Single(function => string.Equals(function.Id, actualFunction.Id)); Assert.NotNull(expectedFunction); ValidateFunction(expectedFunction, actualFunction, validateReadOnlyProperties); } } else { Assert.Null(expected.Outputs); Assert.Null(actual.Outputs); } /*Assert.NotNull(actual.Etag); Guid.Parse(actual.Etag);*/ if (validateReadOnlyProperties) { Assert.Equal(expected.Id, actual.Id); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.Type, actual.Type); Assert.Equal(expected.JobId, actual.JobId); Assert.Equal(expected.ProvisioningState, actual.ProvisioningState); Assert.Equal(expected.JobState, actual.JobState); Assert.Equal(expected.CreatedDate, actual.CreatedDate); //Assert.Equal(expected.Etag, actual.Etag); } } else { Assert.Null(expected); Assert.Null(actual); } } public static void ValidateInput(Input expected, Input actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateSubResource(expected, actual, validateReadOnlyProperties); ValidateInputProperties(expected.Properties, actual.Properties, validateReadOnlyProperties); } else { Assert.Null(expected); Assert.Null(actual); } } public static void ValidateTransformation(Transformation expected, Transformation actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.StreamingUnits, actual.StreamingUnits); Assert.Equal(expected.Query, actual.Query); if (validateReadOnlyProperties) { //Assert.Equal(expected.Etag, actual.Etag); } } else { Assert.Null(expected); Assert.Null(actual); } } public static void ValidateOutput(Output expected, Output actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateSubResource(expected, actual, validateReadOnlyProperties); ValidateSerialization(expected.Serialization, actual.Serialization, validateReadOnlyProperties); ValidateOutputDataSource(expected.Datasource, actual.Datasource, validateReadOnlyProperties); if (validateReadOnlyProperties) { ValidateDiagnostics(expected.Diagnostics, actual.Diagnostics, validateReadOnlyProperties); //Assert.Equal(expected.Etag, actual.Etag); } } else { Assert.Null(expected); Assert.Null(actual); } } public static void ValidateFunction(Function expected, Function actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateSubResource(expected, actual, validateReadOnlyProperties); ValidateFunctionProperties(expected.Properties, actual.Properties, validateReadOnlyProperties); } else { Assert.Null(expected); Assert.Null(actual); } } public static void ValidateFunctionProperties(FunctionProperties expected, FunctionProperties actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is ScalarFunctionProperties) { Assert.IsType<ScalarFunctionProperties>(expected); Assert.IsType<ScalarFunctionProperties>(actual); var expectedScalarFunctionProperties = expected as ScalarFunctionProperties; var actualScalarFunctionProperties = actual as ScalarFunctionProperties; ValidateScalarFunctionProperties(expectedScalarFunctionProperties, actualScalarFunctionProperties, validateReadOnlyProperties); } else { throw new Exception("Function properties could not be cast to ScalarFunctionProperties"); } if (validateReadOnlyProperties) { //Assert.Equal(expected.Etag, actual.Etag); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateInputProperties(InputProperties expected, InputProperties actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateSerialization(expected.Serialization, actual.Serialization, validateReadOnlyProperties); if (actual is StreamInputProperties) { Assert.IsType<StreamInputProperties>(expected); Assert.IsType<StreamInputProperties>(actual); var expectedStreamInputProperties = expected as StreamInputProperties; var actualStreamInputProperties = actual as StreamInputProperties; Assert.NotNull(expectedStreamInputProperties); Assert.NotNull(actualStreamInputProperties); ValidateStreamInputDataSource(expectedStreamInputProperties.Datasource, actualStreamInputProperties.Datasource, validateReadOnlyProperties); } else if (actual is ReferenceInputProperties) { Assert.IsType<ReferenceInputProperties>(expected); Assert.IsType<ReferenceInputProperties>(actual); var expectedReferenceInputProperties = expected as ReferenceInputProperties; var actualReferenceInputProperties = actual as ReferenceInputProperties; Assert.NotNull(expectedReferenceInputProperties); Assert.NotNull(actualReferenceInputProperties); ValidateReferenceInputDataSource(expectedReferenceInputProperties.Datasource, actualReferenceInputProperties.Datasource, validateReadOnlyProperties); } else { throw new Exception("Input properties could not be cast to either StreamInputProperties or ReferenceInputProperties"); } if (validateReadOnlyProperties) { ValidateDiagnostics(expected.Diagnostics, actual.Diagnostics, validateReadOnlyProperties); //Assert.Equal(expected.Etag, actual.Etag); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateStreamInputDataSource(StreamInputDataSource expected, StreamInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is BlobStreamInputDataSource) { Assert.IsType<BlobStreamInputDataSource>(expected); Assert.IsType<BlobStreamInputDataSource>(actual); var expectedBlobStreamInputDataSource = expected as BlobStreamInputDataSource; var actualBlobStreamInputDataSource = actual as BlobStreamInputDataSource; ValidateBlobStreamInputDataSource(expectedBlobStreamInputDataSource, actualBlobStreamInputDataSource, validateReadOnlyProperties); } else if (actual is EventHubStreamInputDataSource) { Assert.IsType<EventHubStreamInputDataSource>(expected); Assert.IsType<EventHubStreamInputDataSource>(actual); var expectedEventHubStreamInputDataSource = expected as EventHubStreamInputDataSource; var actualEventHubStreamInputDataSource = actual as EventHubStreamInputDataSource; ValidateEventHubStreamInputDataSource(expectedEventHubStreamInputDataSource, actualEventHubStreamInputDataSource, validateReadOnlyProperties); } else if (actual is IoTHubStreamInputDataSource) { Assert.IsType<IoTHubStreamInputDataSource>(expected); Assert.IsType<IoTHubStreamInputDataSource>(actual); var expectedIoTHubStreamInputDataSource = expected as IoTHubStreamInputDataSource; var actualIoTHubStreamInputDataSource = actual as IoTHubStreamInputDataSource; ValidateIoTHubStreamInputDataSource(expectedIoTHubStreamInputDataSource, actualIoTHubStreamInputDataSource, validateReadOnlyProperties); } else { throw new Exception("Input properties could not be cast to BlobStreamInputDataSource, EventHubStreamInputDataSource, or IoTHubStreamInputDataSource"); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateBlobStreamInputDataSource(BlobStreamInputDataSource expected, BlobStreamInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateStorageAccountList(expected.StorageAccounts, actual.StorageAccounts, validateReadOnlyProperties); Assert.Equal(expected.Container, actual.Container); Assert.Equal(expected.PathPattern, actual.PathPattern); Assert.Equal(expected.DateFormat, actual.DateFormat); Assert.Equal(expected.TimeFormat, actual.TimeFormat); Assert.Equal(expected.SourcePartitionCount, actual.SourcePartitionCount); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateEventHubStreamInputDataSource(EventHubStreamInputDataSource expected, EventHubStreamInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.ServiceBusNamespace, actual.ServiceBusNamespace); Assert.Equal(expected.SharedAccessPolicyName, actual.SharedAccessPolicyName); Assert.Equal(expected.SharedAccessPolicyKey, actual.SharedAccessPolicyKey); Assert.Equal(expected.EventHubName, actual.EventHubName); Assert.Equal(expected.ConsumerGroupName, actual.ConsumerGroupName); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateIoTHubStreamInputDataSource(IoTHubStreamInputDataSource expected, IoTHubStreamInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.IotHubNamespace, actual.IotHubNamespace); Assert.Equal(expected.SharedAccessPolicyName, actual.SharedAccessPolicyName); Assert.Equal(expected.SharedAccessPolicyKey, actual.SharedAccessPolicyKey); Assert.Equal(expected.ConsumerGroupName, actual.ConsumerGroupName); Assert.Equal(expected.Endpoint, actual.Endpoint); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateReferenceInputDataSource(ReferenceInputDataSource expected, ReferenceInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is BlobReferenceInputDataSource) { Assert.IsType<BlobReferenceInputDataSource>(expected); Assert.IsType<BlobReferenceInputDataSource>(actual); var expectedBlobReferenceInputDataSource = expected as BlobReferenceInputDataSource; var actualBlobReferenceInputDataSource = actual as BlobReferenceInputDataSource; ValidateBlobReferenceInputDataSource(expectedBlobReferenceInputDataSource, actualBlobReferenceInputDataSource, validateReadOnlyProperties); } else { throw new Exception("Input properties could not be cast to BlobReferenceInputDataSource"); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateBlobReferenceInputDataSource(BlobReferenceInputDataSource expected, BlobReferenceInputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateStorageAccountList(expected.StorageAccounts, actual.StorageAccounts, validateReadOnlyProperties); Assert.Equal(expected.Container, actual.Container); Assert.Equal(expected.PathPattern, actual.PathPattern); Assert.Equal(expected.DateFormat, actual.DateFormat); Assert.Equal(expected.TimeFormat, actual.TimeFormat); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateOutputDataSource(OutputDataSource expected, OutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is BlobOutputDataSource) { Assert.IsType<BlobOutputDataSource>(expected); Assert.IsType<BlobOutputDataSource>(actual); var expectedBlobOutputDataSource = expected as BlobOutputDataSource; var actualBlobOutputDataSource = actual as BlobOutputDataSource; ValidateBlobOutputDataSource(expectedBlobOutputDataSource, actualBlobOutputDataSource, validateReadOnlyProperties); } else if (actual is AzureTableOutputDataSource) { Assert.IsType<AzureTableOutputDataSource>(expected); Assert.IsType<AzureTableOutputDataSource>(actual); var expectedAzureTableOutputDataSource = expected as AzureTableOutputDataSource; var actualAzureTableOutputDataSource = actual as AzureTableOutputDataSource; ValidateAzureTableOutputDataSource(expectedAzureTableOutputDataSource, actualAzureTableOutputDataSource, validateReadOnlyProperties); } else if (actual is EventHubOutputDataSource) { Assert.IsType<EventHubOutputDataSource>(expected); Assert.IsType<EventHubOutputDataSource>(actual); var expectedEventHubOutputDataSource = expected as EventHubOutputDataSource; var actualEventHubOutputDataSource = actual as EventHubOutputDataSource; ValidateEventHubOutputDataSource(expectedEventHubOutputDataSource, actualEventHubOutputDataSource, validateReadOnlyProperties); } else if (actual is AzureSqlDatabaseOutputDataSource) { Assert.IsType<AzureSqlDatabaseOutputDataSource>(expected); Assert.IsType<AzureSqlDatabaseOutputDataSource>(actual); var expectedAzureSqlDatabaseOutputDataSource = expected as AzureSqlDatabaseOutputDataSource; var actualAzureSqlDatabaseOutputDataSource = actual as AzureSqlDatabaseOutputDataSource; ValidateAzureSqlDatabaseOutputDataSource(expectedAzureSqlDatabaseOutputDataSource, actualAzureSqlDatabaseOutputDataSource, validateReadOnlyProperties); } else if (actual is DocumentDbOutputDataSource) { Assert.IsType<DocumentDbOutputDataSource>(expected); Assert.IsType<DocumentDbOutputDataSource>(actual); var expectedDocumentDbOutputDataSource = expected as DocumentDbOutputDataSource; var actualDocumentDbOutputDataSource = actual as DocumentDbOutputDataSource; ValidateDocumentDbOutputDataSource(expectedDocumentDbOutputDataSource, actualDocumentDbOutputDataSource, validateReadOnlyProperties); } else if (actual is ServiceBusQueueOutputDataSource) { Assert.IsType<ServiceBusQueueOutputDataSource>(expected); Assert.IsType<ServiceBusQueueOutputDataSource>(actual); var expectedServiceBusQueueOutputDataSource = expected as ServiceBusQueueOutputDataSource; var actualServiceBusQueueOutputDataSource = actual as ServiceBusQueueOutputDataSource; ValidateServiceBusQueueOutputDataSource(expectedServiceBusQueueOutputDataSource, actualServiceBusQueueOutputDataSource, validateReadOnlyProperties); } else if (actual is ServiceBusTopicOutputDataSource) { Assert.IsType<ServiceBusTopicOutputDataSource>(expected); Assert.IsType<ServiceBusTopicOutputDataSource>(actual); var expectedServiceBusTopicOutputDataSource = expected as ServiceBusTopicOutputDataSource; var actualServiceBusTopicOutputDataSource = actual as ServiceBusTopicOutputDataSource; ValidateServiceBusTopicOutputDataSource(expectedServiceBusTopicOutputDataSource, actualServiceBusTopicOutputDataSource, validateReadOnlyProperties); } else if (actual is PowerBIOutputDataSource) { Assert.IsType<PowerBIOutputDataSource>(expected); Assert.IsType<PowerBIOutputDataSource>(actual); var expectedPowerBIOutputDataSource = expected as PowerBIOutputDataSource; var actualPowerBIOutputDataSource = actual as PowerBIOutputDataSource; ValidatePowerBIOutputDataSource(expectedPowerBIOutputDataSource, actualPowerBIOutputDataSource, validateReadOnlyProperties); } else if (actual is AzureDataLakeStoreOutputDataSource) { Assert.IsType<AzureDataLakeStoreOutputDataSource>(expected); Assert.IsType<AzureDataLakeStoreOutputDataSource>(actual); var expectedAzureDataLakeStoreOutputDataSource = expected as AzureDataLakeStoreOutputDataSource; var actualAzureDataLakeStoreOutputDataSource = actual as AzureDataLakeStoreOutputDataSource; ValidateAzureDataLakeStoreOutputDataSource(expectedAzureDataLakeStoreOutputDataSource, actualAzureDataLakeStoreOutputDataSource, validateReadOnlyProperties); } else { throw new Exception("Output data source could not be cast to BlobStreamInputDataSource, EventHubStreamInputDataSource, or IoTHubStreamInputDataSource"); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateBlobOutputDataSource(BlobOutputDataSource expected, BlobOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateStorageAccountList(expected.StorageAccounts, actual.StorageAccounts, validateReadOnlyProperties); Assert.Equal(expected.Container, actual.Container); Assert.Equal(expected.PathPattern, actual.PathPattern); Assert.Equal(expected.DateFormat, actual.DateFormat); Assert.Equal(expected.TimeFormat, actual.TimeFormat); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureTableOutputDataSource(AzureTableOutputDataSource expected, AzureTableOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.AccountName, actual.AccountName); Assert.Equal(expected.AccountKey, actual.AccountKey); Assert.Equal(expected.Table, actual.Table); Assert.Equal(expected.PartitionKey, actual.PartitionKey); Assert.Equal(expected.RowKey, actual.RowKey); ValidateStringList(expected.ColumnsToRemove, actual.ColumnsToRemove); /*if (actual.ColumnsToRemove != null) { Assert.NotNull(expected.ColumnsToRemove); Assert.NotNull(actual.ColumnsToRemove); Assert.Equal(expected.ColumnsToRemove.Count, actual.ColumnsToRemove.Count); foreach (var actualColumnName in actual.ColumnsToRemove) { var numFromExpectedList = expected.ColumnsToRemove.Count( expectedColumnName => string.Equals(expectedColumnName, actualColumnName)); var numFromActualList = actual.ColumnsToRemove.Count( columnName => string.Equals(columnName, actualColumnName)); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected.ColumnsToRemove); Assert.Null(actual.ColumnsToRemove); }*/ Assert.Equal(expected.BatchSize, actual.BatchSize); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateEventHubOutputDataSource(EventHubOutputDataSource expected, EventHubOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.ServiceBusNamespace, actual.ServiceBusNamespace); Assert.Equal(expected.SharedAccessPolicyName, actual.SharedAccessPolicyName); Assert.Equal(expected.SharedAccessPolicyKey, actual.SharedAccessPolicyKey); Assert.Equal(expected.EventHubName, actual.EventHubName); Assert.Equal(expected.PartitionKey, actual.PartitionKey); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureSqlDatabaseOutputDataSource(AzureSqlDatabaseOutputDataSource expected, AzureSqlDatabaseOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Server, actual.Server); Assert.Equal(expected.Database, actual.Database); Assert.Equal(expected.User, actual.User); Assert.Equal(expected.Password, actual.Password); Assert.Equal(expected.Table, actual.Table); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateDocumentDbOutputDataSource(DocumentDbOutputDataSource expected, DocumentDbOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.AccountId, actual.AccountId); Assert.Equal(expected.AccountKey, actual.AccountKey); Assert.Equal(expected.Database, actual.Database); Assert.Equal(expected.CollectionNamePattern, actual.CollectionNamePattern); Assert.Equal(expected.PartitionKey, actual.PartitionKey); Assert.Equal(expected.DocumentId, actual.DocumentId); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateServiceBusQueueOutputDataSource(ServiceBusQueueOutputDataSource expected, ServiceBusQueueOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.ServiceBusNamespace, actual.ServiceBusNamespace); Assert.Equal(expected.SharedAccessPolicyName, actual.SharedAccessPolicyName); Assert.Equal(expected.SharedAccessPolicyKey, actual.SharedAccessPolicyKey); Assert.Equal(expected.QueueName, actual.QueueName); ValidateStringList(expected.PropertyColumns, actual.PropertyColumns); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateServiceBusTopicOutputDataSource(ServiceBusTopicOutputDataSource expected, ServiceBusTopicOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.ServiceBusNamespace, actual.ServiceBusNamespace); Assert.Equal(expected.SharedAccessPolicyName, actual.SharedAccessPolicyName); Assert.Equal(expected.SharedAccessPolicyKey, actual.SharedAccessPolicyKey); Assert.Equal(expected.TopicName, actual.TopicName); ValidateStringList(expected.PropertyColumns, actual.PropertyColumns); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidatePowerBIOutputDataSource(PowerBIOutputDataSource expected, PowerBIOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.RefreshToken, actual.RefreshToken); Assert.Equal(expected.TokenUserPrincipalName, actual.TokenUserPrincipalName); Assert.Equal(expected.TokenUserDisplayName, actual.TokenUserDisplayName); Assert.Equal(expected.Dataset, actual.Dataset); Assert.Equal(expected.Table, actual.Table); Assert.Equal(expected.GroupId, actual.GroupId); Assert.Equal(expected.GroupName, actual.GroupName); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureDataLakeStoreOutputDataSource(AzureDataLakeStoreOutputDataSource expected, AzureDataLakeStoreOutputDataSource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.RefreshToken, actual.RefreshToken); Assert.Equal(expected.TokenUserPrincipalName, actual.TokenUserPrincipalName); Assert.Equal(expected.TokenUserDisplayName, actual.TokenUserDisplayName); Assert.Equal(expected.AccountName, actual.AccountName); Assert.Equal(expected.TenantId, actual.TenantId); Assert.Equal(expected.FilePathPrefix, actual.FilePathPrefix); Assert.Equal(expected.DateFormat, actual.DateFormat); Assert.Equal(expected.TimeFormat, actual.TimeFormat); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateStorageAccountList(IList<StorageAccount> expected, IList<StorageAccount> actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var actualStorageAccount in actual) { Assert.NotNull(actualStorageAccount); var numFromExpectedList = expected.Count( expectedStorageAccount => string.Equals(expectedStorageAccount.AccountName, actualStorageAccount.AccountName) && string.Equals(expectedStorageAccount.AccountKey, actualStorageAccount.AccountKey)); var numFromActualList = actual.Count( storageAccount => string.Equals(storageAccount.AccountName, actualStorageAccount.AccountName) && string.Equals(storageAccount.AccountKey, actualStorageAccount.AccountKey)); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateSerialization(Serialization expected, Serialization actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is CsvSerialization) { Assert.IsType<CsvSerialization>(expected); Assert.IsType<CsvSerialization>(actual); var expectedCsvSerialization = expected as CsvSerialization; var actualCsvSerialization = actual as CsvSerialization; Assert.NotNull(expectedCsvSerialization); Assert.NotNull(actualCsvSerialization); Assert.Equal(expectedCsvSerialization.FieldDelimiter, actualCsvSerialization.FieldDelimiter); Assert.Equal(expectedCsvSerialization.Encoding, actualCsvSerialization.Encoding); } else if (actual is JsonSerialization) { Assert.IsType<JsonSerialization>(expected); Assert.IsType<JsonSerialization>(actual); var expectedJsonSerialization = expected as JsonSerialization; var actualJsonSerialization = actual as JsonSerialization; Assert.NotNull(expectedJsonSerialization); Assert.NotNull(actualJsonSerialization); Assert.Equal(expectedJsonSerialization.Encoding, actualJsonSerialization.Encoding); Assert.Equal(expectedJsonSerialization.Format, actualJsonSerialization.Format); } else if (actual is AvroSerialization) { Assert.IsType<AvroSerialization>(expected); Assert.IsType<AvroSerialization>(actual); var expectedAvroSerialization = expected as AvroSerialization; var actualAvroSerialization = actual as AvroSerialization; Assert.NotNull(expectedAvroSerialization); Assert.NotNull(actualAvroSerialization); } else { throw new Exception("Serialization could not be cast to either Csv, Json or Avro"); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateDiagnostics(Diagnostics expected, Diagnostics actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateDiagnosticConditions(expected.Conditions, actual.Conditions, validateReadOnlyProperties); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateDiagnosticConditions(IList<DiagnosticCondition> expected, IList<DiagnosticCondition> actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var actualDiagnosticCondition in actual) { Assert.NotNull(actualDiagnosticCondition); var numFromExpectedList = expected.Count( expectedDiagnosticCondition => string.Equals(expectedDiagnosticCondition.Since, actualDiagnosticCondition.Since) && string.Equals(expectedDiagnosticCondition.Code, actualDiagnosticCondition.Code) && string.Equals(expectedDiagnosticCondition.Message, actualDiagnosticCondition.Message)); var numFromActualList = actual.Count( diagnosticCondition => string.Equals(diagnosticCondition.Since, actualDiagnosticCondition.Since) && string.Equals(diagnosticCondition.Code, actualDiagnosticCondition.Code) && string.Equals(diagnosticCondition.Message, actualDiagnosticCondition.Message)); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateScalarFunctionProperties(ScalarFunctionProperties expected, ScalarFunctionProperties actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); ValidateFunctionInputList(expected.Inputs, actual.Inputs, validateReadOnlyProperties); ValidateFunctionOutput(expected.Output, actual.Output, validateReadOnlyProperties); ValidateFunctionBinding(expected.Binding, actual.Binding, validateReadOnlyProperties); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateFunctionInputList(IList<FunctionInput> expected, IList<FunctionInput> actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var actualFunctionInput in actual) { Assert.NotNull(actualFunctionInput); var numFromExpectedList = expected.Count( expectedFunctionInput => string.Equals(expectedFunctionInput.DataType, actualFunctionInput.DataType) && expectedFunctionInput.IsConfigurationParameter == actualFunctionInput.IsConfigurationParameter); var numFromActualList = actual.Count( functionInput => string.Equals(functionInput.DataType, actualFunctionInput.DataType) && functionInput.IsConfigurationParameter == actualFunctionInput.IsConfigurationParameter); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateFunctionOutput(FunctionOutput expected, FunctionOutput actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.DataType, actual.DataType); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateFunctionBinding(FunctionBinding expected, FunctionBinding actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); if (actual is AzureMachineLearningWebServiceFunctionBinding) { Assert.IsType<AzureMachineLearningWebServiceFunctionBinding>(expected); Assert.IsType<AzureMachineLearningWebServiceFunctionBinding>(actual); var expectedAzureMachineLearningWebServiceFunctionBinding = expected as AzureMachineLearningWebServiceFunctionBinding; var actualAzureMachineLearningWebServiceFunctionBinding = actual as AzureMachineLearningWebServiceFunctionBinding; ValidateAzureMachineLearningWebServiceFunctionBinding(expectedAzureMachineLearningWebServiceFunctionBinding, actualAzureMachineLearningWebServiceFunctionBinding, validateReadOnlyProperties); } else if (actual is JavaScriptFunctionBinding) { Assert.IsType<JavaScriptFunctionBinding>(expected); Assert.IsType<JavaScriptFunctionBinding>(actual); var expectedJavaScriptFunctionBinding = expected as JavaScriptFunctionBinding; var actualJavaScriptFunctionBinding = actual as JavaScriptFunctionBinding; ValidateJavaScriptFunctionBinding(expectedJavaScriptFunctionBinding, actualJavaScriptFunctionBinding, validateReadOnlyProperties); } else { throw new Exception("FunctionBinding could not be cast to either AzureMachineLearningWebServiceFunctionBinding or JavaScriptFunctionBinding"); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureMachineLearningWebServiceFunctionBinding(AzureMachineLearningWebServiceFunctionBinding expected, AzureMachineLearningWebServiceFunctionBinding actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Endpoint, actual.Endpoint); Assert.Equal(expected.ApiKey, actual.ApiKey); ValidateAzureMachineLearningWebServiceInputs(expected.Inputs, actual.Inputs, validateReadOnlyProperties); ValidateAzureMachineLearningWebServiceOutputColumnList(expected.Outputs, actual.Outputs, validateReadOnlyProperties); Assert.Equal(expected.BatchSize, actual.BatchSize); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureMachineLearningWebServiceInputs(AzureMachineLearningWebServiceInputs expected, AzureMachineLearningWebServiceInputs actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Name, actual.Name); ValidateAzureMachineLearningWebServiceInputColumnList(expected.ColumnNames, actual.ColumnNames, validateReadOnlyProperties); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureMachineLearningWebServiceInputColumnList(IList<AzureMachineLearningWebServiceInputColumn> expected, IList<AzureMachineLearningWebServiceInputColumn> actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var actualAzureMachineLearningWebServiceInputColumn in actual) { Assert.NotNull(actualAzureMachineLearningWebServiceInputColumn); var numFromExpectedList = expected.Count( expectedAzureMachineLearningWebServiceInputColumn => string.Equals(expectedAzureMachineLearningWebServiceInputColumn.Name, actualAzureMachineLearningWebServiceInputColumn.Name) && string.Equals(expectedAzureMachineLearningWebServiceInputColumn.DataType, actualAzureMachineLearningWebServiceInputColumn.DataType) && expectedAzureMachineLearningWebServiceInputColumn.MapTo == actualAzureMachineLearningWebServiceInputColumn.MapTo); var numFromActualList = actual.Count( AzureMachineLearningWebServiceInputColumn => string.Equals(AzureMachineLearningWebServiceInputColumn.Name, actualAzureMachineLearningWebServiceInputColumn.Name) && string.Equals(AzureMachineLearningWebServiceInputColumn.DataType, actualAzureMachineLearningWebServiceInputColumn.DataType) && AzureMachineLearningWebServiceInputColumn.MapTo == actualAzureMachineLearningWebServiceInputColumn.MapTo); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateAzureMachineLearningWebServiceOutputColumnList(IList<AzureMachineLearningWebServiceOutputColumn> expected, IList<AzureMachineLearningWebServiceOutputColumn> actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var actualAzureMachineLearningWebServiceOutputColumn in actual) { Assert.NotNull(actualAzureMachineLearningWebServiceOutputColumn); var numFromExpectedList = expected.Count( expectedAzureMachineLearningWebServiceOutputColumn => string.Equals(expectedAzureMachineLearningWebServiceOutputColumn.Name, actualAzureMachineLearningWebServiceOutputColumn.Name) && string.Equals(expectedAzureMachineLearningWebServiceOutputColumn.DataType, actualAzureMachineLearningWebServiceOutputColumn.DataType)); var numFromActualList = actual.Count( AzureMachineLearningWebServiceOutputColumn => string.Equals(AzureMachineLearningWebServiceOutputColumn.Name, actualAzureMachineLearningWebServiceOutputColumn.Name) && string.Equals(AzureMachineLearningWebServiceOutputColumn.DataType, actualAzureMachineLearningWebServiceOutputColumn.DataType)); Assert.True(numFromExpectedList > 0); Assert.Equal(numFromExpectedList, numFromActualList); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateJavaScriptFunctionBinding(JavaScriptFunctionBinding expected, JavaScriptFunctionBinding actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Script, actual.Script); } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateSubResource(SubResource expected, SubResource actual, bool validateReadOnlyProperties) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.NotNull(actual.Id); Assert.NotNull(actual.Name); Assert.NotNull(actual.Type); if (validateReadOnlyProperties) { Assert.Equal(expected.Id, actual.Id); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.Type, actual.Type); } } else { Assert.Null(expected); Assert.Null(actual); } } private static void ValidateStringList(IList<String> expected, IList<String> actual) { if (actual != null) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.True(expected.OrderBy(str => str).SequenceEqual(actual.OrderBy(str => str))); } else { Assert.Null(expected); Assert.Null(actual); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This source file is machine generated. Please do not change the code manually. using System; using System.Collections.Generic; using System.IO.Packaging; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml; namespace DocumentFormat.OpenXml.Office2013.PowerPoint.Roaming { /// <summary> /// <para>Defines the Key Class.</para> ///<para>This class is only available in Office2013.</para> /// <para> When the object is serialized out as xml, its qualified name is pRoam:key.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] [OfficeAvailability(FileFormatVersions.Office2013)] public partial class Key : OpenXmlLeafTextElement { private const string tagName = "key"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 76; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 13436; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((4 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the Key class. /// </summary> public Key():base(){} /// <summary> /// Initializes a new instance of the Key class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Key(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Key>(deep); } } /// <summary> /// <para>Defines the Value Class.</para> ///<para>This class is only available in Office2013.</para> /// <para> When the object is serialized out as xml, its qualified name is pRoam:value.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] [OfficeAvailability(FileFormatVersions.Office2013)] public partial class Value : OpenXmlLeafTextElement { private const string tagName = "value"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 76; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 13437; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((4 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the Value class. /// </summary> public Value():base(){} /// <summary> /// Initializes a new instance of the Value class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Value(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Value>(deep); } } /// <summary> /// <para>Defines the RoamingProperty Class.</para> ///<para>This class is only available in Office2013.</para> /// <para> When the object is serialized out as xml, its qualified name is pRoam:props.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Key &lt;pRoam:key></description></item> ///<item><description>Value &lt;pRoam:value></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Key),(FileFormatVersions)4)] [ChildElementInfo(typeof(Value),(FileFormatVersions)4)] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] [OfficeAvailability(FileFormatVersions.Office2013)] public partial class RoamingProperty : OpenXmlCompositeElement { private const string tagName = "props"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 76; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 13438; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((4 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the RoamingProperty class. /// </summary> public RoamingProperty():base(){} /// <summary> ///Initializes a new instance of the RoamingProperty class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RoamingProperty(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RoamingProperty class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RoamingProperty(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RoamingProperty class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public RoamingProperty(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 76 == namespaceId && "key" == name) return new Key(); if( 76 == namespaceId && "value" == name) return new Value(); return null; } private static readonly string[] eleTagNames = { "key","value" }; private static readonly byte[] eleNamespaceIds = { 76,76 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> Key.</para> /// <para> Represents the following element tag in the schema: pRoam:key </para> /// </summary> /// <remark> /// xmlns:pRoam = http://schemas.microsoft.com/office/powerpoint/2012/roamingSettings /// </remark> public Key Key { get { return GetElement<Key>(0); } set { SetElement(0, value); } } /// <summary> /// <para> Value.</para> /// <para> Represents the following element tag in the schema: pRoam:value </para> /// </summary> /// <remark> /// xmlns:pRoam = http://schemas.microsoft.com/office/powerpoint/2012/roamingSettings /// </remark> public Value Value { get { return GetElement<Value>(1); } set { SetElement(1, value); } } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<RoamingProperty>(deep); } } }
using Newtonsoft.Json.Linq; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace ShareDB.RichText { [TestFixture] public class DeltaTests { [Test] public void Insert_EmptyText_EmptyOps() { var delta = Delta.New().Insert(""); Assert.That(delta.Ops, Is.Empty); } [Test] public void Insert_Text_OneOp() { var delta = Delta.New().Insert("test"); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = "test" }))); } [Test] public void Insert_ConsecutiveTexts_MergeOps() { var delta = Delta.New().Insert("a").Insert("b"); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = "ab" }))); } [Test] public void Insert_ConsecutiveTextsMatchingAttrs_MergeOps() { var delta = Delta.New() .Insert("a", Obj(new { bold = true })) .Insert("b", Obj(new { bold = true })); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = "ab", attributes = new { bold = true } }))); } [Test] public void Insert_ConsecutiveTextsDifferentAttrs_TwoOps() { var delta = Delta.New() .Insert("a", Obj(new { bold = true })) .Insert("b"); Assert.That(delta.Ops, Is.EqualTo(Objs( new { insert = "a", attributes = new { bold = true } }, new { insert = "b" }))); } [Test] public void Insert_ConsecutiveEmbedsMatchingAttrs_TwoOps() { var delta = Delta.New() .Insert(1, Obj(new { alt = "Description" })) .Insert(Obj(new { url = "http://quilljs.com" }), Obj(new { alt = "Description" })); Assert.That(delta.Ops, Is.EqualTo(Objs( new { insert = 1, attributes = new { alt = "Description" } }, new { insert = new { url = "http://quilljs.com" }, attributes = new { alt = "Description" } }))); } [Test] public void Insert_TextAttributes_OneOp() { JToken attrs = Obj(new { bold = true }); var delta = Delta.New().Insert("test", attrs); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = "test", attributes = attrs }))); } [Test] public void Insert_Embed_OneOp() { var delta = Delta.New().Insert(1); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = 1 }))); } [Test] public void Insert_EmbedAttributes_OneOp() { JToken attrs = Obj(new { url = "http://quilljs.com", alt = "Quill" }); var delta = Delta.New().Insert(1, attrs); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = 1, attributes = attrs }))); } [Test] public void Insert_ObjEmbedAttributes_OneOp() { JToken embed = Obj(new { url = "http://quilljs.com" }); JToken attrs = Obj(new { alt = "Quill" }); var delta = Delta.New().Insert(embed, attrs); Assert.That(delta.Ops, Is.EqualTo(Objs(new { insert = embed, attributes = attrs }))); } [Test] public void Insert_AfterDelete_SwapOps() { var delta = Delta.New().Delete(1).Insert("a"); var expected = Delta.New().Insert("a").Delete(1); Assert.That(delta, Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Insert_AfterDeleteWithMerge_MergeOps() { var delta = Delta.New().Insert("a").Delete(1).Insert("b"); var expected = Delta.New().Insert("ab").Delete(1); Assert.That(delta, Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Insert_AfterDeleteNoMerge_SwapOps() { var delta = Delta.New().Insert(1).Delete(1).Insert("a"); var expected = Delta.New().Insert(1).Insert("a").Delete(1); Assert.That(delta, Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Insert_EmptyAttributes_IgnoreAttributes() { var delta = Delta.New().Insert("a", new JObject()); var expected = Delta.New().Insert("a"); Assert.That(delta, Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Retain_Zero_EmptyOps() { var delta = Delta.New().Retain(0); Assert.That(delta.Ops, Is.Empty); } [Test] public void Retain_Positive_OneOp() { var delta = Delta.New().Retain(2); Assert.That(delta.Ops, Is.EqualTo(Objs(new { retain = 2 }))); } [Test] public void Retain_Attributes_OneOp() { JToken attrs = Obj(new { bold = true }); var delta = Delta.New().Retain(1, attrs); Assert.That(delta.Ops, Is.EqualTo(Objs(new { retain = 1, attributes = attrs }))); } [Test] public void Retain_ConsecutiveRetainsMatchingAttrs_MergeOps() { var delta = Delta.New() .Retain(1, Obj(new { bold = true })) .Retain(3, Obj(new { bold = true })); Assert.That(delta.Ops, Is.EqualTo(Objs(new { retain = 4, attributes = new { bold = true } }))); } [Test] public void Retain_ConsecutiveRetainsDifferentAttrs_TwoOps() { var delta = Delta.New() .Retain(1, Obj(new { bold = true })) .Retain(3); Assert.That(delta.Ops, Is.EqualTo(Objs( new { retain = 1, attributes = new { bold = true } }, new { retain = 3 }))); } [Test] public void Retain_EmptyAttributes_IgnoreAttributes() { var delta = Delta.New().Retain(2, new JObject()).Delete(1); var expected = Delta.New().Retain(2).Delete(1); Assert.That(delta, Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Delete_Zero_EmptyOps() { var delta = Delta.New().Delete(0); Assert.That(delta.Ops, Is.Empty); } [Test] public void Delete_Positive_OneOp() { var delta = Delta.New().Delete(1); Assert.That(delta.Ops, Is.EqualTo(Objs(new { delete = 1 }))); } [Test] public void Delete_ConsecutiveDeletes_MergeOps() { var delta = Delta.New().Delete(2).Delete(3); Assert.That(delta.Ops, Is.EqualTo(Objs(new { delete = 5 }))); } [Test] public void Compose_InsertInsert_TwoOps() { var a = Delta.New().Insert("A"); var b = Delta.New().Insert("B"); var expected = Delta.New().Insert("B").Insert("A"); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_InsertRetain_MergeOps() { var a = Delta.New().Insert("A"); var b = Delta.New().Retain(1, Obj(new { bold = true, color = "red", font = (string) null })); var expected = Delta.New().Insert("A", Obj(new { bold = true, color = "red" })); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_InsertDelete_MergeOps() { var a = Delta.New().Insert("A"); var b = Delta.New().Delete(1); var expected = Delta.New(); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_DeleteInsert_TwoOps() { var a = Delta.New().Delete(1); var b = Delta.New().Insert("B"); var expected = Delta.New().Insert("B").Delete(1); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_DeleteRetain_TwoOps() { var a = Delta.New().Delete(1); var b = Delta.New().Retain(1, Obj(new { bold = true, color = "red" })); var expected = Delta.New().Delete(1).Retain(1, Obj(new { bold = true, color = "red" })); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_DeleteDelete_MergeOps() { var a = Delta.New().Delete(1); var b = Delta.New().Delete(1); var expected = Delta.New().Delete(2); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RetainInsert_TwoOps() { var a = Delta.New().Retain(1, Obj(new { color = "blue" })); var b = Delta.New().Insert("B"); var expected = Delta.New().Insert("B").Retain(1, Obj(new { color = "blue" })); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RetainRetain_MergeOps() { var a = Delta.New().Retain(1, Obj(new { color = "blue" })); var b = Delta.New().Retain(1, Obj(new { bold = true, color = "red", font = (string) null })); var expected = Delta.New().Retain(1, Obj(new { bold = true, color = "red", font = (string) null })); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RetainDelete_MergeOps() { var a = Delta.New().Retain(1, Obj(new { color = "blue" })); var b = Delta.New().Delete(1); var expected = Delta.New().Delete(1); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_InsertInMiddle_MergeOps() { var a = Delta.New().Insert("Hello"); var b = Delta.New().Retain(3).Insert("X"); var expected = Delta.New().Insert("HelXlo"); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_InsertDeleteOrdering_MergeOps() { var a = Delta.New().Insert("Hello"); var b = Delta.New().Insert("Hello"); var insertFirst = Delta.New().Retain(3).Insert("X").Delete(1); var deleteFirst = Delta.New().Retain(3).Delete(1).Insert("X"); var expected = Delta.New().Insert("HelXo"); Assert.That(a.Compose(insertFirst), Is.EqualTo(expected).Using(Delta.EqualityComparer)); Assert.That(b.Compose(deleteFirst), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_InsertEmbedRetain_MergeOps() { var a = Delta.New().Insert(1, Obj(new { src = "http://quilljs.com/image.png" })); var b = Delta.New().Retain(1, Obj(new { alt = "logo" })); var expected = Delta.New().Insert(1, Obj(new { src = "http://quilljs.com/image.png", alt = "logo" })); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_DeleteEntireText_MergeOps() { var a = Delta.New().Retain(4).Insert("Hello"); var b = Delta.New().Delete(9); var expected = Delta.New().Delete(4); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RetainMoreThanText_MergeOps() { var a = Delta.New().Insert("Hello"); var b = Delta.New().Retain(10); var expected = Delta.New().Insert("Hello"); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RetainEmbed_MergeOps() { var a = Delta.New().Insert(1); var b = Delta.New().Retain(1); var expected = Delta.New().Insert(1); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RemoveAttributes_MergeOps() { var a = Delta.New().Insert("A", Obj(new { bold = true })); var b = Delta.New().Retain(1, Obj(new { bold = (bool?) null })); var expected = Delta.New().Insert("A"); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_RemoveEmbedAttributes_MergeOps() { var a = Delta.New().Insert(2, Obj(new { bold = true })); var b = Delta.New().Retain(1, Obj(new { bold = (bool?) null })); var expected = Delta.New().Insert(2); Assert.That(a.Compose(b), Is.EqualTo(expected).Using(Delta.EqualityComparer)); } [Test] public void Compose_Immutability() { JToken attr1 = Obj(new { bold = true }); JToken attr2 = Obj(new { bold = true }); var a1 = Delta.New().Insert("Test", attr1); var a2 = Delta.New().Insert("Test", attr1); var b1 = Delta.New().Retain(1, Obj(new { color = "red" })).Delete(2); var b2 = Delta.New().Retain(1, Obj(new { color = "red" })).Delete(2); var expected = Delta.New().Insert("T", Obj(new { color = "red", bold = true })).Insert("t", attr1); Assert.That(a1.Compose(b1), Is.EqualTo(expected).Using(Delta.EqualityComparer)); Assert.That(a1, Is.EqualTo(a2).Using(Delta.EqualityComparer)); Assert.That(b1, Is.EqualTo(b2).Using(Delta.EqualityComparer)); Assert.That(attr1, Is.EqualTo(attr2)); } private static IEnumerable<JToken> Objs(params object[] objs) { return objs.Select(Obj); } private static JToken Obj(object obj) { return JObject.FromObject(obj); } } }
/* Copyright (c) Citrix Systems, 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Xml; namespace XenAdmin.CustomFields { /// <summary> /// Provide custom fields management support for VMs. The master list of custom fields will be /// maintained in the pool class using the same conventions as the tags implementation (see /// XenAdmin.XenSearch.Tags). When persisting the label-value pairs in the VMs, the /// following key/value convention will be used: /// "XenCenter.CustomFields.foo1" value /// "XenCenter.CustomFields.foo2" value /// </summary> public class CustomFieldsManager { #region These functions deal with caching the list of custom fields private static readonly CustomFieldsCache customFieldsCache = new CustomFieldsCache(); private const String CUSTOM_FIELD_DELIM = "."; public const String CUSTOM_FIELD_BASE_KEY = "XenCenter.CustomFields"; public const String CUSTOM_FIELD = "CustomField:"; public static event Action CustomFieldsChanged; static CustomFieldsManager() { OtherConfigAndTagsWatcher.GuiConfigChanged += OtherConfigAndTagsWatcher_GuiConfigChanged; } private static void OtherConfigAndTagsWatcher_GuiConfigChanged() { InvokeHelper.AssertOnEventThread(); customFieldsCache.RecalculateCustomFields(); OnCustomFieldsChanged(); } private static void OnCustomFieldsChanged() { Action handler = CustomFieldsChanged; if (handler != null) { handler(); } } #endregion #region These functions deal with custom field definitions on the pool object public static List<CustomFieldDefinition> GetCustomFields() { return customFieldsCache.GetCustomFields(); } public static List<CustomFieldDefinition> GetCustomFields(IXenConnection connection) { return customFieldsCache.GetCustomFields(connection); } /// <returns>The CustomFieldDefinition with the given name, or null if none is found.</returns> public static CustomFieldDefinition GetCustomFieldDefinition(string name) { foreach (CustomFieldDefinition d in GetCustomFields()) { if (d.Name == name) return d; } return null; } public static void RemoveCustomField(Session session, IXenConnection connection, CustomFieldDefinition definition) { List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection); if (customFields.Remove(definition)) { SaveCustomFields(session, connection, customFields); // Remove from all Objects RemoveCustomFieldsFrom(session, connection.Cache.VMs, definition); RemoveCustomFieldsFrom(session, connection.Cache.Hosts, definition); RemoveCustomFieldsFrom(session, connection.Cache.Pools, definition); RemoveCustomFieldsFrom(session, connection.Cache.SRs, definition); } } public static void AddCustomField(Session session, IXenConnection connection, CustomFieldDefinition customField) { List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection); if (!customFields.Contains(customField)) { customFields.Add(customField); SaveCustomFields(session, connection, customFields); } } private static String GetCustomFieldDefinitionXML(List<CustomFieldDefinition> customFieldDefinitions) { XmlDocument doc = new XmlDocument(); XmlNode parentNode = doc.CreateElement("CustomFieldDefinitions"); doc.AppendChild(parentNode); foreach (CustomFieldDefinition customFieldDefinition in customFieldDefinitions) { parentNode.AppendChild(customFieldDefinition.ToXmlNode(doc)); } return doc.OuterXml; } #endregion #region These functions deal with the custom fields themselves public static string GetCustomFieldKey(CustomFieldDefinition customFieldDefinition) { return CUSTOM_FIELD_BASE_KEY + CUSTOM_FIELD_DELIM + customFieldDefinition.Name; } private static void RemoveCustomFieldsFrom(Session session, IEnumerable<IXenObject> os, CustomFieldDefinition customFieldDefinition) { InvokeHelper.AssertOffEventThread(); string customFieldKey = GetCustomFieldKey(customFieldDefinition); foreach (IXenObject o in os) { Helpers.RemoveFromOtherConfig(session, o, customFieldKey); } } private static void SaveCustomFields(Session session, IXenConnection connection, List<CustomFieldDefinition> customFields) { Pool pool = Helpers.GetPoolOfOne(connection); if (pool != null) { String customFieldXML = GetCustomFieldDefinitionXML(customFields); Helpers.SetGuiConfig(session, pool, CUSTOM_FIELD_BASE_KEY, customFieldXML); } } public static List<CustomField> CustomFieldValues(IXenObject o) { //Program.AssertOnEventThread(); List<CustomField> customFields = new List<CustomField>(); Dictionary<String, String> otherConfig = GetOtherConfigCopy(o); if (otherConfig != null) { foreach (CustomFieldDefinition customFieldDefinition in customFieldsCache.GetCustomFields(o.Connection)) { string customFieldKey = GetCustomFieldKey(customFieldDefinition); if (!otherConfig.ContainsKey(customFieldKey) || otherConfig[customFieldKey] == String.Empty) { continue; } object value = ParseValue(customFieldDefinition.Type, otherConfig[customFieldKey]); if (value != null) { customFields.Add(new CustomField(customFieldDefinition, value)); } } } return customFields; } // The same as CustomFieldValues(), but with each custom field unwound into an array public static List<object[]> CustomFieldArrays(IXenObject o) { List<object[]> ans = new List<object[]>(); foreach (CustomField cf in CustomFieldValues(o)) { ans.Add(cf.ToArray()); } return ans; } // Whether the object has any custom fields defined public static bool HasCustomFields(IXenObject o) { Dictionary<String, String> otherConfig = GetOtherConfigCopy(o); if (otherConfig != null) { foreach (CustomFieldDefinition customFieldDefinition in GetCustomFields(o.Connection)) { string customFieldKey = GetCustomFieldKey(customFieldDefinition); if (otherConfig.ContainsKey(customFieldKey) && otherConfig[customFieldKey] != String.Empty) { return true; } } } return false; } public static Object GetCustomFieldValue(IXenObject o, CustomFieldDefinition customFieldDefinition) { Dictionary<String, String> otherConfig = GetOtherConfigCopy(o); if (otherConfig == null) return null; String key = GetCustomFieldKey(customFieldDefinition); if (!otherConfig.ContainsKey(key)) return null; String value = otherConfig[key]; if (value == String.Empty) return null; return ParseValue(customFieldDefinition.Type, value); } private static object ParseValue(CustomFieldDefinition.Types type, string value) { switch (type) { case CustomFieldDefinition.Types.Date: DateTime datetime; if (DateTime.TryParse(value, out datetime)) return datetime; return null; case CustomFieldDefinition.Types.String: return value; default: return null; } } private static Dictionary<string, string> GetOtherConfigCopy(IXenObject o) { Dictionary<string, string> output = new Dictionary<string, string>(); InvokeHelper.Invoke(delegate() { Dictionary<String, String> otherConfig = Helpers.GetOtherConfig(o); if (otherConfig == null) { output = null; } else { output = new Dictionary<string, string>(otherConfig); } }); return output; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { public partial class CultureInfo : IFormatProvider, ICloneable { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// //--------------------------------------------------------------------// // Data members to be serialized: //--------------------------------------------------------------------// // We use an RFC4646 type string to construct CultureInfo. // This string is stored in m_name and is authoritative. // We use the _cultureData to get the data for our object private bool _isReadOnly; private CompareInfo _compareInfo; private TextInfo _textInfo; internal NumberFormatInfo numInfo; internal DateTimeFormatInfo dateTimeInfo; private Calendar _calendar; // // The CultureData instance that we are going to read data from. // For supported culture, this will be the CultureData instance that read data from mscorlib assembly. // For customized culture, this will be the CultureData instance that read data from user customized culture binary file. // internal CultureData _cultureData; internal bool _isInherited; private CultureInfo m_consoleFallbackCulture; // Names are confusing. Here are 3 names we have: // // new CultureInfo() m_name _nonSortName _sortName // en-US en-US en-US en-US // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) // en en // // Note that in Silverlight we ask the OS for the text and sort behavior, so the // textinfo and compareinfo names are the same as the name // Note that the name used to be serialized for Everett; it is now serialized // because alernate sorts can have alternate names. // This has a de-DE, de-DE_phoneb or fj-FJ style name internal string m_name; // This will hold the non sorting name to be returned from CultureInfo.Name property. // This has a de-DE style name even for de-DE_phoneb type cultures private string _nonSortName; // This will hold the sorting name to be returned from CultureInfo.SortName property. // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. // Otherwise its the sort name, ie: de-DE or de-DE_phoneb private string _sortName; //--------------------------------------------------------------------// // // Static data members // //--------------------------------------------------------------------// //Get the current user default culture. This one is almost always used, so we create it by default. private static volatile CultureInfo s_userDefaultCulture; // // All of the following will be created on demand. // // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. //The Invariant culture; private static volatile CultureInfo s_InvariantCultureInfo; //These are defaults that we use if a thread has not opted into having an explicit culture private static volatile CultureInfo s_DefaultThreadCurrentUICulture; private static volatile CultureInfo s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo s_currentThreadCulture; [ThreadStatic] private static CultureInfo s_currentThreadUICulture; private static readonly Lock s_lock = new Lock(); private static volatile LowLevelDictionary<string, CultureInfo> s_NameCachedCultures; private static volatile LowLevelDictionary<int, CultureInfo> s_LcidCachedCultures; //The parent culture. private CultureInfo _parent; // LOCALE constants of interest to us internally and privately for LCID functions // (ie: avoid using these and use names if possible) internal const int LOCALE_NEUTRAL = 0x0000; private const int LOCALE_USER_DEFAULT = 0x0400; private const int LOCALE_SYSTEM_DEFAULT = 0x0800; internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; internal const int LOCALE_INVARIANT = 0x007F; // // The CultureData instance that reads the data provided by our CultureData class. // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. private static readonly bool s_init = Init(); private static bool Init() { if (s_InvariantCultureInfo == null) { CultureInfo temp = new CultureInfo("", false); temp._isReadOnly = true; s_InvariantCultureInfo = temp; } s_userDefaultCulture = GetUserDefaultCulture(); return true; } //////////////////////////////////////////////////////////////////////// // // CultureInfo Constructors // //////////////////////////////////////////////////////////////////////// public CultureInfo(String name) : this(name, true) { } public CultureInfo(String name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException(nameof(name), SR.ArgumentNull_String); } // Get our data providing record this._cultureData = CultureData.GetCultureData(name, useUserOverride); if (this._cultureData == null) throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); this.m_name = this._cultureData.CultureName; this._isInherited = !this.EETypePtr.FastEquals(EETypePtr.EETypePtrOf<CultureInfo>()); } public CultureInfo(int culture) : this(culture, true) { } public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); InitializeFromCultureId(culture, useUserOverride); } private void InitializeFromCultureId(int culture, bool useUserOverride) { switch (culture) { case LOCALE_CUSTOM_DEFAULT: case LOCALE_SYSTEM_DEFAULT: case LOCALE_NEUTRAL: case LOCALE_USER_DEFAULT: case LOCALE_CUSTOM_UNSPECIFIED: // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); default: // Now see if this LCID is supported in the system default CultureData table. _cultureData = CultureData.GetCultureData(culture, useUserOverride); break; } _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo)); m_name = _cultureData.CultureName; } // Constructor called by SQL Server's special munged culture - creates a culture with // a TextInfo and CompareInfo that come from a supplied alternate source. This object // is ALWAYS read-only. // Note that we really cannot use an LCID version of this override as the cached // name we create for it has to include both names, and the logic for this is in // the GetCultureInfo override *only*. internal CultureInfo(String cultureName, String textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } Contract.EndContractBlock(); _cultureData = CultureData.GetCultureData(cultureName, false); if (_cultureData == null) throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported); m_name = _cultureData.CultureName; CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName); _compareInfo = altCulture.CompareInfo; _textInfo = altCulture.TextInfo; } // We do this to try to return the system UI language and the default user languages // This method will fallback if this fails (like Invariant) // // TODO: It would appear that this is only ever called with userOveride = true // and this method only has one caller. Can we fold it into the caller? private static CultureInfo GetCultureByName(String name, bool userOverride) { CultureInfo ci = null; // Try to get our culture try { ci = userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name); } catch (ArgumentException) { } if (ci == null) { ci = InvariantCulture; } return ci; } // // Return a specific culture. A tad irrelevent now since we always return valid data // for neutral locales. // // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647, // if we can't find a bigger name. That doesn't help with things like "zh" though, so // the approach is of questionable value // public static CultureInfo CreateSpecificCulture(String name) { Contract.Ensures(Contract.Result<CultureInfo>() != null); CultureInfo culture; try { culture = new CultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. int idx; culture = null; for (idx = 0; idx < name.Length; idx++) { if ('-' == name[idx]) { try { culture = new CultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!(culture.IsNeutralCulture)) { return culture; } return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE)); } // // // // Return a specific culture. A tad irrelevent now since we always return valid data // // for neutral locales. // // // // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647, // // if we can't find a bigger name. That doesn't help with things like "zh" though, so // // the approach is of questionable value // // internal static bool VerifyCultureName(String cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, // so we should check against CultureInfo.Name. for (int i = 0; i < cultureName.Length; i++) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { //If we have an instance of one of our CultureInfos, the user can't have changed the //name and we know that all names are valid in files. if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } //////////////////////////////////////////////////////////////////////// // // CurrentCulture // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// // // We use the following order to return CurrentCulture and CurrentUICulture // o Use WinRT to return the current user profile language // o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture // o use thread culture if the user already set one using DefaultThreadCurrentCulture // or DefaultThreadCurrentUICulture // o Use NLS default user culture // o Use NLS default system culture // o Use Invariant culture // public static CultureInfo CurrentCulture { get { CultureInfo ci = GetUserDefaultCultureCacheOverride(); if (ci != null) { return ci; } if (s_currentThreadCulture != null) { return s_currentThreadCulture; } ci = s_DefaultThreadCurrentCulture; if (ci != null) { return ci; } // if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize if (s_userDefaultCulture == null) { Init(); } Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif s_currentThreadCulture = value; } } public static CultureInfo CurrentUICulture { get { CultureInfo ci = GetUserDefaultCultureCacheOverride(); if (ci != null) { return ci; } if (s_currentThreadUICulture != null) { return s_currentThreadUICulture; } ci = s_DefaultThreadCurrentUICulture; if (ci != null) { return ci; } // if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize if (s_userDefaultCulture == null) { Init(); } Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif s_currentThreadUICulture = value; } } public static CultureInfo InstalledUICulture { get { Contract.Ensures(Contract.Result<CultureInfo>() != null); if (s_userDefaultCulture == null) { Init(); } Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null"); return s_userDefaultCulture; } } public static CultureInfo DefaultThreadCurrentCulture { get { return s_DefaultThreadCurrentCulture; } set { // If you add pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentCulture.set. s_DefaultThreadCurrentCulture = value; } } public static CultureInfo DefaultThreadCurrentUICulture { get { return s_DefaultThreadCurrentUICulture; } set { //If they're trying to use a Culture with a name that we can't use in resource lookup, //don't even let them set it on the thread. // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. if (value != null) { CultureInfo.VerifyCultureName(value, true); } s_DefaultThreadCurrentUICulture = value; } } //////////////////////////////////////////////////////////////////////// // // InvariantCulture // // This instance provides methods, for example for casing and sorting, // that are independent of the system and current user settings. It // should be used only by processes such as some system services that // require such invariant results (eg. file systems). In general, // the results are not linguistically correct and do not match any // culture info. // //////////////////////////////////////////////////////////////////////// public static CultureInfo InvariantCulture { get { return (s_InvariantCultureInfo); } } //////////////////////////////////////////////////////////////////////// // // Parent // // Return the parent CultureInfo for the current instance. // //////////////////////////////////////////////////////////////////////// public virtual CultureInfo Parent { get { if (null == _parent) { CultureInfo culture = null; try { string parentName = this._cultureData.SPARENT; if (String.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } else { culture = new CultureInfo(parentName, this._cultureData.UseUserOverride); } } catch (ArgumentException) { // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. culture = InvariantCulture; } Interlocked.CompareExchange<CultureInfo>(ref _parent, culture, null); } return _parent; } } public virtual int LCID { get { return (this._cultureData.ILANGUAGE); } } public virtual int KeyboardLayoutId { get { return _cultureData.IINPUTLANGUAGEHANDLE; } } public static CultureInfo[] GetCultures(CultureTypes types) { Contract.Ensures(Contract.Result<CultureInfo[]>() != null); // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return (CultureData.GetCultures(types)); } //////////////////////////////////////////////////////////////////////// // // Name // // Returns the full name of the CultureInfo. The name is in format like // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { // We return non sorting name here. if (_nonSortName == null) { _nonSortName = this._cultureData.SNAME; if (_nonSortName == null) { _nonSortName = String.Empty; } } return _nonSortName; } } // This one has the sort information (ie: de-DE_phoneb) internal String SortName { get { if (_sortName == null) { _sortName = this._cultureData.SCOMPAREINFO; } return _sortName; } } public string IetfLanguageTag { get { Contract.Ensures(Contract.Result<string>() != null); // special case the compatibility cultures switch (this.Name) { case "zh-CHT": return "zh-Hant"; case "zh-CHS": return "zh-Hans"; default: return this.Name; } } } //////////////////////////////////////////////////////////////////////// // // DisplayName // // Returns the full name of the CultureInfo in the localized language. // For example, if the localized language of the runtime is Spanish and the CultureInfo is // US English, "Ingles (Estados Unidos)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { Contract.Ensures(Contract.Result<String>() != null); Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set"); return _cultureData.SLOCALIZEDDISPLAYNAME; } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the full name of the CultureInfo in the native language. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SNATIVEDISPLAYNAME); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the full name of the CultureInfo in English. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SENGDISPLAYNAME); } } // ie: en public virtual String TwoLetterISOLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SISO639LANGNAME); } } // ie: eng public virtual String ThreeLetterISOLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return _cultureData.SISO639LANGNAME2; } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsLanguageName // // Returns the 3 letter windows language name for the current instance. eg: "ENU" // The ISO names are much preferred // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return _cultureData.SABBREVLANGNAME; } } //////////////////////////////////////////////////////////////////////// // // CompareInfo Read-Only Property // // Gets the CompareInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual CompareInfo CompareInfo { get { if (_compareInfo == null) { // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture CompareInfo temp = UseUserOverride ? GetCultureInfo(this.m_name).CompareInfo : new CompareInfo(this); if (OkayToCacheClassWithCompatibilityBehavior) { _compareInfo = temp; } else { return temp; } } return (_compareInfo); } } private static bool OkayToCacheClassWithCompatibilityBehavior { get { return true; } } //////////////////////////////////////////////////////////////////////// // // TextInfo // // Gets the TextInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual TextInfo TextInfo { get { if (_textInfo == null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(this._cultureData); tempTextInfo.SetReadOnlyState(_isReadOnly); if (OkayToCacheClassWithCompatibilityBehavior) { _textInfo = tempTextInfo; } else { return tempTextInfo; } } return (_textInfo); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { if (Object.ReferenceEquals(this, value)) return true; CultureInfo that = value as CultureInfo; if (that != null) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo)); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the CultureInfo, // eg. "de-DE_phoneb", "en-US", or "fj-FJ". // //////////////////////////////////////////////////////////////////////// public override String ToString() { return m_name; } public virtual Object GetFormat(Type formatType) { if (formatType == typeof(NumberFormatInfo)) return (NumberFormat); if (formatType == typeof(DateTimeFormatInfo)) return (DateTimeFormat); return (null); } public virtual bool IsNeutralCulture { get { return this._cultureData.IsNeutralCulture; } } public CultureTypes CultureTypes { get { CultureTypes types = 0; if (_cultureData.IsNeutralCulture) types |= CultureTypes.NeutralCultures; else types |= CultureTypes.SpecificCultures; types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0; // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete #pragma warning disable 618 types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0; #pragma warning restore 618 types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0; types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0; return types; } } public virtual NumberFormatInfo NumberFormat { get { if (numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(this._cultureData); temp.isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref numInfo, temp, null); } return (numInfo); } set { if (value == null) { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj); } VerifyWritable(); numInfo = value; } } //////////////////////////////////////////////////////////////////////// // // GetDateTimeFormatInfo // // Create a DateTimeFormatInfo, and fill in the properties according to // the CultureID. // //////////////////////////////////////////////////////////////////////// public virtual DateTimeFormatInfo DateTimeFormat { get { if (dateTimeInfo == null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(this._cultureData, this.Calendar); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref dateTimeInfo, temp, null); } return (dateTimeInfo); } set { if (value == null) { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj); } VerifyWritable(); dateTimeInfo = value; } } public void ClearCachedData() { s_userDefaultCulture = null; RegionInfo.s_currentRegionInfo = null; #pragma warning disable 0618 // disable the obsolete warning TimeZone.ResetTimeZone(); #pragma warning restore 0618 TimeZoneInfo.ClearCachedData(); s_LcidCachedCultures = null; s_NameCachedCultures = null; CultureData.ClearCachedData(); } /*=================================GetCalendarInstance========================== **Action: Map a Win32 CALID to an instance of supported calendar. **Returns: An instance of calendar. **Arguments: calType The Win32 CALID **Exceptions: ** Shouldn't throw exception since the calType value is from our data table or from Win32 registry. ** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar. ============================================================================*/ internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return (new GregorianCalendar()); } return GetCalendarInstanceRare(calType); } //This function exists as a shortcut to prevent us from loading all of the non-gregorian //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(CalendarId calType) { Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar return (new GregorianCalendar((GregorianCalendarTypes)calType)); case CalendarId.TAIWAN: // Taiwan Era calendar return (new TaiwanCalendar()); case CalendarId.JAPAN: // Japanese Emperor Era calendar return (new JapaneseCalendar()); case CalendarId.KOREA: // Korean Tangun Era calendar return (new KoreanCalendar()); case CalendarId.THAI: // Thai calendar return (new ThaiBuddhistCalendar()); case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar return (new HijriCalendar()); case CalendarId.HEBREW: // Hebrew (Lunar) calendar return (new HebrewCalendar()); case CalendarId.UMALQURA: return (new UmAlQuraCalendar()); case CalendarId.PERSIAN: return (new PersianCalendar()); } return (new GregorianCalendar()); } /*=================================Calendar========================== **Action: Return/set the default calendar used by this culture. ** This value can be overridden by regional option if this is a current culture. **Returns: **Arguments: **Exceptions: ** ArgumentNull_Obj if the set value is null. ============================================================================*/ public virtual Calendar Calendar { get { if (_calendar == null) { Debug.Assert(this._cultureData.CalendarIds.Length > 0, "this._cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = this._cultureData.DefaultCalendar; System.Threading.Interlocked.MemoryBarrier(); newObj.SetReadOnlyState(_isReadOnly); _calendar = newObj; } return (_calendar); } } /*=================================OptionCalendars========================== **Action: Return an array of the optional calendar for this culture. **Returns: an array of Calendar. **Arguments: **Exceptions: ============================================================================*/ public virtual Calendar[] OptionalCalendars { get { Contract.Ensures(Contract.Result<Calendar[]>() != null); // // This property always returns a new copy of the calendar array. // CalendarId[] calID = this._cultureData.CalendarIds; Calendar[] cals = new Calendar[calID.Length]; for (int i = 0; i < cals.Length; i++) { cals[i] = GetCalendarInstance(calID[i]); } return (cals); } } public bool UseUserOverride { get { return _cultureData.UseUserOverride; } } public CultureInfo GetConsoleFallbackUICulture() { Contract.Ensures(Contract.Result<CultureInfo>() != null); CultureInfo temp = m_consoleFallbackCulture; if (temp == null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; m_consoleFallbackCulture = temp; } return (temp); } public virtual Object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { if (this.dateTimeInfo != null) { ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone(); } if (this.numInfo != null) { ci.numInfo = (NumberFormatInfo)this.numInfo.Clone(); } } else { ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } if (_textInfo != null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } if (_calendar != null) { ci._calendar = (Calendar)_calendar.Clone(); } return (ci); } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException(nameof(ci)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); if (ci.IsReadOnly) { return (ci); } CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone()); if (!ci.IsNeutralCulture) { //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { if (ci.dateTimeInfo != null) { newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo); } if (ci.numInfo != null) { newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo); } } else { newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } // Don't set the read-only flag too early. // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. newInfo._isReadOnly = true; return (newInfo); } public bool IsReadOnly { get { return (_isReadOnly); } } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } // For resource lookup, we consider a culture the invariant culture by name equality. // We perform this check frequently during resource lookup, so adding a property for // improved readability. internal bool HasInvariantCultureName { get { return Name == CultureInfo.InvariantCulture.Name; } } // Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name. // If lcid is -1, use the altName and create one of those special SQL cultures. internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName) { // retval is our return value. CultureInfo retval; // Temporary hashtable for the names. LowLevelDictionary<string, CultureInfo> tempNameHT = s_NameCachedCultures; if (name != null) { name = CultureData.AnsiToLower(name); } if (altName != null) { altName = CultureData.AnsiToLower(altName); } // We expect the same result for both hashtables, but will test individually for added safety. if (tempNameHT == null) { tempNameHT = new LowLevelDictionary<string, CultureInfo>(); } else { // If we are called by name, check if the object exists in the hashtable. If so, return it. if (lcid == -1 || lcid == 0) { bool ret; using (LockHolder.Hold(s_lock)) { ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval); } if (ret && retval != null) { return retval; } } } // Next, the Lcid table. LowLevelDictionary<int, CultureInfo> tempLcidHT = s_LcidCachedCultures; if (tempLcidHT == null) { // Case insensitive is not an issue here, save the constructor call. tempLcidHT = new LowLevelDictionary<int, CultureInfo>(); } else { // If we were called by Lcid, check if the object exists in the table. If so, return it. if (lcid > 0) { bool ret; using (LockHolder.Hold(s_lock)) { ret = tempLcidHT.TryGetValue(lcid, out retval); } if (ret && retval != null) { return retval; } } } // We now have two temporary hashtables and the desired object was not found. // We'll construct it. We catch any exceptions from the constructor call and return null. try { switch (lcid) { case -1: // call the private constructor retval = new CultureInfo(name, altName); break; case 0: retval = new CultureInfo(name, false); break; default: retval = new CultureInfo(lcid, false); break; } } catch (ArgumentException) { return null; } // Set it to read-only retval._isReadOnly = true; if (lcid == -1) { using (LockHolder.Hold(s_lock)) { // This new culture will be added only to the name hash table. tempNameHT[name + '\xfffd' + altName] = retval; } // when lcid == -1 then TextInfo object is already get created and we need to set it as read only. retval.TextInfo.SetReadOnlyState(true); } else if (lcid == 0) { // Remember our name (as constructed). Do NOT use alternate sort name versions because // we have internal state representing the sort. (So someone would get the wrong cached version) string newName = CultureData.AnsiToLower(retval.m_name); // We add this new culture info object to both tables. using (LockHolder.Hold(s_lock)) { tempNameHT[newName] = retval; } } else { using (LockHolder.Hold(s_lock)) { tempLcidHT[lcid] = retval; } } // Copy the two hashtables to the corresponding member variables. This will potentially overwrite // new tables simultaneously created by a new thread, but maximizes thread safety. if (-1 != lcid) { // Only when we modify the lcid hash table, is there a need to overwrite. s_LcidCachedCultures = tempLcidHT; } s_NameCachedCultures = tempNameHT; // Finally, return our new CultureInfo object. return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (LCID version)... use named version public static CultureInfo GetCultureInfo(int culture) { // Must check for -1 now since the helper function uses the value to signal // the altCulture code path for SQL Server. // Also check for zero as this would fail trying to add as a key to the hash. if (culture <= 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(culture, null, null); if (null == retval) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (Named version) public static CultureInfo GetCultureInfo(string name) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } CultureInfo retval = GetCultureInfoHelper(0, name, null); if (retval == null) { throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). public static CultureInfo GetCultureInfo(string name, string altName) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } if (altName == null) { throw new ArgumentNullException(nameof(altName)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) { throw new CultureNotFoundException("name or altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } return retval; } // This function is deprecated, we don't like it public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { Contract.Ensures(Contract.Result<CultureInfo>() != null); // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo ci = GetCultureInfo(name); // Disallow alt sorts and es-es_TS if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return ci; } } }
// ============================================================= // BytesRoad.NetSuit : A free network library for .NET platform // ============================================================= // // Copyright (C) 2004-2005 BytesRoad Software // // Project Info: http://www.bytesroad.com/NetSuit/ // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // ========================================================================== // Changed by: NRPG using System; using System.Net; using System.Net.Sockets; using BytesRoad.Net.Sockets.Advanced; namespace BytesRoad.Net.Sockets { /// <summary> /// Summary description for Socket_None. /// </summary> internal class Socket_None : SocketBase { #region Async classes class Bind_SO : AsyncResultBase { internal Bind_SO(AsyncCallback cb, object state) : base(cb, state) { } } class Connect_SO : AsyncResultBase { int _port; internal Connect_SO(int port, AsyncCallback cb, object state) : base(cb, state) { _port = port; } internal int Port { get { return _port;} } } #endregion internal Socket_None() { } internal Socket_None(Socket systemSocket) : base(systemSocket) { } #region Attributes override internal ProxyType ProxyType { get { return ProxyType.None; } } override internal EndPoint LocalEndPoint { get { return _socket.LocalEndPoint; } } override internal EndPoint RemoteEndPoint { get { return _socket.RemoteEndPoint; } } #endregion #region Helpers #endregion #region Accept functions (overriden) override internal SocketBase Accept() { CheckDisposed(); return new Socket_None(_socket.Accept()); } override internal IAsyncResult BeginAccept(AsyncCallback callback, object state) { CheckDisposed(); return _socket.BeginAccept(callback, state); } override internal SocketBase EndAccept(IAsyncResult asyncResult) { return new Socket_None(_socket.EndAccept(asyncResult)); } #endregion #region Connect functions (overriden) override internal void Connect(EndPoint remoteEP) { CheckDisposed(); _socket.Connect(remoteEP); } override internal IAsyncResult BeginConnect( EndPoint remoteEP, AsyncCallback callback, object state) { CheckDisposed(); Connect_SO stateObj = null; SetProgress(true); try { stateObj = new Connect_SO(-1, callback, state); _socket.BeginConnect( remoteEP, new AsyncCallback(Connect_End), stateObj); } catch(Exception e) { SetProgress(false); throw e; } return stateObj; } override internal IAsyncResult BeginConnect( string hostName, int port, AsyncCallback callback, object state) { CheckDisposed(); SetProgress(true); Connect_SO stateObj = null; try { stateObj = new Connect_SO(port, callback, state); Dns.BeginGetHostEntry(hostName, new AsyncCallback(GetHost_End), stateObj); } catch(Exception e) { SetProgress(false); throw e; } return stateObj; } void GetHost_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); IPHostEntry host = Dns.EndGetHostEntry(ar); if(null == host) throw new SocketException(SockErrors.WSAHOST_NOT_FOUND); // throw new HostNotFoundException("Unable to resolve host name."); EndPoint remoteEP = ConstructEndPoint(host, stateObj.Port); _socket.BeginConnect( remoteEP, new AsyncCallback(Connect_End), stateObj); } catch(Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } } void Connect_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); _socket.EndConnect(ar); } catch(Exception e) { stateObj.Exception = e; } stateObj.SetCompleted(); } override internal void EndConnect(IAsyncResult asyncResult) { VerifyAsyncResult(asyncResult, typeof(Connect_SO), "EndConnect"); HandleAsyncEnd(asyncResult, true); } #endregion #region Bind functions (overriden) override internal void Bind(SocketBase baseSocket) { CheckDisposed(); IPEndPoint ep = (IPEndPoint)baseSocket.SystemSocket.LocalEndPoint; ep.Port = 0; _socket.Bind(ep); } override internal IAsyncResult BeginBind( SocketBase baseSocket, AsyncCallback callback, object state) { CheckDisposed(); Bind_SO stateObj = new Bind_SO(callback, state); try { IPEndPoint ep = (IPEndPoint)baseSocket.SystemSocket.LocalEndPoint; ep.Port = 0; _socket.Bind(ep); } catch(Exception e) { stateObj.Exception = e; } stateObj.SetCompleted(); return stateObj; } override internal void EndBind(IAsyncResult ar) { VerifyAsyncResult(ar, typeof(Bind_SO), "EndBind"); HandleAsyncEnd(ar, false); } #endregion #region Listen function (overriden) override internal void Listen(int backlog) { CheckDisposed(); _socket.Listen(backlog); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow.Commands { internal sealed class Commands : IInteractiveWindowCommands { private const string _commandSeparator = ", "; private readonly Dictionary<string, IInteractiveWindowCommand> _commands; private readonly int _maxCommandNameLength; private readonly IInteractiveWindow _window; private readonly IContentType _commandContentType; private readonly IStandardClassificationService _classificationRegistry; private IContentType _languageContentType; private ITextBuffer _previousBuffer; public string CommandPrefix { get; set; } public bool InCommand { get { return _window.CurrentLanguageBuffer.ContentType == _commandContentType; } } internal Commands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null) { CommandPrefix = prefix; _window = window; Dictionary<string, IInteractiveWindowCommand> commandsDict = new Dictionary<string, IInteractiveWindowCommand>(); foreach (var command in commands) { int length = 0; foreach (var name in command.Names) { if (commandsDict.ContainsKey(name)) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(_commandSeparator, command.Names))); } if (length != 0) { length += _commandSeparator.Length; } // plus the length of `#` for display purpose length += name.Length + 1; commandsDict[name] = command; } if (length == 0) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name)); } _maxCommandNameLength = Math.Max(_maxCommandNameLength, length); } _commands = commandsDict; _classificationRegistry = classificationRegistry; if (contentTypeRegistry != null) { _commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } if (window != null) { window.SubmissionBufferAdded += Window_SubmissionBufferAdded; window.Properties[typeof(IInteractiveWindowCommands)] = this; } } private void Window_SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) { if (_previousBuffer != null) { _previousBuffer.Changed -= NewBufferChanged; } _languageContentType = e.NewBuffer.ContentType; e.NewBuffer.Changed += NewBufferChanged; _previousBuffer = e.NewBuffer; } private void NewBufferChanged(object sender, TextContentChangedEventArgs e) { bool isCommand = IsCommand(e.After.GetExtent()); ITextBuffer buffer = e.After.TextBuffer; IContentType contentType = buffer.ContentType; IContentType newContentType = null; if (contentType == _languageContentType) { if (isCommand) { newContentType = _commandContentType; } } else { if (!isCommand) { newContentType = _languageContentType; } } if (newContentType != null) { buffer.ChangeContentType(newContentType, editTag: null); } } internal bool IsCommand(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; return TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan) != null; } internal IInteractiveWindowCommand TryParseCommand(SnapshotSpan span, out SnapshotSpan prefixSpan, out SnapshotSpan commandSpan, out SnapshotSpan argumentsSpan) { string prefix = CommandPrefix; SnapshotSpan trimmed = span.TrimStart(); if (!trimmed.StartsWith(prefix)) { prefixSpan = commandSpan = argumentsSpan = default(SnapshotSpan); return null; } prefixSpan = trimmed.SubSpan(0, prefix.Length); var nameAndArgs = trimmed.SubSpan(prefix.Length).TrimStart(); SnapshotPoint nameEnd = nameAndArgs.IndexOfAnyWhiteSpace() ?? span.End; commandSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameAndArgs.Start.Position, nameEnd.Position)); argumentsSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameEnd.Position, span.End.Position)).Trim(); return this[commandSpan.GetText()]; } public IInteractiveWindowCommand this[string name] { get { IInteractiveWindowCommand command; _commands.TryGetValue(name, out command); return command; } } public IEnumerable<IInteractiveWindowCommand> GetCommands() { return _commands.Values; } internal IEnumerable<string> Help() { string format = "{0,-" + _maxCommandNameLength + "} {1}"; return _commands.GroupBy(entry => entry.Value). Select(group => string.Format(format, string.Join(_commandSeparator, group.Key.Names.Select(s => "#" + s)), group.Key.Description)). OrderBy(line => line); } public IEnumerable<ClassificationSpan> Classify(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span.Snapshot.GetExtent(), out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { yield break; } if (span.OverlapsWith(prefixSpan)) { yield return Classification(span.Snapshot, prefixSpan, _classificationRegistry.Keyword); } if (span.OverlapsWith(commandSpan)) { yield return Classification(span.Snapshot, commandSpan, _classificationRegistry.Keyword); } if (argumentsSpan.Length > 0) { foreach (var classifiedSpan in command.ClassifyArguments(span.Snapshot, argumentsSpan.Span, span.Span)) { yield return classifiedSpan; } } } private ClassificationSpan Classification(ITextSnapshot snapshot, Span span, IClassificationType classificationType) { return new ClassificationSpan(new SnapshotSpan(snapshot, span), classificationType); } /// <returns> /// Null if parsing fails, the result of execution otherwise. /// </returns> public Task<ExecutionResult> TryExecuteCommand() { var span = _window.CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { return null; } return ExecuteCommandAsync(command, argumentsSpan.GetText()); } private async Task<ExecutionResult> ExecuteCommandAsync(IInteractiveWindowCommand command, string arguments) { try { return await command.Execute(_window, arguments).ConfigureAwait(false); } catch (Exception e) { _window.ErrorOutputWriter.WriteLine(InteractiveWindowResources.CommandFailed, command.Names.First(), e.Message); return ExecutionResult.Failure; } } private const string HelpIndent = " "; private static readonly string[] s_shortcutDescriptions = new[] { "Enter " + InteractiveWindowResources.EnterHelp, "Ctrl-Enter " + InteractiveWindowResources.CtrlEnterHelp1, " " + InteractiveWindowResources.CtrlEnterHelp1, "Shift-Enter " + InteractiveWindowResources.ShiftEnterHelp, "Escape " + InteractiveWindowResources.EscapeHelp, "Alt-UpArrow " + InteractiveWindowResources.AltUpArrowHelp, "Alt-DownArrow " + InteractiveWindowResources.AltDownArrowHelp, "Ctrl-Alt-UpArrow " + InteractiveWindowResources.CtrlAltUpArrowHelp, "Ctrl-Alt-DownArrow " + InteractiveWindowResources.CtrlAltDownArrowHelp, "UpArrow " + InteractiveWindowResources.UpArrowHelp1, " " + InteractiveWindowResources.UpArrowHelp2, "DownArrow " + InteractiveWindowResources.DownArrowHelp1, " " + InteractiveWindowResources.DownArrowHelp2, "Ctrl-K, Ctrl-Enter " + InteractiveWindowResources.CtrlKCtrlEnterHelp, "Ctrl-E, Ctrl-Enter " + InteractiveWindowResources.CtrlECtrlEnterHelp, "Ctrl-A " + InteractiveWindowResources.CtrlAHelp, }; private static readonly string[] s_CSVBScriptDirectives = new[] { "#r " + InteractiveWindowResources.RefHelp, "#load " + InteractiveWindowResources.LoadHelp }; public void DisplayHelp() { _window.WriteLine(InteractiveWindowResources.KeyboardShortcuts); foreach (var line in s_shortcutDescriptions) { _window.Write(HelpIndent); _window.WriteLine(line); } _window.WriteLine(InteractiveWindowResources.ReplCommands); foreach (var line in Help()) { _window.Write(HelpIndent); _window.WriteLine(line); } // Hack: Display script directives only in CS/VB interactive window // TODO: https://github.com/dotnet/roslyn/issues/6441 var evaluatorTypeName = _window.Evaluator.GetType().Name; if (evaluatorTypeName == "CSharpInteractiveEvaluator" || evaluatorTypeName == "VisualBasicInteractiveEvaluator") { _window.WriteLine(InteractiveWindowResources.CSVBScriptDirectives); foreach (var line in s_CSVBScriptDirectives) { _window.Write(HelpIndent); _window.WriteLine(line); } } } public void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails) { if (displayDetails) { writer.WriteLine(command.Description); writer.WriteLine(string.Empty); } writer.WriteLine(InteractiveWindowResources.Usage); writer.Write(HelpIndent); writer.Write(CommandPrefix); writer.Write(string.Join(_commandSeparator + CommandPrefix, command.Names)); string commandLine = command.CommandLine; if (commandLine != null) { writer.Write(" "); writer.Write(commandLine); } if (displayDetails) { writer.WriteLine(string.Empty); var paramsDesc = command.ParametersDescription; if (paramsDesc != null && paramsDesc.Any()) { writer.WriteLine(string.Empty); writer.WriteLine(InteractiveWindowResources.Parameters); int maxParamNameLength = paramsDesc.Max(entry => entry.Key.Length); string paramHelpLineFormat = HelpIndent + "{0,-" + maxParamNameLength + "} {1}"; foreach (var paramDesc in paramsDesc) { writer.WriteLine(string.Format(paramHelpLineFormat, paramDesc.Key, paramDesc.Value)); } } IEnumerable<string> details = command.DetailedDescription; if (details != null && details.Any()) { writer.WriteLine(string.Empty); foreach (var line in details) { writer.WriteLine(line); } } } } public void DisplayCommandHelp(IInteractiveWindowCommand command) { DisplayCommandUsage(command, _window.OutputWriter, displayDetails: true); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace FlatRedBall.Graphics.PostProcessing { #region XML Docs /// <summary> /// Post processing to implement directional blur. /// </summary> #endregion public class DirectionalBlur : PostProcessingEffectBase { #region Fields #region XML Docs /// <summary> /// The number of samples used in the blur filtering (static for now) /// </summary> #endregion private int mBlurSampleCount = 9; private float mBlurStandardDeviation = 2.0f; private float mSampleScale = 30.0f; private float mAngle = 0f; private string mTechnique = "BlurHi"; private EffectQuality mBlurQuality = EffectQuality.High; private float[] mSampleWeights; private Vector2[] mSampleOffsets; #endregion #region Properties #region XML Docs /// <summary> /// Controls the strength of the Gaussian blur /// (the standard deviation of the normal curve used for sampling nearby coordinates) /// </summary> #endregion public float GaussianStrength { get { return mBlurStandardDeviation; } set { if (mBlurStandardDeviation != value) { mBlurStandardDeviation = value; SetSampleParameters(); } } } #region XML Docs /// <summary> /// Gets or sets the length of the directional blur (in pixels) /// </summary> #endregion public float Length { get { return mSampleScale; } set { if (mSampleScale != value) { mSampleScale = value; SetSampleParameters(); } } } #region XML Docs /// <summary> /// Gets or sets the angle of the directional blur /// </summary> #endregion public float Angle { get { return mAngle; } set { mAngle = value; SetSampleParameters(); } } #region XML Docs /// <summary> /// Gets or sets the quality of the blur /// </summary> #endregion public EffectQuality Quality { get { return mBlurQuality; } set { if (mBlurQuality != value) { mBlurQuality = value; #region Set technique names switch (mBlurQuality) { case EffectQuality.High: mTechnique = "BlurHi"; mBlurSampleCount = 9; break; case EffectQuality.Medium: mTechnique = "BlurMed"; mBlurSampleCount = 7; break; case EffectQuality.Low: mTechnique = "BlurLow"; mBlurSampleCount = 5; break; default: mTechnique = "BlurHi"; mBlurSampleCount = 9; break; } #endregion // Set the effect technique mEffect.CurrentTechnique = mEffect.Techniques[mTechnique]; // calculate new sample values SetSampleParameters(); } } } #endregion #region Constuctor #region XML Docs /// <summary> /// Internal Constructor (so this class can't be instantiated externally) /// </summary> #endregion internal DirectionalBlur() { } #endregion #region Public Methods #region XML Docs /// <summary> /// Reports this effect's name as a string /// </summary> /// <returns>The effect's name as a string</returns> #endregion public override string ToString() { return "DirectionalBlur"; } #endregion #region Internal Methods #region XML Docs /// <summary> /// Loads the effect /// </summary> #endregion public override void InitializeEffect() { // Load the effect // If modifying the shaders uncomment the following file: //mEffect = FlatRedBallServices.Load<Effect>(@"Assets\Shaders\PostProcessing\DirectionalBlur"); // Otherwise, keep the following line uncommented so the .xnb files in the // resources are used. mEffect = FlatRedBallServices.mResourceContentManager.Load<Effect>("DirectionalBlur"); // Set the sampling parameters SetSampleParameters(); // Call the base initialization method base.InitializeEffect(); } #region XML Docs /// <summary> /// Calculates and sets the sampling parameters in the shader /// </summary> #endregion internal void SetSampleParameters() { float[] sampleWeights = new float[mBlurSampleCount]; Vector2[] sampleOffsets = new Vector2[mBlurSampleCount]; Vector2 pixelSize = PostProcessingManager.PixelSize; // Direction is negated on y axis to account for // texture coordinate y values being inverted with respect to normal values // Direction is then inverted so it blurs in the direction of the angle specified, // instead of sampling in that direction (which results in a blur in the opposite // direction). // This results in only the x value being negated. Vector2 direction = new Vector2( -(float)System.Math.Cos((double)mAngle), (float)System.Math.Sin((double)mAngle)); float stepLength = mSampleScale / (float)mBlurSampleCount; // Calculate values using normal (gaussian) distribution float weightSum = 0f; for (int i = 0; i < mBlurSampleCount; i++) { // Get weight sampleWeights[i] = 1f / (((float)System.Math.Sqrt(2.0 * System.Math.PI) / mBlurStandardDeviation) * (float)System.Math.Pow(System.Math.E, System.Math.Pow((double)i, 2.0) / (2.0 * System.Math.Pow((double)mBlurStandardDeviation, 2.0)))); // Add to total weight value (for normalization) weightSum += sampleWeights[i]; // Get offset sampleOffsets[i] = (((float)i * stepLength * direction) + (Vector2.One * .5f)) * pixelSize; } // Normalize sample weights for (int i = 0; i < sampleWeights.Length; i++) { sampleWeights[i] /= weightSum; } // Set parameters in shader mSampleWeights = sampleWeights; mSampleOffsets = sampleOffsets; } protected override void SetEffectParameters(Camera camera) { mEffect.Parameters["sampleWeights"].SetValue(mSampleWeights); mEffect.Parameters["sampleOffsets"].SetValue(mSampleOffsets); } #region XML Docs /// <summary> /// Draws the effect /// </summary> /// <param name="screenTexture">The screen texture</param> /// <param name="baseRectangle">The rectangle to draw to</param> /// <param name="clearColor">The background color</param> #endregion public override void Draw( Camera camera, ref Texture2D screenTexture, ref Rectangle baseRectangle, Color clearColor) { // Set the effect parameters SetEffectParameters(camera); #region Directional Blur // Draw the horizontal pass DrawToTexture(camera, ref mTexture, clearColor, ref screenTexture, ref baseRectangle); #endregion } #endregion } }
/* * Copyright (c) 2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.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. */ using System; using System.Runtime.InteropServices; namespace OpenMetaverse { /// <summary> /// An 8-bit color structure including an alpha channel /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Color4 : IComparable<Color4>, IEquatable<Color4> { /// <summary>Red</summary> public float R; /// <summary>Green</summary> public float G; /// <summary>Blue</summary> public float B; /// <summary>Alpha</summary> public float A; #region Constructors /// <summary> /// /// </summary> /// <param name="r"></param> /// <param name="g"></param> /// <param name="b"></param> /// <param name="a"></param> public Color4(byte r, byte g, byte b, byte a) { const float quanta = 1.0f / 255.0f; R = (float)r * quanta; G = (float)g * quanta; B = (float)b * quanta; A = (float)a * quanta; } public Color4(float r, float g, float b, float a) { // Quick check to see if someone is doing something obviously wrong // like using float values from 0.0 - 255.0 if (r > 1f || g > 1f || b > 1f || a > 1f) throw new ArgumentException( String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", r, g, b, a)); // Valid range is from 0.0 to 1.0 R = Utils.Clamp(r, 0f, 1f); G = Utils.Clamp(g, 0f, 1f); B = Utils.Clamp(b, 0f, 1f); A = Utils.Clamp(a, 0f, 1f); } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> public Color4(byte[] byteArray, int pos, bool inverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted); } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> /// <returns>A 16 byte array containing R, G, B, and A</returns> public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted, alphaInverted); } /// <summary> /// Copy constructor /// </summary> /// <param name="color">Color to copy</param> public Color4(Color4 color) { R = color.R; G = color.G; B = color.B; A = color.A; } #endregion Constructors #region Public Methods /// <summary> /// IComparable.CompareTo implementation /// </summary> /// <remarks>Sorting ends up like this: |--Grayscale--||--Color--|. /// Alpha is only used when the colors are otherwise equivalent</remarks> public int CompareTo(Color4 color) { float thisHue = GetHue(); float thatHue = color.GetHue(); if (thisHue < 0f && thatHue < 0f) { // Both monochromatic if (R == color.R) { // Monochromatic and equal, compare alpha return A.CompareTo(color.A); } else { // Compare lightness return R.CompareTo(R); } } else { if (thisHue == thatHue) { // RGB is equal, compare alpha return A.CompareTo(color.A); } else { // Compare hues return thisHue.CompareTo(thatHue); } } } public void FromBytes(byte[] byteArray, int pos, bool inverted) { const float quanta = 1.0f / 255.0f; if (inverted) { R = (float)(255 - byteArray[pos]) * quanta; G = (float)(255 - byteArray[pos + 1]) * quanta; B = (float)(255 - byteArray[pos + 2]) * quanta; A = (float)(255 - byteArray[pos + 3]) * quanta; } else { R = (float)byteArray[pos] * quanta; G = (float)byteArray[pos + 1] * quanta; B = (float)byteArray[pos + 2] * quanta; A = (float)byteArray[pos + 3] * quanta; } } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { FromBytes(byteArray, pos, inverted); if (alphaInverted) A = 1.0f - A; } public byte[] GetBytes() { return GetBytes(false); } public byte[] GetBytes(bool inverted) { byte[] byteArray = new byte[4]; ToBytes(byteArray, 0, inverted); return byteArray; } public byte[] GetFloatBytes() { byte[] bytes = new byte[16]; ToFloatBytes(bytes, 0); return bytes; } /// <summary> /// Writes the raw bytes for this color to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { ToBytes(dest, pos, false); } /// <summary> /// Serializes this color into four bytes in a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 4 bytes before the end of the array</param> /// <param name="inverted">True to invert the output (1.0 becomes 0 /// instead of 255)</param> public void ToBytes(byte[] dest, int pos, bool inverted) { dest[pos + 0] = Utils.FloatToByte(R, 0f, 1f); dest[pos + 1] = Utils.FloatToByte(G, 0f, 1f); dest[pos + 2] = Utils.FloatToByte(B, 0f, 1f); dest[pos + 3] = Utils.FloatToByte(A, 0f, 1f); if (inverted) { dest[pos + 0] = (byte)(255 - dest[pos + 0]); dest[pos + 1] = (byte)(255 - dest[pos + 1]); dest[pos + 2] = (byte)(255 - dest[pos + 2]); dest[pos + 3] = (byte)(255 - dest[pos + 3]); } } /// <summary> /// Writes the raw bytes for this color to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array</param> public void ToFloatBytes(byte[] dest, int pos) { Buffer.BlockCopy(BitConverter.GetBytes(R), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(G), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(B), 0, dest, pos + 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(A), 0, dest, pos + 12, 4); } public float GetHue() { const float HUE_MAX = 360f; float max = Math.Max(Math.Max(R, G), B); float min = Math.Min(Math.Min(R, B), B); if (max == min) { // Achromatic, hue is undefined return -1f; } else if (R == max) { float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return bDelta - gDelta; } else if (G == max) { float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return (HUE_MAX / 3f) + rDelta - bDelta; } else // B == max { float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; } } /// <summary> /// Ensures that values are in range 0-1 /// </summary> public void ClampValues() { if (R < 0f) R = 0f; if (G < 0f) G = 0f; if (B < 0f) B = 0f; if (A < 0f) A = 0f; if (R > 1f) R = 1f; if (G > 1f) G = 1f; if (B > 1f) B = 1f; if (A > 1f) A = 1f; } #endregion Public Methods #region Static Methods /// <summary> /// Create an RGB color from a hue, saturation, value combination /// </summary> /// <param name="hue">Hue</param> /// <param name="saturation">Saturation</param> /// <param name="value">Value</param> /// <returns>An fully opaque RGB color (alpha is 1.0)</returns> public static Color4 FromHSV(double hue, double saturation, double value) { double r = 0d; double g = 0d; double b = 0d; if (saturation == 0d) { // If s is 0, all colors are the same. // This is some flavor of gray. r = value; g = value; b = value; } else { double p; double q; double t; double fractionalSector; int sectorNumber; double sectorPos; // The color wheel consists of 6 sectors. // Figure out which sector you//re in. sectorPos = hue / 60d; sectorNumber = (int)(Math.Floor(sectorPos)); // get the fractional part of the sector. // That is, how many degrees into the sector // are you? fractionalSector = sectorPos - sectorNumber; // Calculate values for the three axes // of the color. p = value * (1d - saturation); q = value * (1d - (saturation * fractionalSector)); t = value * (1d - (saturation * (1d - fractionalSector))); // Assign the fractional colors to r, g, and b // based on the sector the angle is in. switch (sectorNumber) { case 0: r = value; g = t; b = p; break; case 1: r = q; g = value; b = p; break; case 2: r = p; g = value; b = t; break; case 3: r = p; g = q; b = value; break; case 4: r = t; g = p; b = value; break; case 5: r = value; g = p; b = q; break; } } return new Color4((float)r, (float)g, (float)b, 1f); } /// <summary> /// Performs linear interpolation between two colors /// </summary> /// <param name="value1">Color to start at</param> /// <param name="value2">Color to end at</param> /// <param name="amount">Amount to interpolate</param> /// <returns>The interpolated color</returns> public static Color4 Lerp(Color4 value1, Color4 value2, float amount) { return new Color4( Utils.Lerp(value1.R, value2.R, amount), Utils.Lerp(value1.G, value2.G, amount), Utils.Lerp(value1.B, value2.B, amount), Utils.Lerp(value1.A, value2.A, amount)); } #endregion Static Methods #region Overrides public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); } public string ToRGBString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); } public override bool Equals(object obj) { return (obj is Color4) ? this == (Color4)obj : false; } public bool Equals(Color4 other) { return this == other; } public override int GetHashCode() { return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode(); } #endregion Overrides #region Operators public static bool operator ==(Color4 lhs, Color4 rhs) { return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A); } public static bool operator !=(Color4 lhs, Color4 rhs) { return !(lhs == rhs); } public static Color4 operator +(Color4 lhs, Color4 rhs) { lhs.R += rhs.R; lhs.G += rhs.G; lhs.B += rhs.B; lhs.A += rhs.A; lhs.ClampValues(); return lhs; } public static Color4 operator -(Color4 lhs, Color4 rhs) { lhs.R -= rhs.R; lhs.G -= rhs.G; lhs.B -= rhs.B; lhs.A -= rhs.A; lhs.ClampValues(); return lhs; } public static Color4 operator *(Color4 lhs, Color4 rhs) { lhs.R *= rhs.R; lhs.G *= rhs.G; lhs.B *= rhs.B; lhs.A *= rhs.A; lhs.ClampValues(); return lhs; } #endregion Operators /// <summary>A Color4 with zero RGB values and fully opaque (alpha 1.0)</summary> public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f); /// <summary>A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0)</summary> public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Collections.Generic; using System.Management.Automation.Runspaces; using System.Management.Automation.Remoting; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Execution context used for stepping. /// </summary> internal class ExecutionContextForStepping : IDisposable { private ExecutionContext _executionContext; private PSInformationalBuffers _originalInformationalBuffers; private PSHost _originalHost; private ExecutionContextForStepping(ExecutionContext ctxt) { Dbg.Assert(ctxt != null, "ExecutionContext cannot be null."); _executionContext = ctxt; } internal static ExecutionContextForStepping PrepareExecutionContext( ExecutionContext ctxt, PSInformationalBuffers newBuffers, PSHost newHost) { ExecutionContextForStepping result = new ExecutionContextForStepping(ctxt); result._originalInformationalBuffers = ctxt.InternalHost.InternalUI.GetInformationalMessageBuffers(); result._originalHost = ctxt.InternalHost.ExternalHost; ctxt.InternalHost.InternalUI.SetInformationalMessageBuffers(newBuffers); ctxt.InternalHost.SetHostRef(newHost); return result; } // Summary: // Performs application-defined tasks associated with freeing, releasing, or // resetting unmanaged resources. void IDisposable.Dispose() { _executionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(_originalInformationalBuffers); _executionContext.InternalHost.SetHostRef(_originalHost); GC.SuppressFinalize(this); } } /// <summary> /// This class wraps a RunspacePoolInternal object. It is used to function /// as a server side runspacepool. /// </summary> internal class ServerSteppablePipelineDriver { #region Private Data // that is associated with this // powershell driver // associated with this powershell // data structure handler object to handle all // communications with the client // private bool datasent = false; // if the remaining data has been sent // to the client before sending state // information // data to client // was created private bool _addToHistory; // associated with this powershell #if !CORECLR // No ApartmentState In CoreCLR private ApartmentState apartmentState; // apartment state for this powershell #endif // pipeline that runs the actual command. private ServerSteppablePipelineSubscriber _eventSubscriber; private PSDataCollection<object> _powershellInput; // input collection of the PowerShell pipeline #endregion #if CORECLR // No ApartmentState In CoreCLR /// <summary> /// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently /// run 2 pipelines. /// </summary> /// <param name="powershell">Decoded powershell object.</param> /// <param name="noInput">Whether there is input for this powershell.</param> /// <param name="clientPowerShellId">The client powershell id.</param> /// <param name="clientRunspacePoolId">The client runspacepool id.</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">Serialization options for the streams in this powershell.</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> /// <param name="eventSubscriber"> /// Steppable pipeline event subscriber /// </param> /// <param name="powershellInput">Input collection of the PowerShell pipeline.</param> internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput) #else /// <summary> /// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently /// run 2 pipelines. /// </summary> /// <param name="powershell">Decoded powershell object.</param> /// <param name="noInput">Whether there is input for this powershell.</param> /// <param name="clientPowerShellId">The client powershell id.</param> /// <param name="clientRunspacePoolId">The client runspacepool id.</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="apartmentState">Apartment state for this powershell.</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">Serialization options for the streams in this powershell.</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> /// <param name="eventSubscriber"> /// Steppable pipeline event subscriber /// </param> /// <param name="powershellInput">Input collection of the PowerShell pipeline.</param> internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput) #endif { LocalPowerShell = powershell; InstanceId = clientPowerShellId; RunspacePoolId = clientRunspacePoolId; RemoteStreamOptions = streamOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = apartmentState; #endif NoInput = noInput; _addToHistory = addToHistory; _eventSubscriber = eventSubscriber; _powershellInput = powershellInput; Input = new PSDataCollection<object>(); InputEnumerator = Input.GetEnumerator(); Input.ReleaseOnEnumeration = true; DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, null); RemoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); // subscribe to various data structure handler events DataStructureHandler.InputEndReceived += new EventHandler(HandleInputEndReceived); DataStructureHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(HandleInputReceived); DataStructureHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived); DataStructureHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(HandleHostResponseReceived); DataStructureHandler.OnSessionConnected += new EventHandler(HandleSessionConnected); if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NestedPipelineMissingRunspace); } // else, set the runspace pool and invoke this powershell LocalPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); PipelineState = PSInvocationState.NotStarted; } #region Internal Methods /// <summary> /// Local PowerShell instance. /// </summary> internal PowerShell LocalPowerShell { get; } /// <summary> /// Instance id by which this powershell driver is /// identified. This is the same as the id of the /// powershell on the client side. /// </summary> internal Guid InstanceId { get; } /// <summary> /// Server remote host. /// </summary> internal ServerRemoteHost RemoteHost { get; } /// <summary> /// Serialization options for the streams in this powershell. /// </summary> internal RemoteStreamOptions RemoteStreamOptions { get; } /// <summary> /// Id of the runspace pool driver which created /// this object. This is the same as the id of /// the runspace pool at the client side which /// is associated with the powershell on the /// client side. /// </summary> internal Guid RunspacePoolId { get; } /// <summary> /// ServerPowerShellDataStructureHandler associated with this /// powershell driver. /// </summary> internal ServerPowerShellDataStructureHandler DataStructureHandler { get; } /// <summary> /// Pipeline invocation state. /// </summary> internal PSInvocationState PipelineState { get; private set; } /// <summary> /// Checks if the steppable pipeline has input. /// </summary> internal bool NoInput { get; } /// <summary> /// Steppablepipeline object. /// </summary> internal SteppablePipeline SteppablePipeline { get; set; } /// <summary> /// Synchronization object. /// </summary> internal object SyncObject { get; } = new object(); /// <summary> /// Processing input. /// </summary> internal bool ProcessingInput { get; set; } /// <summary> /// Input enumerator. /// </summary> internal IEnumerator<object> InputEnumerator { get; } /// <summary> /// Input collection. /// </summary> internal PSDataCollection<object> Input { get; } /// <summary> /// Is the pipeline pulsed. /// </summary> internal bool Pulsed { get; set; } /// <summary> /// Total objects processed. /// </summary> internal int TotalObjectsProcessed { get; set; } /// <summary> /// Starts the exectution. /// </summary> internal void Start() { PipelineState = PSInvocationState.Running; _eventSubscriber.FireStartSteppablePipeline(this); if (_powershellInput != null) { _powershellInput.Pulse(); } } #endregion Internal Methods #region DataStructure related event handling / processing /// <summary> /// Close the input collection of the local powershell. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing this event.</param> internal void HandleInputEndReceived(object sender, EventArgs eventArgs) { Input.Complete(); CheckAndPulseForProcessing(true); if (_powershellInput != null) { _powershellInput.Pulse(); } } private void HandleSessionConnected(object sender, EventArgs eventArgs) { // Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin if (Input != null) { Input.Complete(); } } /// <summary> /// Handle a host message response received. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing this event.</param> internal void HandleHostResponseReceived(object sender, RemoteDataEventArgs<RemoteHostResponse> eventArgs) { RemoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data); } /// <summary> /// Stop the local powershell. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Unused.</param> private void HandleStopReceived(object sender, EventArgs eventArgs) { lock (SyncObject) { PipelineState = PSInvocationState.Stopping; } PerformStop(); if (_powershellInput != null) { _powershellInput.Pulse(); } } /// <summary> /// Add input to the local powershell's input collection. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing this event.</param> private void HandleInputReceived(object sender, RemoteDataEventArgs<object> eventArgs) { Dbg.Assert(!NoInput, "Input data should not be received for powershells created with no input"); if (Input != null) { lock (SyncObject) { Input.Add(eventArgs.Data); } CheckAndPulseForProcessing(false); if (_powershellInput != null) { _powershellInput.Pulse(); } } } /// <summary> /// Checks if there is any pending input that needs processing. If so, triggers RunProcessRecord /// event. The pipeline execution thread catches this and calls us back when the pipeline is /// suspended. /// </summary> /// <param name="complete"></param> internal void CheckAndPulseForProcessing(bool complete) { if (complete) { _eventSubscriber.FireHandleProcessRecord(this); } else if (!Pulsed) { bool shouldPulse = false; lock (SyncObject) { if (Pulsed) { return; } if (!ProcessingInput && ((Input.Count > TotalObjectsProcessed))) { shouldPulse = true; Pulsed = true; } } if (shouldPulse && (PipelineState == PSInvocationState.Running)) { _eventSubscriber.FireHandleProcessRecord(this); } } } /// <summary> /// Performs the stop operation. /// </summary> internal void PerformStop() { bool shouldPerformStop = false; lock (SyncObject) { if (!ProcessingInput && (PipelineState == PSInvocationState.Stopping)) { shouldPerformStop = true; } } if (shouldPerformStop) { SetState(PSInvocationState.Stopped, new PipelineStoppedException()); } } /// <summary> /// Changes state and sends message to the client as needed. /// </summary> /// <param name="newState"></param> /// <param name="reason"></param> internal void SetState(PSInvocationState newState, Exception reason) { PSInvocationState copyState = PSInvocationState.NotStarted; bool shouldRaiseEvents = false; lock (SyncObject) { switch (PipelineState) { case PSInvocationState.NotStarted: { switch (newState) { case PSInvocationState.Running: case PSInvocationState.Stopping: case PSInvocationState.Completed: case PSInvocationState.Stopped: case PSInvocationState.Failed: copyState = newState; // NotStarted -> Running..we dont send // state back to client. break; } } break; case PSInvocationState.Running: { switch (newState) { case PSInvocationState.NotStarted: throw new InvalidOperationException(); case PSInvocationState.Running: break; case PSInvocationState.Stopping: copyState = newState; break; case PSInvocationState.Completed: case PSInvocationState.Stopped: case PSInvocationState.Failed: copyState = newState; shouldRaiseEvents = true; break; } } break; case PSInvocationState.Stopping: { switch (newState) { case PSInvocationState.Completed: case PSInvocationState.Failed: copyState = PSInvocationState.Stopped; shouldRaiseEvents = true; break; case PSInvocationState.Stopped: copyState = newState; shouldRaiseEvents = true; break; default: throw new InvalidOperationException(); } } break; case PSInvocationState.Stopped: case PSInvocationState.Completed: case PSInvocationState.Failed: break; } PipelineState = copyState; } if (shouldRaiseEvents) { // send the state change notification to the client DataStructureHandler.SendStateChangedInformationToClient( new PSInvocationStateInfo(copyState, reason)); } if (PipelineState == PSInvocationState.Completed || PipelineState == PSInvocationState.Stopped || PipelineState == PSInvocationState.Failed) { // Remove itself from the runspace pool DataStructureHandler.RaiseRemoveAssociationEvent(); } } #endregion } }
#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.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Google.Protobuf; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; using Grpc.Testing; namespace Grpc.IntegrationTesting { /// <summary> /// Helper methods to start client runners for performance testing. /// </summary> public class ClientRunners { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>(); // Profilers to use for clients. static readonly BlockingCollection<BasicProfiler> profilers = new BlockingCollection<BasicProfiler>(); internal static void AddProfiler(BasicProfiler profiler) { GrpcPreconditions.CheckNotNull(profiler); profilers.Add(profiler); } /// <summary> /// Creates a started client runner. /// </summary> public static IClientRunner CreateStarted(ClientConfig config) { Logger.Debug("ClientConfig: {0}", config); if (config.AsyncClientThreads != 0) { Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value"); } if (config.CoreLimit != 0) { Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value"); } if (config.CoreList.Count > 0) { Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value"); } var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams); return new ClientRunnerImpl(channels, config.ClientType, config.RpcType, config.OutstandingRpcsPerChannel, config.LoadParams, config.PayloadConfig, config.HistogramParams, () => GetNextProfiler()); } private static List<Channel> CreateChannels(int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams) { GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1."); GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified."); var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure; List<ChannelOption> channelOptions = null; if (securityParams != null && securityParams.ServerHostOverride != "") { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride) }; } var result = new List<Channel>(); for (int i = 0; i < clientChannels; i++) { var target = serverTargets.ElementAt(i % serverTargets.Count()); var channel = new Channel(target, credentials, channelOptions); result.Add(channel); } return result; } private static BasicProfiler GetNextProfiler() { BasicProfiler result = null; profilers.TryTake(out result); return result; } } internal class ClientRunnerImpl : IClientRunner { const double SecondsToNanos = 1e9; readonly List<Channel> channels; readonly ClientType clientType; readonly RpcType rpcType; readonly PayloadConfig payloadConfig; readonly Histogram histogram; readonly List<Task> runnerTasks; readonly CancellationTokenSource stoppedCts = new CancellationTokenSource(); readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); readonly AtomicCounter statsResetCount = new AtomicCounter(); public ClientRunnerImpl(List<Channel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, Func<BasicProfiler> profilerFactory) { GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, "outstandingRpcsPerChannel"); GrpcPreconditions.CheckNotNull(histogramParams, "histogramParams"); this.channels = new List<Channel>(channels); this.clientType = clientType; this.rpcType = rpcType; this.payloadConfig = payloadConfig; this.histogram = new Histogram(histogramParams.Resolution, histogramParams.MaxPossible); this.runnerTasks = new List<Task>(); foreach (var channel in this.channels) { for (int i = 0; i < outstandingRpcsPerChannel; i++) { var timer = CreateTimer(loadParams, 1.0 / this.channels.Count / outstandingRpcsPerChannel); var optionalProfiler = profilerFactory(); this.runnerTasks.Add(RunClientAsync(channel, timer, optionalProfiler)); } } } public ClientStats GetStats(bool reset) { var histogramData = histogram.GetSnapshot(reset); var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds; if (reset) { statsResetCount.Increment(); } // TODO: populate user time and system time return new ClientStats { Latencies = histogramData, TimeElapsed = secondsElapsed, TimeUser = 0, TimeSystem = 0 }; } public async Task StopAsync() { stoppedCts.Cancel(); foreach (var runnerTask in runnerTasks) { await runnerTask; } foreach (var channel in channels) { await channel.ShutdownAsync(); } } private void RunUnary(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler) { if (optionalProfiler != null) { Profilers.SetForCurrentThread(optionalProfiler); } bool profilerReset = false; var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { // after the first stats reset, also reset the profiler. if (optionalProfiler != null && !profilerReset && statsResetCount.Count > 0) { optionalProfiler.Reset(); profilerReset = true; } stopwatch.Restart(); client.UnaryCall(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); timer.WaitForNext(); } } private async Task RunUnaryAsync(Channel channel, IInterarrivalTimer timer) { var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await client.UnaryCallAsync(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } } private async Task RunStreamingPingPongAsync(Channel channel, IInterarrivalTimer timer) { var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); using (var call = client.StreamingCall()) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private async Task RunGenericStreamingAsync(Channel channel, IInterarrivalTimer timer) { var request = CreateByteBufferRequest(); var stopwatch = new Stopwatch(); var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions()); using (var call = Calls.AsyncDuplexStreamingCall(callDetails)) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private Task RunClientAsync(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler) { if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams) { GrpcPreconditions.CheckArgument(clientType == ClientType.AsyncClient, "Generic client only supports async API"); GrpcPreconditions.CheckArgument(rpcType == RpcType.Streaming, "Generic client only supports streaming calls"); return RunGenericStreamingAsync(channel, timer); } GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); if (clientType == ClientType.SyncClient) { GrpcPreconditions.CheckArgument(rpcType == RpcType.Unary, "Sync client can only be used for Unary calls in C#"); // create a dedicated thread for the synchronous client return Task.Factory.StartNew(() => RunUnary(channel, timer, optionalProfiler), TaskCreationOptions.LongRunning); } else if (clientType == ClientType.AsyncClient) { switch (rpcType) { case RpcType.Unary: return RunUnaryAsync(channel, timer); case RpcType.Streaming: return RunStreamingPingPongAsync(channel, timer); } } throw new ArgumentException("Unsupported configuration."); } private SimpleRequest CreateSimpleRequest() { GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); return new SimpleRequest { Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize), ResponseSize = payloadConfig.SimpleParams.RespSize }; } private byte[] CreateByteBufferRequest() { return new byte[payloadConfig.BytebufParams.ReqSize]; } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier) { switch (loadParams.LoadCase) { case LoadParams.LoadOneofCase.ClosedLoop: return new ClosedLoopInterarrivalTimer(); case LoadParams.LoadOneofCase.Poisson: return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier); default: throw new ArgumentException("Unknown load type"); } } } }
using JobManager; using JobManager.Date; using JobManager.Exceptions; using Newtonsoft.Json; using System; using System.Linq.Expressions; using System.Reflection; namespace JobManager { /// <summary> /// The job emulation. /// /// /// Example to create a job. /// <code> /// /// public class TestJob { /// public int JMExecute() { /// Console.WriteLine("Hello World."); /// return 1; /// } /// /// /// public static void Main(string args[]) { /// /// DateTime dt = DateTime.Now; /// /// DateInterval di = new DateInterval(); /// di.Minutes = 20; /// /// Job j = new RepeatableJob("RepJob1", new TestJob(), dt, di); /// /// } /// } /// /// /// </code> /// </summary> public abstract class Job { internal Manager _parentManager; internal object _referenceToJobObject; internal string _name; internal string _id; internal Func<int> _function; internal DateTime _executionDate; internal DateInterval _executionInterval; /// <summary> /// The parent manager. Used to have a link with the parent manager. /// </summary> [JsonIgnore] public Manager ParentManager { get { return _parentManager; } set { if (value == null) throw new ArgumentNullException("Manager can't be null"); if (_parentManager != null) throw new ArgumentException("Manager already set"); _parentManager = value; } } /// <summary> /// Reference to the object created for the job. /// </summary> [JsonIgnore] public object ReferenceToJobObject { get { return _referenceToJobObject; } protected set { if (value == null) throw new ArgumentNullException("Manager can't be null"); _referenceToJobObject = value; } } /// <summary> /// The function to execute when it's time to. /// Inside the object, it has to be named as "JMExecute" /// </summary> [JsonIgnore] public Func<int> Function { get { return _function; } set { if (value == null) throw new ArgumentNullException("Manager can't be null"); _function = value; } } /// <summary> /// Name of the object created. /// It could be only "UniqueJob" and "RepeatableJob". /// </summary> public string Name { get { return _name; } protected set { _name = value; } } /// <summary> /// Id given by the user. /// It's use to differenciate jobs inside the manager. /// </summary> public string Id { get { return _id; } protected set { _id = value; } } /// <summary> /// The next execution date. /// It gives the date to when the job has to be execute. /// </summary> public DateTime ExecutionDate { get { return _executionDate; } set { _executionDate = value; } } /// <summary> /// The date interval. /// Time to wait between two executions. /// </summary> public DateInterval ExecutionInterval { get { return _executionInterval; } set { _executionInterval = value; } } /// <summary> /// Use to forbid inheritance. /// </summary> internal Job() { } /// <summary> /// Create the instance. Internal is use to forbid inheritance. /// Raise InvalidObjectException if the object doesn't have "JMExecute" /// function. /// </summary> internal Job(string Id, object Obj, DateTime ExecutionDate, DateInterval Interval) { this.Id = Id; this.ReferenceToJobObject = Obj; this.ExecutionDate = ExecutionDate; this.ExecutionInterval = Interval; FindFunction(); } /// <summary> /// Job repetetion. /// </summary> /// <returns>true if the job is repeatable.</returns> public abstract bool IsRepeatable(); /// <summary> /// Function to execute when it's time. /// </summary> public void Execute() { try { if (Function() == 0) throw new BadReturnedValueException("Function returned 0."); } catch(BadReturnedValueException) { throw; } catch(Exception e) { throw new ExecutionException("Error while running function.", e); } } /// <summary> /// Add the interval to know the next date. /// </summary> public void ChangeToNextDate() { ExecutionDate = ExecutionDate.AddYears(ExecutionInterval.Years) .AddMonths(ExecutionInterval.Months) .AddDays(ExecutionInterval.Days) .AddHours(ExecutionInterval.Hours) .AddMinutes(ExecutionInterval.Minutes) .AddSeconds(ExecutionInterval.Seconds) .AddMilliseconds(ExecutionInterval.Milliseconds); } /// <summary> /// Use to find "JMExecute" function inside the given object. /// Throw InvalidObjectException if it doesn't exists. /// </summary> private void FindFunction() { Type ObjectType = ReferenceToJobObject.GetType(); MethodInfo JobMethod = ObjectType.GetMethod("JMExecute"); if (!JobMethod.ReturnType.Equals(typeof(int))) { throw new InvalidObjectException( "Type " + ObjectType.Name + " doesn't contain 'JMExecute'" + " method returning an integer"); } Function = Expression.Lambda<Func<int>>( Expression.Call( Expression.Constant(ReferenceToJobObject), JobMethod ) ).Compile(); } } /// <summary> /// Represent a unique job. /// It will be remove just after its execution. /// </summary> public sealed class UniqueJob : Job { /// <summary> /// Create an empty instance. Only used by the json loader. /// </summary> public UniqueJob() { } /// <summary> /// Create the instance with given data /// </summary> public UniqueJob(string Id, object Obj, DateTime ExecutionDate, DateInterval Interval) : base(Id, Obj, ExecutionDate, Interval) { this.Name = "UniqueJob"; } public override bool IsRepeatable() { return false; } } /// <summary> /// Represent a repeatable job. /// </summary> public sealed class RepeatableJob : Job { /// <summary> /// Create an empty instance. Only used by the json loader. /// </summary> public RepeatableJob() { } /// <summary> /// Create the instance with given data. /// </summary> public RepeatableJob(string Id, object Obj, DateTime ExecutionDate, DateInterval Interval) : base(Id, Obj, ExecutionDate, Interval) { this.Name = "RepeatableJob"; } public override bool IsRepeatable() { return true; } } }
using Avalonia.Media; using Avalonia.Visuals.Platform; using Xunit; namespace Avalonia.Visuals.UnitTests.Media { using System.Globalization; using System.IO; using Avalonia.Platform; using Moq; public class PathMarkupParserTests { [Fact] public void Parses_Move() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("M10 10"); var figure = pathGeometry.Figures[0]; Assert.Equal(new Point(10, 10), figure.StartPoint); } } [Fact] public void Parses_Line() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("M0 0L10 10"); var figure = pathGeometry.Figures[0]; var segment = figure.Segments[0]; Assert.IsType<LineSegment>(segment); var lineSegment = (LineSegment)segment; Assert.Equal(new Point(10, 10), lineSegment.Point); } } [Fact] public void Parses_Close() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("M0 0L10 10z"); var figure = pathGeometry.Figures[0]; Assert.True(figure.IsClosed); } } [Fact] public void Parses_FillMode_Before_Move() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("F 1M0,0"); Assert.Equal(FillRule.NonZero, pathGeometry.FillRule); } } [Theory] [InlineData("M0 0 10 10 20 20")] [InlineData("M0,0 10,10 20,20")] [InlineData("M0,0,10,10,20,20")] public void Parses_Implicit_Line_Command_After_Move(string pathData) { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse(pathData); var figure = pathGeometry.Figures[0]; var segment = figure.Segments[0]; Assert.IsType<LineSegment>(segment); var lineSegment = (LineSegment)segment; Assert.Equal(new Point(10, 10), lineSegment.Point); segment = figure.Segments[1]; Assert.IsType<LineSegment>(segment); lineSegment = (LineSegment)segment; Assert.Equal(new Point(20, 20), lineSegment.Point); } } [Theory] [InlineData("m0 0 10 10 20 20")] [InlineData("m0,0 10,10 20,20")] [InlineData("m0,0,10,10,20,20")] public void Parses_Implicit_Line_Command_After_Relative_Move(string pathData) { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse(pathData); var figure = pathGeometry.Figures[0]; var segment = figure.Segments[0]; Assert.IsType<LineSegment>(segment); var lineSegment = (LineSegment)segment; Assert.Equal(new Point(10, 10), lineSegment.Point); segment = figure.Segments[1]; Assert.IsType<LineSegment>(segment); lineSegment = (LineSegment)segment; Assert.Equal(new Point(30, 30), lineSegment.Point); } } [Fact] public void Parses_Scientific_Notation_Double() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("M -1.01725E-005 -1.01725e-005"); var figure = pathGeometry.Figures[0]; Assert.Equal( new Point( double.Parse("-1.01725E-005", NumberStyles.Float, CultureInfo.InvariantCulture), double.Parse("-1.01725E-005", NumberStyles.Float, CultureInfo.InvariantCulture)), figure.StartPoint); } } [Theory] [InlineData("M5.5.5 5.5.5 5.5.5")] [InlineData("F1M9.0771,11C9.1161,10.701,9.1801,10.352,9.3031,10L9.0001,10 9.0001,6.166 3.0001,9.767 3.0001,10 " + "9.99999999997669E-05,10 9.99999999997669E-05,0 3.0001,0 3.0001,0.234 9.0001,3.834 9.0001,0 " + "12.0001,0 12.0001,8.062C12.1861,8.043 12.3821,8.031 12.5941,8.031 15.3481,8.031 15.7961,9.826 " + "15.9201,11L16.0001,16 9.0001,16 9.0001,12.562 9.0001,11z")] // issue #1708 [InlineData(" M0 0")] [InlineData("F1 M24,14 A2,2,0,1,1,20,14 A2,2,0,1,1,24,14 z")] // issue #1107 [InlineData("M0 0L10 10z")] [InlineData("M50 50 L100 100 L150 50")] [InlineData("M50 50L100 100L150 50")] [InlineData("M50,50 L100,100 L150,50")] [InlineData("M50 50 L-10 -10 L10 50")] [InlineData("M50 50L-10-10L10 50")] [InlineData("M50 50 L100 100 L150 50zM50 50 L70 70 L120 50z")] [InlineData("M 50 50 L 100 100 L 150 50")] [InlineData("M50 50 L100 100 L150 50 H200 V100Z")] [InlineData("M 80 200 A 100 50 45 1 0 100 50")] [InlineData( "F1 M 16.6309 18.6563C 17.1309 8.15625 29.8809 14.1563 29.8809 14.1563C 30.8809 11.1563 34.1308 11.4063" + " 34.1308 11.4063C 33.5 12 34.6309 13.1563 34.6309 13.1563C 32.1309 13.1562 31.1309 14.9062 31.1309 14.9" + "062C 41.1309 23.9062 32.6309 27.9063 32.6309 27.9062C 24.6309 24.9063 21.1309 22.1562 16.6309 18.6563 Z" + " M 16.6309 19.9063C 21.6309 24.1563 25.1309 26.1562 31.6309 28.6562C 31.6309 28.6562 26.3809 39.1562 18" + ".3809 36.1563C 18.3809 36.1563 18 38 16.3809 36.9063C 15 36 16.3809 34.9063 16.3809 34.9063C 16.3809 34" + ".9063 10.1309 30.9062 16.6309 19.9063 Z ")] [InlineData( "F1M16,12C16,14.209 14.209,16 12,16 9.791,16 8,14.209 8,12 8,11.817 8.03,11.644 8.054,11.467L6.585,10 4,10 " + "4,6.414 2.5,7.914 0,5.414 0,3.586 3.586,0 4.414,0 7.414,3 7.586,3 9,1.586 11.914,4.5 10.414,6 " + "12.461,8.046C14.45,8.278,16,9.949,16,12")] public void Should_Parse(string pathData) { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse(pathData); Assert.True(true); } } [Theory] [InlineData("M0 0L10 10")] [InlineData("M0 0L10 10z")] [InlineData("M0 0L10 10 \n ")] [InlineData("M0 0L10 10z \n ")] [InlineData("M0 0L10 10 ")] [InlineData("M0 0L10 10z ")] public void Should_AlwaysEndFigure(string pathData) { var context = new Mock<IGeometryContext>(); using (var parser = new PathMarkupParser(context.Object)) { parser.Parse(pathData); } context.Verify(v => v.EndFigure(It.IsAny<bool>()), Times.AtLeastOnce()); } [Theory] [InlineData("M 5.5, 5 L 5.5, 5 L 5.5, 5")] [InlineData("F1 M 9.0771, 11 C 9.1161, 10.701 9.1801, 10.352 9.3031, 10 L 9.0001, 10 L 9.0001, 6.166 L 3.0001, 9.767 L 3.0001, 10 " + "L 9.99999999997669E-05, 10 L 9.99999999997669E-05, 0 L 3.0001, 0 L 3.0001, 0.234 L 9.0001, 3.834 L 9.0001, 0 " + "L 12.0001, 0 L 12.0001, 8.062 C 12.1861, 8.043 12.3821, 8.031 12.5941, 8.031 C 15.3481, 8.031 15.7961, 9.826 " + "15.9201, 11 L 16.0001, 16 L 9.0001, 16 L 9.0001, 12.562 L 9.0001, 11Z")] [InlineData("F1 M 24, 14 A 2, 2 0 1 1 20, 14 A 2, 2 0 1 1 24, 14Z")] [InlineData("M 0, 0 L 10, 10Z")] [InlineData("M 50, 50 L 100, 100 L 150, 50")] [InlineData("M 50, 50 L -10, -10 L 10, 50")] [InlineData("M 50, 50 L 100, 100 L 150, 50Z M 50, 50 L 70, 70 L 120, 50Z")] [InlineData("M 80, 200 A 100, 50 45 1 0 100, 50")] [InlineData("F1 M 16, 12 C 16, 14.209 14.209, 16 12, 16 C 9.791, 16 8, 14.209 8, 12 C 8, 11.817 8.03, 11.644 8.054, 11.467 L 6.585, 10 " + "L 4, 10 L 4, 6.414 L 2.5, 7.914 L 0, 5.414 L 0, 3.586 L 3.586, 0 L 4.414, 0 L 7.414, 3 L 7.586, 3 L 9, 1.586 L " + "11.914, 4.5 L 10.414, 6 L 12.461, 8.046 C 14.45, 8.278 16, 9.949 16, 12")] public void Parsed_Geometry_ToString_Should_Produce_Valid_Value(string pathData) { var target = PathGeometry.Parse(pathData); string output = target.ToString(); Assert.Equal(pathData, output); } [Theory] [InlineData("M5.5.5 5.5.5 5.5.5", "M 5.5, 0.5 L 5.5, 0.5 L 5.5, 0.5")] [InlineData("F1 M24,14 A2,2,0,1,1,20,14 A2,2,0,1,1,24,14 z", "F1 M 24, 14 A 2, 2 0 1 1 20, 14 A 2, 2 0 1 1 24, 14Z")] [InlineData("F1M16,12C16,14.209 14.209,16 12,16 9.791,16 8,14.209 8,12 8,11.817 8.03,11.644 8.054,11.467L6.585,10 4,10 " + "4,6.414 2.5,7.914 0,5.414 0,3.586 3.586,0 4.414,0 7.414,3 7.586,3 9,1.586 11.914,4.5 10.414,6 " + "12.461,8.046C14.45,8.278,16,9.949,16,12", "F1 M 16, 12 C 16, 14.209 14.209, 16 12, 16 C 9.791, 16 8, 14.209 8, 12 C 8, 11.817 8.03, 11.644 8.054, 11.467 L 6.585, 10 " + "L 4, 10 L 4, 6.414 L 2.5, 7.914 L 0, 5.414 L 0, 3.586 L 3.586, 0 L 4.414, 0 L 7.414, 3 L 7.586, 3 L 9, 1.586 L " + "11.914, 4.5 L 10.414, 6 L 12.461, 8.046 C 14.45, 8.278 16, 9.949 16, 12")] public void Parsed_Geometry_ToString_Should_Format_Value(string pathData, string formattedPathData) { var target = PathGeometry.Parse(pathData); string output = target.ToString(); Assert.Equal(formattedPathData, output); } [Theory] [InlineData("0 0")] [InlineData("j")] public void Throws_InvalidDataException_On_None_Defined_Command(string pathData) { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { Assert.Throws<InvalidDataException>(() => parser.Parse(pathData)); } } [Fact] public void CloseFigure_Should_Move_CurrentPoint_To_CreateFigurePoint() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("M10,10L100,100Z m10,10"); Assert.Equal(2, pathGeometry.Figures.Count); var figure = pathGeometry.Figures[0]; Assert.Equal(new Point(10, 10), figure.StartPoint); Assert.Equal(true, figure.IsClosed); Assert.Equal(new Point(100, 100), ((LineSegment)figure.Segments[0]).Point); figure = pathGeometry.Figures[1]; Assert.Equal(new Point(20, 20), figure.StartPoint); } } [Fact] public void Should_Parse_Flags_Without_Separator() { var pathGeometry = new PathGeometry(); using (var context = new PathGeometryContext(pathGeometry)) using (var parser = new PathMarkupParser(context)) { parser.Parse("a.898.898 0 01.27.188"); var figure = pathGeometry.Figures[0]; var segments = figure.Segments; Assert.NotNull(segments); Assert.Equal(1, segments.Count); var arcSegment = segments[0]; Assert.IsType<ArcSegment>(arcSegment); } } } }
// Radial Menu|Prefabs|0040 namespace VRTK { using UnityEngine; using System.Collections; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public delegate void HapticPulseEventHandler(float strength); /// <summary> /// This adds a UI element into the world space that can be dropped into a Controller object and used to create and use Radial Menus from the touchpad. /// </summary> /// <remarks> /// If the RadialMenu is placed inside a controller, it will automatically find a `VRTK_ControllerEvents` in its parent to use at the input. However, a `VRTK_ControllerEvents` can be defined explicitly by setting the `Events` parameter of the `Radial Menu Controller` script also attached to the prefab. /// /// The RadialMenu can also be placed inside a `VRTK_InteractableObject` for the RadialMenu to be anchored to a world object instead of the controller. The `Events Manager` parameter will automatically be set if the RadialMenu is a child of an InteractableObject, but it can also be set manually in the inspector. Additionally, for the RadialMenu to be anchored in the world, the `RadialMenuController` script in the prefab must be replaced with `VRTK_IndependentRadialMenuController`. See the script information for further details on making the RadialMenu independent of the controllers. /// </remarks> /// <example> /// `VRTK/Examples/030_Controls_RadialTouchpadMenu` displays a radial menu for each controller. The left controller uses the `Hide On Release` variable, so it will only be visible if the left touchpad is being touched. It also uses the `Execute On Unclick` variable to delay execution until the touchpad button is unclicked. The example scene also contains a demonstration of anchoring the RadialMenu to an interactable cube instead of a controller. /// </example> [ExecuteInEditMode] public class RadialMenu : MonoBehaviour { #region Variables [Tooltip("An array of Buttons that define the interactive buttons required to be displayed as part of the radial menu.")] public List<RadialMenuButton> buttons; [Tooltip("The base for each button in the menu, by default set to a dynamic circle arc that will fill up a portion of the menu.")] public GameObject buttonPrefab; [Tooltip("If checked, then the buttons will be auto generated on awake.")] public bool generateOnAwake = true; [Tooltip("Percentage of the menu the buttons should fill, 1.0 is a pie slice, 0.1 is a thin ring.")] [Range(0f, 1f)] public float buttonThickness = 0.5f; [Tooltip("The background colour of the buttons, default is white.")] public Color buttonColor = Color.white; [Tooltip("The distance the buttons should move away from the centre. This creates space between the individual buttons.")] public float offsetDistance = 1; [Tooltip("The additional rotation of the Radial Menu.")] [Range(0, 359)] public float offsetRotation; [Tooltip("Whether button icons should rotate according to their arc or be vertical compared to the controller.")] public bool rotateIcons; [Tooltip("The margin in pixels that the icon should keep within the button.")] public float iconMargin; [Tooltip("Whether the buttons are shown")] public bool isShown; [Tooltip("Whether the buttons should be visible when not in use.")] public bool hideOnRelease; [Tooltip("Whether the button action should happen when the button is released, as opposed to happening immediately when the button is pressed.")] public bool executeOnUnclick; [Tooltip("The base strength of the haptic pulses when the selected button is changed, or a button is pressed. Set to zero to disable.")] [Range(0, 1)] public float baseHapticStrength; public event HapticPulseEventHandler FireHapticPulse; //Has to be public to keep state from editor -> play mode? [Tooltip("The actual GameObjects that make up the radial menu.")] public List<GameObject> menuButtons; private int currentHover = -1; private int currentPress = -1; #endregion #region Unity Methods protected virtual void Awake() { if (Application.isPlaying) { if (!isShown) { transform.localScale = Vector3.zero; } if (generateOnAwake) { RegenerateButtons(); } } } protected virtual void Update() { //Keep track of pressed button and constantly invoke Hold event if (currentPress != -1) { buttons[currentPress].OnHold.Invoke(); } } #endregion #region Interaction //Turns and Angle and Event type into a button action private void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error { //Get button ID from angle float buttonAngle = 360f / buttons.Count; //Each button is an arc with this angle angle = mod((angle + -offsetRotation), 360); //Offset the touch coordinate with our offset int buttonID = (int)mod(((angle + (buttonAngle / 2f)) / buttonAngle), buttons.Count); //Convert angle into ButtonID (This is the magic) var pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event //If we changed buttons while moving, un-hover and un-click the last button we were on if (currentHover != buttonID && currentHover != -1) { ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); if (executeOnUnclick && currentPress != -1) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); AttempHapticPulse(baseHapticStrength * 1.666f); } } if (evt == ButtonEvent.click) //Click button if click, and keep track of current press (executes button action) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); currentPress = buttonID; if (!executeOnUnclick) { buttons[buttonID].OnClick.Invoke(); AttempHapticPulse(baseHapticStrength * 2.5f); } } else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method (hide menu) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler); currentPress = -1; if (executeOnUnclick) { AttempHapticPulse(baseHapticStrength * 2.5f); buttons[buttonID].OnClick.Invoke(); } } else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc). Show menu { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler); buttons[buttonID].OnHoverEnter.Invoke(); AttempHapticPulse(baseHapticStrength); } currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes } /* * Public methods to call Interact */ public void HoverButton(float angle) { InteractButton(angle, ButtonEvent.hoverOn); } public void ClickButton(float angle) { InteractButton(angle, ButtonEvent.click); } public void UnClickButton(float angle) { InteractButton(angle, ButtonEvent.unclick); } public void ToggleMenu() { if (isShown) { HideMenu(true); } else { ShowMenu(); } } public void StopTouching() { if (currentHover != -1) { var pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); currentHover = -1; } } /* * Public methods to Show/Hide menu */ public void ShowMenu() { if (!isShown) { isShown = true; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } public RadialMenuButton GetButton(int id) { if (id < buttons.Count) { return buttons[id]; } return null; } public void HideMenu(bool force) { if (isShown && (hideOnRelease || force)) { isShown = false; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } //Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0 private IEnumerator TweenMenuScale(bool show) { float targetScale = 0; Vector3 Dir = -1 * Vector3.one; if (show) { targetScale = 1; Dir = Vector3.one; } int i = 0; //Sanity check for infinite loops while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale))) { transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear yield return true; i++; } transform.localScale = Dir * targetScale; StopCoroutine("TweenMenuScale"); } private void AttempHapticPulse(float strength) { if (strength > 0 && FireHapticPulse != null) { FireHapticPulse(strength); } } #endregion #region Generation //Creates all the button Arcs and populates them with desired icons public void RegenerateButtons() { RemoveAllButtons(); for (int i = 0; i < buttons.Count; i++) { // Initial placement/instantiation GameObject newButton = Instantiate(buttonPrefab); newButton.transform.SetParent(transform); newButton.transform.localScale = Vector3.one; newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero; newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero; //Setup button arc UICircle circle = newButton.GetComponent<UICircle>(); if (buttonThickness == 1) { circle.fill = true; } else { circle.thickness = (int)(buttonThickness * (GetComponent<RectTransform>().rect.width / 2f)); } int fillPerc = (int)(100f / buttons.Count); circle.fillPercent = fillPerc; circle.color = buttonColor; //Final placement/rotation float angle = ((360 / buttons.Count) * i) + offsetRotation; newButton.transform.localEulerAngles = new Vector3(0, 0, angle); newButton.layer = 4; //UI Layer newButton.transform.localPosition = Vector3.zero; if (circle.fillPercent < 55) { float angleRad = (angle * Mathf.PI) / 180f; Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad)); newButton.transform.localPosition += (Vector3)angleVector * offsetDistance; } //Place and populate Button Icon GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject; if (buttons[i].ButtonIcon == null) { buttonIcon.SetActive(false); } else { buttonIcon.GetComponent<Image>().sprite = buttons[i].ButtonIcon; buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0); //Min icon size from thickness and arc float scale1 = Mathf.Abs(circle.thickness); float R = Mathf.Abs(buttonIcon.transform.localPosition.x); float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f; float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f)); if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees { scale2 = float.MaxValue; } float iconScale = Mathf.Min(scale1, scale2) - iconMargin; buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale); //Rotate icons all vertically if desired if (!rotateIcons) { buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles; } } menuButtons.Add(newButton); } } public void AddButton(RadialMenuButton newButton) { buttons.Add(newButton); RegenerateButtons(); } private void RemoveAllButtons() { if (menuButtons == null) { menuButtons = new List<GameObject>(); } for (int i = 0; i < menuButtons.Count; i++) { DestroyImmediate(menuButtons[i]); } menuButtons = new List<GameObject>(); } #endregion #region Utility private float mod(float a, float b) { return a - b * Mathf.Floor(a / b); } #endregion } [System.Serializable] public class RadialMenuButton { public Sprite ButtonIcon; public UnityEvent OnClick = new UnityEvent(); public UnityEvent OnHold = new UnityEvent(); public UnityEvent OnHoverEnter = new UnityEvent(); public UnityEvent OnHoverExit = new UnityEvent(); } public enum ButtonEvent { hoverOn, hoverOff, click, unclick } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { [PythonType("super")] public class Super : PythonTypeSlot, ICodeFormattable { private PythonType _thisClass; private object _self; private object _selfClass; public Super() { } #region Python Public API Surface public void __init__(PythonType type) { __init__(type, null); } public void __init__(PythonType type, object obj) { if (obj != null) { PythonType dt = obj as PythonType; if (PythonOps.IsInstance(obj, type)) { this._thisClass = type; this._self = obj; this._selfClass = DynamicHelpers.GetPythonType(obj); } else if (dt != null && dt.IsSubclassOf(type)) { this._thisClass = type; this._selfClass = obj; this._self = obj; } else { throw PythonOps.TypeError("super(type, obj): obj must be an instance or subtype of type {1}, not {0}", PythonTypeOps.GetName(obj), type.Name); } } else { this._thisClass = type; this._self = null; this._selfClass = null; } } public PythonType __thisclass__ { get { return _thisClass; } } public object __self__ { get { return _self; } } public object __self_class__ { get { return _selfClass; } } public new object __get__(CodeContext/*!*/ context, object instance, object owner) { PythonType selfType = PythonType; if (selfType == TypeCache.Super) { Super res = new Super(); res.__init__(_thisClass, instance); return res; } return PythonCalls.Call(context, selfType, _thisClass, instance); } #endregion #region Custom member access [SpecialName] public object GetCustomMember(CodeContext context, string name) { // first find where we are in the mro... PythonType mroType = _selfClass as PythonType; object value; if (mroType != null) { // can be null if the user does super.__new__ IList<PythonType> mro = mroType.ResolutionOrder; int lookupType; bool foundThis = false; for (lookupType = 0; lookupType < mro.Count; lookupType++) { if (mro[lookupType] == _thisClass) { foundThis = true; break; } } if (!foundThis) { // __self__ is not a subclass of __thisclass__, we need to // search __thisclass__'s mro and return a method from one // of it's bases. lookupType = 0; mro = _thisClass.ResolutionOrder; } // if we're super on a class then we have no self. object self = _self == _selfClass ? null : _self; // then skip our class, and lookup in everything // above us until we get a hit. lookupType++; while (lookupType < mro.Count) { if (TryLookupInBase(context, mro[lookupType], name, self, out value)) return value; lookupType++; } } if (PythonType.TryGetBoundMember(context, this, name, out value)) { return value; } return OperationFailed.Value; } [SpecialName] public void SetMember(CodeContext context, string name, object value) { PythonType.SetMember(context, this, name, value); } [SpecialName] public void DeleteCustomMember(CodeContext context, string name) { PythonType.DeleteMember(context, this, name); } private bool TryLookupInBase(CodeContext context, PythonType pt, string name, object self, out object value) { PythonTypeSlot dts; if (pt.OldClass == null) { // new-style class, or reflected type, lookup slot if (pt.TryLookupSlot(context, name, out dts) && dts.TryGetValue(context, self, DescriptorContext, out value)) { return true; } } else { // old-style class, lookup attribute OldClass dt = pt.OldClass; if (dt.TryLookupOneSlot(DescriptorContext, name, out value)) { value = OldClass.GetOldStyleDescriptor(context, value, self, DescriptorContext); return true; } } value = null; return false; } private PythonType DescriptorContext { get { if (!DynamicHelpers.GetPythonType(_self).IsSubclassOf(_thisClass)) { if(_self == _selfClass) // Using @classmethod return _selfClass as PythonType ?? _thisClass; return _thisClass; } if (_selfClass is PythonType dt) return dt; return ((OldClass)_selfClass).TypeObject; } } // TODO needed because ICustomMembers is too hard to implement otherwise. Let's fix that and get rid of this. private PythonType PythonType { get { if (GetType() == typeof(Super)) return TypeCache.Super; IPythonObject sdo = this as IPythonObject; Debug.Assert(sdo != null); return sdo.PythonType; } } #endregion internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = __get__(context, instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #region ICodeFormattable Members public string __repr__(CodeContext context) { string selfRepr; if (_self == this) selfRepr = "<super object>"; else selfRepr = PythonOps.Repr(context, _self); return string.Format("<{0}: {1}, {2}>", PythonTypeOps.GetName(this), PythonOps.Repr(context, _thisClass), selfRepr); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for NamespacesOperations. /// </summary> public static partial class NamespacesOperationsExtensions { /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to check availability of the given namespace name /// </param> public static CheckNameAvailabilityResult CheckNameAvailabilityMethod(this INamespacesOperations operations, CheckNameAvailability parameters) { return operations.CheckNameAvailabilityMethodAsync(parameters).GetAwaiter().GetResult(); } /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to check availability of the given namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityMethodAsync(this INamespacesOperations operations, CheckNameAvailability parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityMethodWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<SBNamespace> List(this INamespacesOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBNamespace>> ListAsync(this INamespacesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> public static IPage<SBNamespace> ListByResourceGroup(this INamespacesOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBNamespace>> ListByResourceGroupAsync(this INamespacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> public static SBNamespace CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespace parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBNamespace> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespace parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { operations.DeleteAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static SBNamespace Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return operations.GetAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBNamespace> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a service namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> public static SBNamespace Update(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespaceUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a service namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBNamespace> UpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespaceUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static IPage<SBAuthorizationRule> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBAuthorizationRule>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> public static SBAuthorizationRule CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SBAuthorizationRule parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBAuthorizationRule> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SBAuthorizationRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static SBAuthorizationRule GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBAuthorizationRule> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the primary and secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static AccessKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the primary and secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the primary or secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> public static AccessKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters) { return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the primary or secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> public static SBNamespace BeginCreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespace parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SBNamespace> BeginCreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, SBNamespace parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { operations.BeginDeleteAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SBNamespace> ListNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBNamespace>> ListNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SBNamespace> ListByResourceGroupNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBNamespace>> ListByResourceGroupNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SBAuthorizationRule> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SBAuthorizationRule>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using gagr = Google.Api.Gax.ResourceNames; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary>Settings for <see cref="ErrorStatsServiceClient"/> instances.</summary> public sealed partial class ErrorStatsServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ErrorStatsServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ErrorStatsServiceSettings"/>.</returns> public static ErrorStatsServiceSettings GetDefault() => new ErrorStatsServiceSettings(); /// <summary>Constructs a new <see cref="ErrorStatsServiceSettings"/> object with default settings.</summary> public ErrorStatsServiceSettings() { } private ErrorStatsServiceSettings(ErrorStatsServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListGroupStatsSettings = existing.ListGroupStatsSettings; ListEventsSettings = existing.ListEventsSettings; DeleteEventsSettings = existing.DeleteEventsSettings; OnCopy(existing); } partial void OnCopy(ErrorStatsServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListGroupStats</c> and <c>ErrorStatsServiceClient.ListGroupStatsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListGroupStatsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListEvents</c> and <c>ErrorStatsServiceClient.ListEventsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListEventsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.DeleteEvents</c> and <c>ErrorStatsServiceClient.DeleteEventsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteEventsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ErrorStatsServiceSettings"/> object.</returns> public ErrorStatsServiceSettings Clone() => new ErrorStatsServiceSettings(this); } /// <summary> /// Builder class for <see cref="ErrorStatsServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class ErrorStatsServiceClientBuilder : gaxgrpc::ClientBuilderBase<ErrorStatsServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ErrorStatsServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ErrorStatsServiceClientBuilder() { UseJwtAccessWithScopes = ErrorStatsServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ErrorStatsServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ErrorStatsServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ErrorStatsServiceClient Build() { ErrorStatsServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ErrorStatsServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ErrorStatsServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ErrorStatsServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ErrorStatsServiceClient.Create(callInvoker, Settings); } private async stt::Task<ErrorStatsServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ErrorStatsServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ErrorStatsServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ErrorStatsServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ErrorStatsServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ErrorStatsService client wrapper, for convenient use.</summary> /// <remarks> /// An API for retrieving and managing error statistics as well as data for /// individual events. /// </remarks> public abstract partial class ErrorStatsServiceClient { /// <summary> /// The default endpoint for the ErrorStatsService service, which is a host of /// "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "clouderrorreporting.googleapis.com:443"; /// <summary>The default ErrorStatsService scopes.</summary> /// <remarks> /// The default ErrorStatsService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ErrorStatsServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ErrorStatsServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ErrorStatsServiceClient"/>.</returns> public static stt::Task<ErrorStatsServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ErrorStatsServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ErrorStatsServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ErrorStatsServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create() => new ErrorStatsServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ErrorStatsServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> internal static ErrorStatsServiceClient Create(grpccore::CallInvoker callInvoker, ErrorStatsServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ErrorStatsService.ErrorStatsServiceClient grpcClient = new ErrorStatsService.ErrorStatsServiceClient(callInvoker); return new ErrorStatsServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ErrorStatsService client</summary> public virtual ErrorStatsService.ErrorStatsServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}` /// and `{projectNumber}` can be found in the /// [Google Cloud Console](https://support.google.com/cloud/answer/6158840). /// /// Examples: `projects/my-project-123`, `projects/5551234`. /// </param> /// <param name="timeRange"> /// Optional. List data for the given time range. /// If not set, a default time range is used. The field /// &amp;lt;code&amp;gt;time_range_begin&amp;lt;/code&amp;gt; in the response will specify the beginning /// of this time range. /// Only &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit /// &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list. If a &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list is given, also /// &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with zero occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(string projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStats(new ListGroupStatsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), TimeRange = timeRange, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}` /// and `{projectNumber}` can be found in the /// [Google Cloud Console](https://support.google.com/cloud/answer/6158840). /// /// Examples: `projects/my-project-123`, `projects/5551234`. /// </param> /// <param name="timeRange"> /// Optional. List data for the given time range. /// If not set, a default time range is used. The field /// &amp;lt;code&amp;gt;time_range_begin&amp;lt;/code&amp;gt; in the response will specify the beginning /// of this time range. /// Only &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit /// &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list. If a &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list is given, also /// &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with zero occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(string projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStatsAsync(new ListGroupStatsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), TimeRange = timeRange, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}` /// and `{projectNumber}` can be found in the /// [Google Cloud Console](https://support.google.com/cloud/answer/6158840). /// /// Examples: `projects/my-project-123`, `projects/5551234`. /// </param> /// <param name="timeRange"> /// Optional. List data for the given time range. /// If not set, a default time range is used. The field /// &amp;lt;code&amp;gt;time_range_begin&amp;lt;/code&amp;gt; in the response will specify the beginning /// of this time range. /// Only &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit /// &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list. If a &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list is given, also /// &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with zero occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(gagr::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStats(new ListGroupStatsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = timeRange, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}` /// and `{projectNumber}` can be found in the /// [Google Cloud Console](https://support.google.com/cloud/answer/6158840). /// /// Examples: `projects/my-project-123`, `projects/5551234`. /// </param> /// <param name="timeRange"> /// Optional. List data for the given time range. /// If not set, a default time range is used. The field /// &amp;lt;code&amp;gt;time_range_begin&amp;lt;/code&amp;gt; in the response will specify the beginning /// of this time range. /// Only &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit /// &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list. If a &amp;lt;code&amp;gt;group_id&amp;lt;/code&amp;gt; list is given, also /// &amp;lt;code&amp;gt;ErrorGroupStats&amp;lt;/code&amp;gt; with zero occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(gagr::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStatsAsync(new ListGroupStatsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = timeRange, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the specified events. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// Required. The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(string projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEvents(new ListEventsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// Required. The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(string projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEventsAsync(new ListEventsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// Required. The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(gagr::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEvents(new ListEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// Required. The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(gagr::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEventsAsync(new ListEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual DeleteEventsResponse DeleteEvents(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, st::CancellationToken cancellationToken) => DeleteEventsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual DeleteEventsResponse DeleteEvents(string projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEvents(new DeleteEventsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(string projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEventsAsync(new DeleteEventsRequest { ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(string projectName, st::CancellationToken cancellationToken) => DeleteEventsAsync(projectName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual DeleteEventsResponse DeleteEvents(gagr::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEvents(new DeleteEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(gagr::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEventsAsync(new DeleteEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// Required. The resource name of the Google Cloud Platform project. Written /// as `projects/{projectID}`, where `{projectID}` is the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// /// Example: `projects/my-project-123`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(gagr::ProjectName projectName, st::CancellationToken cancellationToken) => DeleteEventsAsync(projectName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ErrorStatsService client wrapper implementation, for convenient use.</summary> /// <remarks> /// An API for retrieving and managing error statistics as well as data for /// individual events. /// </remarks> public sealed partial class ErrorStatsServiceClientImpl : ErrorStatsServiceClient { private readonly gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> _callListGroupStats; private readonly gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> _callListEvents; private readonly gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> _callDeleteEvents; /// <summary> /// Constructs a client wrapper for the ErrorStatsService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ErrorStatsServiceSettings"/> used within this client.</param> public ErrorStatsServiceClientImpl(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings settings) { GrpcClient = grpcClient; ErrorStatsServiceSettings effectiveSettings = settings ?? ErrorStatsServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListGroupStats = clientHelper.BuildApiCall<ListGroupStatsRequest, ListGroupStatsResponse>(grpcClient.ListGroupStatsAsync, grpcClient.ListGroupStats, effectiveSettings.ListGroupStatsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName); Modify_ApiCall(ref _callListGroupStats); Modify_ListGroupStatsApiCall(ref _callListGroupStats); _callListEvents = clientHelper.BuildApiCall<ListEventsRequest, ListEventsResponse>(grpcClient.ListEventsAsync, grpcClient.ListEvents, effectiveSettings.ListEventsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName); Modify_ApiCall(ref _callListEvents); Modify_ListEventsApiCall(ref _callListEvents); _callDeleteEvents = clientHelper.BuildApiCall<DeleteEventsRequest, DeleteEventsResponse>(grpcClient.DeleteEventsAsync, grpcClient.DeleteEvents, effectiveSettings.DeleteEventsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName); Modify_ApiCall(ref _callDeleteEvents); Modify_DeleteEventsApiCall(ref _callDeleteEvents); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListGroupStatsApiCall(ref gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> call); partial void Modify_ListEventsApiCall(ref gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> call); partial void Modify_DeleteEventsApiCall(ref gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> call); partial void OnConstruction(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ErrorStatsService client</summary> public override ErrorStatsService.ErrorStatsServiceClient GrpcClient { get; } partial void Modify_ListGroupStatsRequest(ref ListGroupStatsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteEventsRequest(ref DeleteEventsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns> public override gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified groups. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns> public override gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override DeleteEventsResponse DeleteEvents(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Sync(request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Async(request, callSettings); } } public partial class ListGroupStatsRequest : gaxgrpc::IPageRequest { } public partial class ListEventsRequest : gaxgrpc::IPageRequest { } public partial class ListGroupStatsResponse : gaxgrpc::IPageResponse<ErrorGroupStats> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<ErrorGroupStats> GetEnumerator() => ErrorGroupStats.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class ListEventsResponse : gaxgrpc::IPageResponse<ErrorEvent> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<ErrorEvent> GetEnumerator() => ErrorEvents.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
#region License // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using FluentMigrator.Runner.BatchParser; using FluentMigrator.Runner.BatchParser.RangeSearchers; using FluentMigrator.Runner.BatchParser.Sources; using NUnit.Framework; namespace FluentMigrator.Tests.Unit.BatchParser { public class RangeSearcherTests { [TestCase(typeof(AnsiSqlIdentifier), 1, 1)] [TestCase(typeof(MySqlIdentifier), 1, 1)] [TestCase(typeof(SqlServerIdentifier), 1, 1)] [TestCase(typeof(SqlString), 1, 1)] [TestCase(typeof(MultiLineComment), 2, 2)] [TestCase(typeof(DoubleDashSingleLineComment), 2, 0)] public void TestConfiguration(Type type, int startLength, int endLength) { var instance = Activator.CreateInstance(type); Assert.IsInstanceOf<IRangeSearcher>(instance); var rangeSearcher = (IRangeSearcher)instance; Assert.AreEqual(startLength, rangeSearcher.StartCodeLength); Assert.AreEqual(endLength, rangeSearcher.EndCodeLength); } [TestCase(" \"qweqwe\" ", "qweqwe")] [TestCase(@" ""qwe\""qweqwe"" ", "qwe\\")] public void TestAnsiSqlIdentifiers(string input, string expected) { var source = new LinesSource(new[] { input }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new AnsiSqlIdentifier(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); var endIndex = endInfo.Index; var result = reader.ReadString(endIndex - reader.Index); Assert.AreEqual(expected, result); } [TestCase(" `qweqwe` ", "qweqwe")] [TestCase(" `qwe``qweqwe` ", "qwe``qweqwe")] public void TestMySqlIdentifiers(string input, string expected) { var source = new LinesSource(new[] { input }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new MySqlIdentifier(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); var endIndex = endInfo.Index; var result = reader.ReadString(endIndex - reader.Index); Assert.AreEqual(expected, result); } [TestCase(" [qweqwe] ", "qweqwe")] [TestCase(" [qwe]]qweqwe] ", "qwe]]qweqwe")] public void TestSqlServerIdentifiers(string input, string expected) { var source = new LinesSource(new[] { input }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new SqlServerIdentifier(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); var endIndex = endInfo.Index; var result = reader.ReadString(endIndex - reader.Index); Assert.AreEqual(expected, result); } [TestCase(" 'qweqwe' ", "qweqwe")] [TestCase(" 'qweqwe'", "qweqwe")] [TestCase(" 'qwe''qweqwe' ", "qwe''qweqwe")] public void TestSqlString(string input, string expected) { var source = new LinesSource(new[] { input }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new SqlString(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); var endIndex = endInfo.Index; var result = reader.ReadString(endIndex - reader.Index); Assert.AreEqual(expected, result); } [TestCase(" 'qweqwe")] public void TestIncompleteSqlString(string input) { var source = new LinesSource(new[] { input }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new SqlString(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNull(endInfo); } [Test] public void TestMissingSqlString() { var source = new LinesSource(new[] { string.Empty }); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new SqlString(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreEqual(-1, startIndex); } [TestCase(" /* blah */ ", " blah ")] [TestCase(" /* blah /* blubb */ ", " blah /* blubb ")] public void TestMultiLineCommentWithSingleLine(string input, string expected) { var source = new TextReaderSource(new StringReader(input)); var reader = source.CreateReader(); Assert.IsNotNull(reader); var rangeSearcher = new MultiLineComment(); var startIndex = rangeSearcher.FindStartCode(reader); Assert.AreNotEqual(-1, startIndex); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); var endIndex = endInfo.Index; var result = reader.ReadString(endIndex - reader.Index); Assert.AreEqual(expected, result); } [TestCase("/** blah\n * blubb\n*/ ", "* blah\n * blubb\n")] public void TestMultiLineCommentWithMultipleLines(string input, string expected) { using (var source = new TextReaderSource(new StringReader(input), true)) { var reader = source.CreateReader(); Assert.IsNotNull(reader); var foundStart = false; var content = new StringBuilder(); var writer = new StringWriter(content) { NewLine = "\n", }; var rangeSearcher = new MultiLineComment(); while (reader != null) { if (!foundStart) { var startIndex = rangeSearcher.FindStartCode(reader); if (startIndex == -1) { reader = reader.Advance(reader.Length); continue; } foundStart = true; reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); } var endInfo = rangeSearcher.FindEndCode(reader); if (endInfo == null) { writer.WriteLine(reader.ReadString(reader.Length)); reader = reader.Advance(reader.Length); continue; } var contentLength = endInfo.Index - reader.Index; writer.Write(reader.ReadString(contentLength)); reader = reader.Advance(contentLength + rangeSearcher.EndCodeLength); foundStart = false; } Assert.IsFalse(foundStart); Assert.AreEqual(expected, content.ToString()); } } [TestCase(" -- qweqwe", " qweqwe", " ")] [TestCase(" -- qwe\nqwe", " qwe", " \nqwe")] [TestCase("asd -- qwe\nqwe", " qwe", "asd \nqwe")] public void TestDoubleDashSingleLineComment(string input, string expectedComment, string expectedOther) { var source = new TextReaderSource(new StringReader(input)); var reader = source.CreateReader(); Assert.IsNotNull(reader); var commentContent = new StringBuilder(); var commentWriter = new StringWriter(commentContent) { NewLine = "\n", }; var otherContent = new StringBuilder(); var otherWriter = new StringWriter(otherContent) { NewLine = "\n", }; var addNewLine = false; var rangeSearcher = new DoubleDashSingleLineComment(); while (reader != null) { if (addNewLine) otherWriter.WriteLine(); var startIndex = rangeSearcher.FindStartCode(reader); if (startIndex == -1) { otherWriter.Write(reader.ReadString(reader.Length)); addNewLine = true; reader = reader.Advance(reader.Length); continue; } otherWriter.Write(reader.ReadString(startIndex)); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); var contentLength = endInfo.Index - reader.Index; commentWriter.Write(reader.ReadString(contentLength)); addNewLine = (contentLength + rangeSearcher.EndCodeLength) == reader.Length; reader = reader.Advance(contentLength + rangeSearcher.EndCodeLength); } Assert.AreEqual(expectedComment, commentContent.ToString()); Assert.AreEqual(expectedOther, otherContent.ToString()); } [TestCase(" # qweqwe", " qweqwe", " ")] [TestCase(" # qwe\nqwe", " qwe", " \nqwe")] [TestCase("asd # qwe\nqwe", "", "asd # qwe\nqwe")] public void TestPoundSignSingleLineComment(string input, string expectedComment, string expectedOther) { var source = new TextReaderSource(new StringReader(input)); var reader = source.CreateReader(); Assert.IsNotNull(reader); var commentContent = new StringBuilder(); var commentWriter = new StringWriter(commentContent) { NewLine = "\n", }; var otherContent = new StringBuilder(); var otherWriter = new StringWriter(otherContent) { NewLine = "\n", }; var addNewLine = false; var rangeSearcher = new PoundSignSingleLineComment(); while (reader != null) { if (addNewLine) otherWriter.WriteLine(); var startIndex = rangeSearcher.FindStartCode(reader); if (startIndex == -1) { otherWriter.Write(reader.ReadString(reader.Length)); addNewLine = true; reader = reader.Advance(reader.Length); continue; } otherWriter.Write(reader.ReadString(startIndex)); reader = reader.Advance(startIndex + rangeSearcher.StartCodeLength); Assert.IsNotNull(reader); var endInfo = rangeSearcher.FindEndCode(reader); Assert.IsNotNull(endInfo); var contentLength = endInfo.Index - reader.Index; commentWriter.Write(reader.ReadString(contentLength)); addNewLine = (contentLength + rangeSearcher.EndCodeLength) == reader.Length; reader = reader.Advance(contentLength + rangeSearcher.EndCodeLength); } Assert.AreEqual(expectedComment, commentContent.ToString()); Assert.AreEqual(expectedOther, otherContent.ToString()); } [Test] public void TestNestingMultiLineComment() { var searchers = new Stack<IRangeSearcher>(); IRangeSearcher searcher = new NestingMultiLineComment(); var source = new TextReaderSource(new StringReader("/* /* */ */")); var reader = source.CreateReader(); Assert.IsNotNull(reader); Assert.AreEqual(0, searcher.FindStartCode(reader)); reader = reader.Advance(2); Assert.IsNotNull(reader); var endInfo = searcher.FindEndCode(reader); Assert.NotNull(endInfo); Assert.True(endInfo.IsNestedStart); searchers.Push(searcher); searcher = endInfo.NestedRangeSearcher; Assert.NotNull(searcher); Assert.AreEqual(3, endInfo.Index); reader = reader.Advance(endInfo.Index - reader.Index + searcher.StartCodeLength); Assert.IsNotNull(reader); endInfo = searcher.FindEndCode(reader); Assert.NotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); Assert.AreEqual(6, endInfo.Index); reader = reader.Advance(endInfo.Index - reader.Index + searcher.EndCodeLength); Assert.IsNotNull(reader); searcher = searchers.Pop(); endInfo = searcher.FindEndCode(reader); Assert.NotNull(endInfo); Assert.IsFalse(endInfo.IsNestedStart); Assert.AreEqual(9, endInfo.Index); reader = reader.Advance(endInfo.Index - reader.Index + searcher.EndCodeLength); Assert.IsNull(reader); } } }
using System; using System.Collections.Generic; using System.Linq; namespace XCommon.Util { public static class MimeTypeMap { private static readonly Lazy<IDictionary<string, string>> _mappings = new Lazy<IDictionary<string, string>>(BuildMappings); private static IDictionary<string, string> BuildMappings() { #region Mime types List var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {".323", "text/h323"}, {".3g2", "video/3gpp2"}, {".3gp", "video/3gpp"}, {".3gp2", "video/3gpp2"}, {".3gpp", "video/3gpp"}, {".7z", "application/x-7z-compressed"}, {".aa", "audio/audible"}, {".AAC", "audio/aac"}, {".aaf", "application/octet-stream"}, {".aax", "audio/vnd.audible.aax"}, {".ac3", "audio/ac3"}, {".aca", "application/octet-stream"}, {".accda", "application/msaccess.addin"}, {".accdb", "application/msaccess"}, {".accdc", "application/msaccess.cab"}, {".accde", "application/msaccess"}, {".accdr", "application/msaccess.runtime"}, {".accdt", "application/msaccess"}, {".accdw", "application/msaccess.webapplication"}, {".accft", "application/msaccess.ftemplate"}, {".acx", "application/internet-property-stream"}, {".AddIn", "text/xml"}, {".ade", "application/msaccess"}, {".adobebridge", "application/x-bridge-url"}, {".adp", "application/msaccess"}, {".ADT", "audio/vnd.dlna.adts"}, {".ADTS", "audio/aac"}, {".afm", "application/octet-stream"}, {".ai", "application/postscript"}, {".aif", "audio/aiff"}, {".aifc", "audio/aiff"}, {".aiff", "audio/aiff"}, {".air", "application/vnd.adobe.air-application-installer-package+zip"}, {".amc", "application/mpeg"}, {".anx", "application/annodex"}, {".apk", "application/vnd.android.package-archive" }, {".application", "application/x-ms-application"}, {".art", "image/x-jg"}, {".asa", "application/xml"}, {".asax", "application/xml"}, {".ascx", "application/xml"}, {".asd", "application/octet-stream"}, {".asf", "video/x-ms-asf"}, {".ashx", "application/xml"}, {".asi", "application/octet-stream"}, {".asm", "text/plain"}, {".asmx", "application/xml"}, {".aspx", "application/xml"}, {".asr", "video/x-ms-asf"}, {".asx", "video/x-ms-asf"}, {".atom", "application/atom+xml"}, {".au", "audio/basic"}, {".avi", "video/x-msvideo"}, {".axa", "audio/annodex"}, {".axs", "application/olescript"}, {".axv", "video/annodex"}, {".bas", "text/plain"}, {".bcpio", "application/x-bcpio"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".cab", "application/octet-stream"}, {".caf", "audio/x-caf"}, {".calx", "application/vnd.ms-office.calx"}, {".cat", "application/vnd.ms-pki.seccat"}, {".cc", "text/plain"}, {".cd", "text/plain"}, {".cdda", "audio/aiff"}, {".cdf", "application/x-cdf"}, {".cer", "application/x-x509-ca-cert"}, {".cfg", "text/plain"}, {".chm", "application/octet-stream"}, {".class", "application/x-java-applet"}, {".clp", "application/x-msclip"}, {".cmd", "text/plain"}, {".cmx", "image/x-cmx"}, {".cnf", "text/plain"}, {".cod", "image/cis-cod"}, {".config", "application/xml"}, {".contact", "text/x-ms-contact"}, {".coverage", "application/xml"}, {".cpio", "application/x-cpio"}, {".cpp", "text/plain"}, {".crd", "application/x-mscardfile"}, {".crl", "application/pkix-crl"}, {".crt", "application/x-x509-ca-cert"}, {".cs", "text/plain"}, {".csdproj", "text/plain"}, {".csh", "application/x-csh"}, {".csproj", "text/plain"}, {".css", "text/css"}, {".csv", "text/csv"}, {".cur", "application/octet-stream"}, {".cxx", "text/plain"}, {".dat", "application/octet-stream"}, {".datasource", "application/xml"}, {".dbproj", "text/plain"}, {".dcr", "application/x-director"}, {".def", "text/plain"}, {".deploy", "application/octet-stream"}, {".der", "application/x-x509-ca-cert"}, {".dgml", "application/xml"}, {".dib", "image/bmp"}, {".dif", "video/x-dv"}, {".dir", "application/x-director"}, {".disco", "text/xml"}, {".divx", "video/divx"}, {".dll", "application/x-msdownload"}, {".dll.config", "text/xml"}, {".dlm", "text/dlm"}, {".doc", "application/msword"}, {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".dot", "application/msword"}, {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, {".dsp", "application/octet-stream"}, {".dsw", "text/plain"}, {".dtd", "text/xml"}, {".dtsConfig", "text/xml"}, {".dv", "video/x-dv"}, {".dvi", "application/x-dvi"}, {".dwf", "drawing/x-dwf"}, {".dwg", "application/acad"}, {".dwp", "application/octet-stream"}, {".dxf", "application/x-dxf" }, {".dxr", "application/x-director"}, {".eml", "message/rfc822"}, {".emz", "application/octet-stream"}, {".eot", "application/vnd.ms-fontobject"}, {".eps", "application/postscript"}, {".etl", "application/etl"}, {".etx", "text/x-setext"}, {".evy", "application/envoy"}, {".exe", "application/octet-stream"}, {".exe.config", "text/xml"}, {".fdf", "application/vnd.fdf"}, {".fif", "application/fractals"}, {".filters", "application/xml"}, {".fla", "application/octet-stream"}, {".flac", "audio/flac"}, {".flr", "x-world/x-vrml"}, {".flv", "video/x-flv"}, {".fsscript", "application/fsharp-script"}, {".fsx", "application/fsharp-script"}, {".generictest", "application/xml"}, {".gif", "image/gif"}, {".gpx", "application/gpx+xml"}, {".group", "text/x-ms-group"}, {".gsm", "audio/x-gsm"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".hdf", "application/x-hdf"}, {".hdml", "text/x-hdml"}, {".hhc", "application/x-oleobject"}, {".hhk", "application/octet-stream"}, {".hhp", "application/octet-stream"}, {".hlp", "application/winhlp"}, {".hpp", "text/plain"}, {".hqx", "application/mac-binhex40"}, {".hta", "application/hta"}, {".htc", "text/x-component"}, {".htm", "text/html"}, {".html", "text/html"}, {".htt", "text/webviewhtml"}, {".hxa", "application/xml"}, {".hxc", "application/xml"}, {".hxd", "application/octet-stream"}, {".hxe", "application/xml"}, {".hxf", "application/xml"}, {".hxh", "application/octet-stream"}, {".hxi", "application/octet-stream"}, {".hxk", "application/xml"}, {".hxq", "application/octet-stream"}, {".hxr", "application/octet-stream"}, {".hxs", "application/octet-stream"}, {".hxt", "text/html"}, {".hxv", "application/xml"}, {".hxw", "application/octet-stream"}, {".hxx", "text/plain"}, {".i", "text/plain"}, {".ico", "image/x-icon"}, {".ics", "application/octet-stream"}, {".idl", "text/plain"}, {".ief", "image/ief"}, {".iii", "application/x-iphone"}, {".inc", "text/plain"}, {".inf", "application/octet-stream"}, {".ini", "text/plain"}, {".inl", "text/plain"}, {".ins", "application/x-internet-signup"}, {".ipa", "application/x-itunes-ipa"}, {".ipg", "application/x-itunes-ipg"}, {".ipproj", "text/plain"}, {".ipsw", "application/x-itunes-ipsw"}, {".iqy", "text/x-ms-iqy"}, {".isp", "application/x-internet-signup"}, {".ite", "application/x-itunes-ite"}, {".itlp", "application/x-itunes-itlp"}, {".itms", "application/x-itunes-itms"}, {".itpc", "application/x-itunes-itpc"}, {".IVF", "video/x-ivf"}, {".jar", "application/java-archive"}, {".java", "application/octet-stream"}, {".jck", "application/liquidmotion"}, {".jcz", "application/liquidmotion"}, {".jfif", "image/pjpeg"}, {".jnlp", "application/x-java-jnlp-file"}, {".jpb", "application/octet-stream"}, {".jpe", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/javascript"}, {".json", "application/json"}, {".jsx", "text/jscript"}, {".jsxbin", "text/plain"}, {".latex", "application/x-latex"}, {".library-ms", "application/windows-library+xml"}, {".lit", "application/x-ms-reader"}, {".loadtest", "application/xml"}, {".lpk", "application/octet-stream"}, {".lsf", "video/x-la-asf"}, {".lst", "text/plain"}, {".lsx", "video/x-la-asf"}, {".lzh", "application/octet-stream"}, {".m13", "application/x-msmediaview"}, {".m14", "application/x-msmediaview"}, {".m1v", "video/mpeg"}, {".m2t", "video/vnd.dlna.mpeg-tts"}, {".m2ts", "video/vnd.dlna.mpeg-tts"}, {".m2v", "video/mpeg"}, {".m3u", "audio/x-mpegurl"}, {".m3u8", "audio/x-mpegurl"}, {".m4a", "audio/m4a"}, {".m4b", "audio/m4b"}, {".m4p", "audio/m4p"}, {".m4r", "audio/x-m4r"}, {".m4v", "video/x-m4v"}, {".mac", "image/x-macpaint"}, {".mak", "text/plain"}, {".man", "application/x-troff-man"}, {".manifest", "application/x-ms-manifest"}, {".map", "text/plain"}, {".master", "application/xml"}, {".mbox", "application/mbox"}, {".mda", "application/msaccess"}, {".mdb", "application/x-msaccess"}, {".mde", "application/msaccess"}, {".mdp", "application/octet-stream"}, {".me", "application/x-troff-me"}, {".mfp", "application/x-shockwave-flash"}, {".mht", "message/rfc822"}, {".mhtml", "message/rfc822"}, {".mid", "audio/mid"}, {".midi", "audio/mid"}, {".mix", "application/octet-stream"}, {".mk", "text/plain"}, {".mk3d", "video/x-matroska-3d"}, {".mka", "audio/x-matroska"}, {".mkv", "video/x-matroska"}, {".mmf", "application/x-smaf"}, {".mno", "text/xml"}, {".mny", "application/x-msmoney"}, {".mod", "video/mpeg"}, {".mov", "video/quicktime"}, {".movie", "video/x-sgi-movie"}, {".mp2", "video/mpeg"}, {".mp2v", "video/mpeg"}, {".mp3", "audio/mpeg"}, {".mp4", "video/mp4"}, {".mp4v", "video/mp4"}, {".mpa", "video/mpeg"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpf", "application/vnd.ms-mediapackage"}, {".mpg", "video/mpeg"}, {".mpp", "application/vnd.ms-project"}, {".mpv2", "video/mpeg"}, {".mqv", "video/quicktime"}, {".ms", "application/x-troff-ms"}, {".msg", "application/vnd.ms-outlook"}, {".msi", "application/octet-stream"}, {".mso", "application/octet-stream"}, {".mts", "video/vnd.dlna.mpeg-tts"}, {".mtx", "application/xml"}, {".mvb", "application/x-msmediaview"}, {".mvc", "application/x-miva-compiled"}, {".mxp", "application/x-mmxp"}, {".nc", "application/x-netcdf"}, {".nsc", "video/x-ms-asf"}, {".nws", "message/rfc822"}, {".ocx", "application/octet-stream"}, {".oda", "application/oda"}, {".odb", "application/vnd.oasis.opendocument.database"}, {".odc", "application/vnd.oasis.opendocument.chart"}, {".odf", "application/vnd.oasis.opendocument.formula"}, {".odg", "application/vnd.oasis.opendocument.graphics"}, {".odh", "text/plain"}, {".odi", "application/vnd.oasis.opendocument.image"}, {".odl", "text/plain"}, {".odm", "application/vnd.oasis.opendocument.text-master"}, {".odp", "application/vnd.oasis.opendocument.presentation"}, {".ods", "application/vnd.oasis.opendocument.spreadsheet"}, {".odt", "application/vnd.oasis.opendocument.text"}, {".oga", "audio/ogg"}, {".ogg", "audio/ogg"}, {".ogv", "video/ogg"}, {".ogx", "application/ogg"}, {".one", "application/onenote"}, {".onea", "application/onenote"}, {".onepkg", "application/onenote"}, {".onetmp", "application/onenote"}, {".onetoc", "application/onenote"}, {".onetoc2", "application/onenote"}, {".opus", "audio/ogg"}, {".orderedtest", "application/xml"}, {".osdx", "application/opensearchdescription+xml"}, {".otf", "application/font-sfnt"}, {".otg", "application/vnd.oasis.opendocument.graphics-template"}, {".oth", "application/vnd.oasis.opendocument.text-web"}, {".otp", "application/vnd.oasis.opendocument.presentation-template"}, {".ots", "application/vnd.oasis.opendocument.spreadsheet-template"}, {".ott", "application/vnd.oasis.opendocument.text-template"}, {".oxt", "application/vnd.openofficeorg.extension"}, {".p10", "application/pkcs10"}, {".p12", "application/x-pkcs12"}, {".p7b", "application/x-pkcs7-certificates"}, {".p7c", "application/pkcs7-mime"}, {".p7m", "application/pkcs7-mime"}, {".p7r", "application/x-pkcs7-certreqresp"}, {".p7s", "application/pkcs7-signature"}, {".pbm", "image/x-portable-bitmap"}, {".pcast", "application/x-podcast"}, {".pct", "image/pict"}, {".pcx", "application/octet-stream"}, {".pcz", "application/octet-stream"}, {".pdf", "application/pdf"}, {".pfb", "application/octet-stream"}, {".pfm", "application/octet-stream"}, {".pfx", "application/x-pkcs12"}, {".pgm", "image/x-portable-graymap"}, {".pic", "image/pict"}, {".pict", "image/pict"}, {".pkgdef", "text/plain"}, {".pkgundef", "text/plain"}, {".pko", "application/vnd.ms-pki.pko"}, {".pls", "audio/scpls"}, {".pma", "application/x-perfmon"}, {".pmc", "application/x-perfmon"}, {".pml", "application/x-perfmon"}, {".pmr", "application/x-perfmon"}, {".pmw", "application/x-perfmon"}, {".png", "image/png"}, {".pnm", "image/x-portable-anymap"}, {".pnt", "image/x-macpaint"}, {".pntg", "image/x-macpaint"}, {".pnz", "image/png"}, {".pot", "application/vnd.ms-powerpoint"}, {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, {".ppa", "application/vnd.ms-powerpoint"}, {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, {".ppm", "image/x-portable-pixmap"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prf", "application/pics-rules"}, {".prm", "application/octet-stream"}, {".prx", "application/octet-stream"}, {".ps", "application/postscript"}, {".psc1", "application/PowerShell"}, {".psd", "application/octet-stream"}, {".psess", "application/xml"}, {".psm", "application/octet-stream"}, {".psp", "application/octet-stream"}, {".pst", "application/vnd.ms-outlook"}, {".pub", "application/x-mspublisher"}, {".pwz", "application/vnd.ms-powerpoint"}, {".qht", "text/x-html-insertion"}, {".qhtm", "text/x-html-insertion"}, {".qt", "video/quicktime"}, {".qti", "image/x-quicktime"}, {".qtif", "image/x-quicktime"}, {".qtl", "application/x-quicktimeplayer"}, {".qxd", "application/octet-stream"}, {".ra", "audio/x-pn-realaudio"}, {".ram", "audio/x-pn-realaudio"}, {".rar", "application/x-rar-compressed"}, {".ras", "image/x-cmu-raster"}, {".rat", "application/rat-file"}, {".rc", "text/plain"}, {".rc2", "text/plain"}, {".rct", "text/plain"}, {".rdlc", "application/xml"}, {".reg", "text/plain"}, {".resx", "application/xml"}, {".rf", "image/vnd.rn-realflash"}, {".rgb", "image/x-rgb"}, {".rgs", "text/plain"}, {".rm", "application/vnd.rn-realmedia"}, {".rmi", "audio/mid"}, {".rmp", "application/vnd.rn-rn_music_package"}, {".roff", "application/x-troff"}, {".rpm", "audio/x-pn-realaudio-plugin"}, {".rqy", "text/x-ms-rqy"}, {".rtf", "application/rtf"}, {".rtx", "text/richtext"}, {".rvt", "application/octet-stream" }, {".ruleset", "application/xml"}, {".s", "text/plain"}, {".safariextz", "application/x-safari-safariextz"}, {".scd", "application/x-msschedule"}, {".scr", "text/plain"}, {".sct", "text/scriptlet"}, {".sd2", "audio/x-sd2"}, {".sdp", "application/sdp"}, {".sea", "application/octet-stream"}, {".searchConnector-ms", "application/windows-search-connector+xml"}, {".setpay", "application/set-payment-initiation"}, {".setreg", "application/set-registration-initiation"}, {".settings", "application/xml"}, {".sgimb", "application/x-sgimb"}, {".sgml", "text/sgml"}, {".sh", "application/x-sh"}, {".shar", "application/x-shar"}, {".shtml", "text/html"}, {".sit", "application/x-stuffit"}, {".sitemap", "application/xml"}, {".skin", "application/xml"}, {".skp", "application/x-koan" }, {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, {".slk", "application/vnd.ms-excel"}, {".sln", "text/plain"}, {".slupkg-ms", "application/x-ms-license"}, {".smd", "audio/x-smd"}, {".smi", "application/octet-stream"}, {".smx", "audio/x-smd"}, {".smz", "audio/x-smd"}, {".snd", "audio/basic"}, {".snippet", "application/xml"}, {".snp", "application/octet-stream"}, {".sol", "text/plain"}, {".sor", "text/plain"}, {".spc", "application/x-pkcs7-certificates"}, {".spl", "application/futuresplash"}, {".spx", "audio/ogg"}, {".src", "application/x-wais-source"}, {".srf", "text/plain"}, {".SSISDeploymentManifest", "text/xml"}, {".ssm", "application/streamingmedia"}, {".sst", "application/vnd.ms-pki.certstore"}, {".stl", "application/vnd.ms-pki.stl"}, {".sv4cpio", "application/x-sv4cpio"}, {".sv4crc", "application/x-sv4crc"}, {".svc", "application/xml"}, {".svg", "image/svg+xml"}, {".swf", "application/x-shockwave-flash"}, {".step", "application/step"}, {".stp", "application/step"}, {".t", "application/x-troff"}, {".tar", "application/x-tar"}, {".tcl", "application/x-tcl"}, {".testrunconfig", "application/xml"}, {".testsettings", "application/xml"}, {".tex", "application/x-tex"}, {".texi", "application/x-texinfo"}, {".texinfo", "application/x-texinfo"}, {".tgz", "application/x-compressed"}, {".thmx", "application/vnd.ms-officetheme"}, {".thn", "application/octet-stream"}, {".tif", "image/tiff"}, {".tiff", "image/tiff"}, {".tlh", "text/plain"}, {".tli", "text/plain"}, {".toc", "application/octet-stream"}, {".tr", "application/x-troff"}, {".trm", "application/x-msterminal"}, {".trx", "application/xml"}, {".ts", "video/vnd.dlna.mpeg-tts"}, {".tsv", "text/tab-separated-values"}, {".ttf", "application/font-sfnt"}, {".tts", "video/vnd.dlna.mpeg-tts"}, {".txt", "text/plain"}, {".u32", "application/octet-stream"}, {".uls", "text/iuls"}, {".user", "text/plain"}, {".ustar", "application/x-ustar"}, {".vb", "text/plain"}, {".vbdproj", "text/plain"}, {".vbk", "video/mpeg"}, {".vbproj", "text/plain"}, {".vbs", "text/vbscript"}, {".vcf", "text/x-vcard"}, {".vcproj", "application/xml"}, {".vcs", "text/plain"}, {".vcxproj", "application/xml"}, {".vddproj", "text/plain"}, {".vdp", "text/plain"}, {".vdproj", "text/plain"}, {".vdx", "application/vnd.ms-visio.viewer"}, {".vml", "text/xml"}, {".vscontent", "application/xml"}, {".vsct", "text/xml"}, {".vsd", "application/vnd.visio"}, {".vsi", "application/ms-vsi"}, {".vsix", "application/vsix"}, {".vsixlangpack", "text/xml"}, {".vsixmanifest", "text/xml"}, {".vsmdi", "application/xml"}, {".vspscc", "text/plain"}, {".vss", "application/vnd.visio"}, {".vsscc", "text/plain"}, {".vssettings", "text/xml"}, {".vssscc", "text/plain"}, {".vst", "application/vnd.visio"}, {".vstemplate", "text/xml"}, {".vsto", "application/x-ms-vsto"}, {".vsw", "application/vnd.visio"}, {".vsx", "application/vnd.visio"}, {".vtx", "application/vnd.visio"}, {".wasm", "application/wasm"}, {".wav", "audio/wav"}, {".wave", "audio/wav"}, {".wax", "audio/x-ms-wax"}, {".wbk", "application/msword"}, {".wbmp", "image/vnd.wap.wbmp"}, {".wcm", "application/vnd.ms-works"}, {".wdb", "application/vnd.ms-works"}, {".wdp", "image/vnd.ms-photo"}, {".webarchive", "application/x-safari-webarchive"}, {".webm", "video/webm"}, {".webp", "image/webp"}, /* https://en.wikipedia.org/wiki/WebP */ {".webtest", "application/xml"}, {".wiq", "application/xml"}, {".wiz", "application/msword"}, {".wks", "application/vnd.ms-works"}, {".WLMP", "application/wlmoviemaker"}, {".wlpginstall", "application/x-wlpg-detect"}, {".wlpginstall3", "application/x-wlpg3-detect"}, {".wm", "video/x-ms-wm"}, {".wma", "audio/x-ms-wma"}, {".wmd", "application/x-ms-wmd"}, {".wmf", "application/x-msmetafile"}, {".wml", "text/vnd.wap.wml"}, {".wmlc", "application/vnd.wap.wmlc"}, {".wmls", "text/vnd.wap.wmlscript"}, {".wmlsc", "application/vnd.wap.wmlscriptc"}, {".wmp", "video/x-ms-wmp"}, {".wmv", "video/x-ms-wmv"}, {".wmx", "video/x-ms-wmx"}, {".wmz", "application/x-ms-wmz"}, {".woff", "application/font-woff"}, {".woff2", "application/font-woff2"}, {".wpl", "application/vnd.ms-wpl"}, {".wps", "application/vnd.ms-works"}, {".wri", "application/x-mswrite"}, {".wrl", "x-world/x-vrml"}, {".wrz", "x-world/x-vrml"}, {".wsc", "text/scriptlet"}, {".wsdl", "text/xml"}, {".wvx", "video/x-ms-wvx"}, {".x", "application/directx"}, {".xaf", "x-world/x-vrml"}, {".xaml", "application/xaml+xml"}, {".xap", "application/x-silverlight-app"}, {".xbap", "application/x-ms-xbap"}, {".xbm", "image/x-xbitmap"}, {".xdr", "text/plain"}, {".xht", "application/xhtml+xml"}, {".xhtml", "application/xhtml+xml"}, {".xla", "application/vnd.ms-excel"}, {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, {".xlc", "application/vnd.ms-excel"}, {".xld", "application/vnd.ms-excel"}, {".xlk", "application/vnd.ms-excel"}, {".xll", "application/vnd.ms-excel"}, {".xlm", "application/vnd.ms-excel"}, {".xls", "application/vnd.ms-excel"}, {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".xlt", "application/vnd.ms-excel"}, {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, {".xlw", "application/vnd.ms-excel"}, {".xml", "text/xml"}, {".xmp", "application/octet-stream" }, {".xmta", "application/xml"}, {".xof", "x-world/x-vrml"}, {".XOML", "text/plain"}, {".xpm", "image/x-xpixmap"}, {".xps", "application/vnd.ms-xpsdocument"}, {".xrm-ms", "text/xml"}, {".xsc", "application/xml"}, {".xsd", "text/xml"}, {".xsf", "text/xml"}, {".xsl", "text/xml"}, {".xslt", "text/xml"}, {".xsn", "application/octet-stream"}, {".xss", "application/xml"}, {".xspf", "application/xspf+xml"}, {".xtp", "application/octet-stream"}, {".xwd", "image/x-xwindowdump"}, {".z", "application/x-compress"}, {".zip", "application/zip"}, {"application/fsharp-script", ".fsx"}, {"application/msaccess", ".adp"}, {"application/msword", ".doc"}, {"application/octet-stream", ".bin"}, {"application/onenote", ".one"}, {"application/postscript", ".eps"}, {"application/step", ".step"}, {"application/vnd.ms-excel", ".xls"}, {"application/vnd.ms-powerpoint", ".ppt"}, {"application/vnd.ms-works", ".wks"}, {"application/vnd.visio", ".vsd"}, {"application/x-director", ".dir"}, {"application/x-shockwave-flash", ".swf"}, {"application/x-x509-ca-cert", ".cer"}, {"application/x-zip-compressed", ".zip"}, {"application/xhtml+xml", ".xhtml"}, {"application/xml", ".xml"}, // anomoly, .xml -> text/xml, but application/xml -> many thingss, but all are xml, so safest is .xml {"audio/aac", ".AAC"}, {"audio/aiff", ".aiff"}, {"audio/basic", ".snd"}, {"audio/mid", ".midi"}, {"audio/wav", ".wav"}, {"audio/x-m4a", ".m4a"}, {"audio/x-mpegurl", ".m3u"}, {"audio/x-pn-realaudio", ".ra"}, {"audio/x-smd", ".smd"}, {"image/bmp", ".bmp"}, {"image/jpeg", ".jpg"}, {"image/pict", ".pic"}, {"image/png", ".png"}, {"image/tiff", ".tiff"}, {"image/x-macpaint", ".mac"}, {"image/x-quicktime", ".qti"}, {"message/rfc822", ".eml"}, {"text/html", ".html"}, {"text/plain", ".txt"}, {"text/scriptlet", ".wsc"}, {"text/xml", ".xml"}, {"video/3gpp", ".3gp"}, {"video/3gpp2", ".3gp2"}, {"video/mp4", ".mp4"}, {"video/mpeg", ".mpg"}, {"video/quicktime", ".mov"}, {"video/vnd.dlna.mpeg-tts", ".m2t"}, {"video/x-dv", ".dv"}, {"video/x-la-asf", ".lsf"}, {"video/x-ms-asf", ".asf"}, {"x-world/x-vrml", ".xof"}, }; #endregion var cache = mappings.ToList(); foreach (var mapping in cache) { if (!mappings.ContainsKey(mapping.Value)) { mappings.Add(mapping.Value, mapping.Key); } } return mappings; } public static string GetMimeType(string extension) { if (extension == null) { throw new ArgumentNullException("extension"); } if (!extension.StartsWith(".")) { extension = "." + extension; } string mime; return _mappings.Value.TryGetValue(extension, out mime) ? mime : "application/octet-stream"; } public static string GetExtension(string mimeType) { return GetExtension(mimeType, true); } public static string GetExtension(string mimeType, bool throwErrorIfNotFound) { if (mimeType == null) { throw new ArgumentNullException("mimeType"); } if (mimeType.StartsWith(".")) { throw new ArgumentException("Requested mime type is not valid: " + mimeType); } string extension; if (_mappings.Value.TryGetValue(mimeType, out extension)) { return extension; } if (throwErrorIfNotFound) { throw new ArgumentException("Requested mime type is not registered: " + mimeType); } else { return string.Empty; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Redis.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCloudRedisClientTest { [xunit::FactAttribute] public void GetInstanceRequestObject() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance response = client.GetInstance(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceRequestObjectAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance responseCallSettings = await client.GetInstanceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Instance responseCancellationToken = await client.GetInstanceAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstance() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance response = client.GetInstance(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance responseCallSettings = await client.GetInstanceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Instance responseCancellationToken = await client.GetInstanceAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceResourceNames() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance response = client.GetInstance(request.InstanceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceResourceNamesAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Instance expectedResponse = new Instance { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), DisplayName = "display_name137f65c2", Labels = { { "key8a0b6e3c", "value60c16320" }, }, LocationId = "location_iddaa574e2", AlternativeLocationId = "alternative_location_id9b86fe18", RedisVersion = "redis_version52f1f9d8", ReservedIpRange = "reserved_ip_range779ab299", Host = "hosta8dbb367", Port = -78310000, CurrentLocationId = "current_location_id65ef644c", CreateTime = new wkt::Timestamp(), State = Instance.Types.State.Updating, StatusMessage = "status_message2c618f86", RedisConfigs = { { "key8a0b6e3c", "value60c16320" }, }, Tier = Instance.Types.Tier.Basic, MemorySizeGb = 863378110, AuthorizedNetwork = "authorized_network63563381", PersistenceIamIdentity = "persistence_iam_identitye8d96e46", ConnectMode = Instance.Types.ConnectMode.Unspecified, AuthEnabled = false, ServerCaCerts = { new TlsCertificate(), }, TransitEncryptionMode = Instance.Types.TransitEncryptionMode.Disabled, MaintenancePolicy = new MaintenancePolicy(), MaintenanceSchedule = new MaintenanceSchedule(), SecondaryIpRange = "secondary_ip_range516c3dce", ReplicaCount = -2132170114, Nodes = { new NodeInfo(), }, ReadEndpoint = "read_endpointb6c6d0a1", ReadEndpointPort = 906869138, ReadReplicasMode = Instance.Types.ReadReplicasMode.ReadReplicasEnabled, PersistenceConfig = new PersistenceConfig(), }; mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); Instance responseCallSettings = await client.GetInstanceAsync(request.InstanceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Instance responseCancellationToken = await client.GetInstanceAsync(request.InstanceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceAuthStringRequestObject() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthString(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString response = client.GetInstanceAuthString(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceAuthStringRequestObjectAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthStringAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceAuthString>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString responseCallSettings = await client.GetInstanceAuthStringAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceAuthString responseCancellationToken = await client.GetInstanceAuthStringAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceAuthString() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthString(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString response = client.GetInstanceAuthString(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceAuthStringAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthStringAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceAuthString>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString responseCallSettings = await client.GetInstanceAuthStringAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceAuthString responseCancellationToken = await client.GetInstanceAuthStringAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceAuthStringResourceNames() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthString(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString response = client.GetInstanceAuthString(request.InstanceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceAuthStringResourceNamesAsync() { moq::Mock<CloudRedis.CloudRedisClient> mockGrpcClient = new moq::Mock<CloudRedis.CloudRedisClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceAuthStringRequest request = new GetInstanceAuthStringRequest { InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceAuthString expectedResponse = new InstanceAuthString { AuthString = "auth_string7b7a4b11", }; mockGrpcClient.Setup(x => x.GetInstanceAuthStringAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceAuthString>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudRedisClient client = new CloudRedisClientImpl(mockGrpcClient.Object, null); InstanceAuthString responseCallSettings = await client.GetInstanceAuthStringAsync(request.InstanceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceAuthString responseCancellationToken = await client.GetInstanceAuthStringAsync(request.InstanceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using ServiceStack.Text.Support; #if WINDOWS_PHONE using System.Linq.Expressions; #endif namespace ServiceStack.Text { public delegate EmptyCtorDelegate EmptyCtorFactoryDelegate(Type type); public delegate object EmptyCtorDelegate(); public static class ReflectionExtensions { private static Dictionary<Type, object> DefaultValueTypes = new Dictionary<Type, object>(); public static object GetDefaultValue(this Type type) { #if NETFX_CORE if (!type.GetTypeInfo().IsValueType) return null; #else if (!type.IsValueType) return null; #endif object defaultValue; if (DefaultValueTypes.TryGetValue(type, out defaultValue)) return defaultValue; defaultValue = Activator.CreateInstance(type); Dictionary<Type, object> snapshot, newCache; do { snapshot = DefaultValueTypes; newCache = new Dictionary<Type, object>(DefaultValueTypes); newCache[type] = defaultValue; } while (!ReferenceEquals( Interlocked.CompareExchange(ref DefaultValueTypes, newCache, snapshot), snapshot)); return defaultValue; } public static bool IsInstanceOf(this Type type, Type thisOrBaseType) { while (type != null) { if (type == thisOrBaseType) return true; #if NETFX_CORE type = type.GetTypeInfo().BaseType; #else type = type.BaseType; #endif } return false; } public static bool IsGenericType(this Type type) { while (type != null) { #if NETFX_CORE if (type.GetTypeInfo().IsGenericType) return true; type = type.GetTypeInfo().BaseType; #else if (type.IsGenericType) return true; type = type.BaseType; #endif } return false; } public static Type GetGenericType(this Type type) { while (type != null) { #if NETFX_CORE if (type.GetTypeInfo().IsGenericType) return type; type = type.GetTypeInfo().BaseType; #else if (type.IsGenericType) return type; type = type.BaseType; #endif } return null; } public static bool IsOrHasGenericInterfaceTypeOf(this Type type, Type genericTypeDefinition) { return (type.GetTypeWithGenericTypeDefinitionOf(genericTypeDefinition) != null) || (type == genericTypeDefinition); } public static Type GetTypeWithGenericTypeDefinitionOf(this Type type, Type genericTypeDefinition) { #if NETFX_CORE foreach (var t in type.GetTypeInfo().ImplementedInterfaces) #else foreach (var t in type.GetInterfaces()) #endif { #if NETFX_CORE if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == genericTypeDefinition) #else if (t.IsGenericType && t.GetGenericTypeDefinition() == genericTypeDefinition) #endif { return t; } } var genericType = type.GetGenericType(); if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition) { return genericType; } return null; } public static Type GetTypeWithInterfaceOf(this Type type, Type interfaceType) { if (type == interfaceType) return interfaceType; #if NETFX_CORE foreach (var t in type.GetTypeInfo().ImplementedInterfaces) #else foreach (var t in type.GetInterfaces()) #endif { if (t == interfaceType) return t; } return null; } public static bool HasInterface(this Type type, Type interfaceType) { #if NETFX_CORE foreach (var t in type.GetTypeInfo().ImplementedInterfaces) #else foreach (var t in type.GetInterfaces()) #endif { if (t == interfaceType) return true; } return false; } public static bool AllHaveInterfacesOfType( this Type assignableFromType, params Type[] types) { foreach (var type in types) { if (assignableFromType.GetTypeWithInterfaceOf(type) == null) return false; } return true; } public static bool IsNumericType(this Type type) { #if NETFX_CORE if (!type.GetTypeInfo().IsValueType) return false; #else if (!type.IsValueType) return false; #endif return type.IsIntegerType() || type.IsRealNumberType(); } public static bool IsIntegerType(this Type type) { #if NETFX_CORE if (!type.GetTypeInfo().IsValueType) return false; #else if (!type.IsValueType) return false; #endif var underlyingType = Nullable.GetUnderlyingType(type) ?? type; return underlyingType == typeof(byte) || underlyingType == typeof(sbyte) || underlyingType == typeof(short) || underlyingType == typeof(ushort) || underlyingType == typeof(int) || underlyingType == typeof(uint) || underlyingType == typeof(long) || underlyingType == typeof(ulong); } public static bool IsRealNumberType(this Type type) { #if NETFX_CORE if (!type.GetTypeInfo().IsValueType) return false; #else if (!type.IsValueType) return false; #endif var underlyingType = Nullable.GetUnderlyingType(type) ?? type; return underlyingType == typeof(float) || underlyingType == typeof(double) || underlyingType == typeof(decimal); } public static Type GetTypeWithGenericInterfaceOf(this Type type, Type genericInterfaceType) { #if NETFX_CORE foreach (var t in type.GetTypeInfo().ImplementedInterfaces) #else foreach (var t in type.GetInterfaces()) #endif { #if NETFX_CORE if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == genericInterfaceType) return t; #else if (t.IsGenericType && t.GetGenericTypeDefinition() == genericInterfaceType) return t; #endif } #if NETFX_CORE if (!type.GetTypeInfo().IsGenericType) return null; #else if (!type.IsGenericType) return null; #endif var genericType = type.GetGenericType(); return genericType.GetGenericTypeDefinition() == genericInterfaceType ? genericType : null; } public static bool HasAnyTypeDefinitionsOf(this Type genericType, params Type[] theseGenericTypes) { #if NETFX_CORE if (!genericType.GetTypeInfo().IsGenericType) return false; #else if (!genericType.IsGenericType) return false; #endif var genericTypeDefinition = genericType.GetGenericTypeDefinition(); foreach (var thisGenericType in theseGenericTypes) { if (genericTypeDefinition == thisGenericType) return true; } return false; } public static Type[] GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments( this Type assignableFromType, Type typeA, Type typeB) { var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeAInterface == null) return null; var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeBInterface == null) return null; #if NETFX_CORE var typeAGenericArgs = typeAInterface.GenericTypeArguments; var typeBGenericArgs = typeBInterface.GenericTypeArguments; #else var typeAGenericArgs = typeAInterface.GetGenericArguments(); var typeBGenericArgs = typeBInterface.GetGenericArguments(); #endif if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null; for (var i = 0; i < typeBGenericArgs.Length; i++) { if (typeAGenericArgs[i] != typeBGenericArgs[i]) { return null; } } return typeAGenericArgs; } public static TypePair GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments( this Type assignableFromType, Type typeA, Type typeB) { var typeAInterface = typeA.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeAInterface == null) return null; var typeBInterface = typeB.GetTypeWithGenericInterfaceOf(assignableFromType); if (typeBInterface == null) return null; #if NETFX_CORE var typeAGenericArgs = typeAInterface.GenericTypeArguments; var typeBGenericArgs = typeBInterface.GenericTypeArguments; #else var typeAGenericArgs = typeAInterface.GetGenericArguments(); var typeBGenericArgs = typeBInterface.GetGenericArguments(); #endif if (typeAGenericArgs.Length != typeBGenericArgs.Length) return null; for (var i = 0; i < typeBGenericArgs.Length; i++) { if (!AreAllStringOrValueTypes(typeAGenericArgs[i], typeBGenericArgs[i])) { return null; } } return new TypePair(typeAGenericArgs, typeBGenericArgs); } public static bool AreAllStringOrValueTypes(params Type[] types) { foreach (var type in types) { #if NETFX_CORE if (!(type == typeof(string) || type.GetTypeInfo().IsValueType)) return false; #else if (!(type == typeof(string) || type.IsValueType)) return false; #endif } return true; } static Dictionary<Type, EmptyCtorDelegate> ConstructorMethods = new Dictionary<Type, EmptyCtorDelegate>(); public static EmptyCtorDelegate GetConstructorMethod(Type type) { EmptyCtorDelegate emptyCtorFn; if (ConstructorMethods.TryGetValue(type, out emptyCtorFn)) return emptyCtorFn; emptyCtorFn = GetConstructorMethodToCache(type); Dictionary<Type, EmptyCtorDelegate> snapshot, newCache; do { snapshot = ConstructorMethods; newCache = new Dictionary<Type, EmptyCtorDelegate>(ConstructorMethods); newCache[type] = emptyCtorFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ConstructorMethods, newCache, snapshot), snapshot)); return emptyCtorFn; } static Dictionary<string, EmptyCtorDelegate> TypeNamesMap = new Dictionary<string, EmptyCtorDelegate>(); public static EmptyCtorDelegate GetConstructorMethod(string typeName) { EmptyCtorDelegate emptyCtorFn; if (TypeNamesMap.TryGetValue(typeName, out emptyCtorFn)) return emptyCtorFn; var type = JsConfig.TypeFinder.Invoke(typeName); if (type == null) return null; emptyCtorFn = GetConstructorMethodToCache(type); Dictionary<string, EmptyCtorDelegate> snapshot, newCache; do { snapshot = TypeNamesMap; newCache = new Dictionary<string, EmptyCtorDelegate>(TypeNamesMap); newCache[typeName] = emptyCtorFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TypeNamesMap, newCache, snapshot), snapshot)); return emptyCtorFn; } public static EmptyCtorDelegate GetConstructorMethodToCache(Type type) { #if NETFX_CORE var emptyCtor = type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Count() == 0); #else var emptyCtor = type.GetConstructor(Type.EmptyTypes); #endif if (emptyCtor != null) { #if MONOTOUCH || c|| XBOX || NETFX_CORE return () => Activator.CreateInstance(type); #elif WINDOWS_PHONE return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile(); #else #if SILVERLIGHT var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes); #else var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(ReflectionExtensions).Module, true); #endif var ilgen = dm.GetILGenerator(); ilgen.Emit(System.Reflection.Emit.OpCodes.Nop); ilgen.Emit(System.Reflection.Emit.OpCodes.Newobj, emptyCtor); ilgen.Emit(System.Reflection.Emit.OpCodes.Ret); return (EmptyCtorDelegate)dm.CreateDelegate(typeof(EmptyCtorDelegate)); #endif } #if (SILVERLIGHT && !WINDOWS_PHONE) || XBOX return () => Activator.CreateInstance(type); #elif WINDOWS_PHONE return Expression.Lambda<EmptyCtorDelegate>(Expression.New(type)).Compile(); #else //Anonymous types don't have empty constructors return () => FormatterServices.GetUninitializedObject(type); #endif } private static class TypeMeta<T> { public static readonly EmptyCtorDelegate EmptyCtorFn; static TypeMeta() { EmptyCtorFn = GetConstructorMethodToCache(typeof(T)); } } public static object CreateInstance<T>() { return TypeMeta<T>.EmptyCtorFn(); } public static object CreateInstance(this Type type) { var ctorFn = GetConstructorMethod(type); return ctorFn(); } public static object CreateInstance(string typeName) { var ctorFn = GetConstructorMethod(typeName); return ctorFn(); } public static PropertyInfo[] GetPublicProperties(this Type type) { #if NETFX_CORE if (type.GetTypeInfo().IsInterface) #else if (type.IsInterface) #endif { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); #if NETFX_CORE foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces) #else foreach (var subInterface in subType.GetInterfaces()) #endif { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } #if NETFX_CORE var typeProperties = subType.GetRuntimeProperties(); #else var typeProperties = subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); #endif var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } #if NETFX_CORE return type.GetRuntimeProperties() .Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties .ToArray(); #else return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance) .Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties .ToArray(); #endif } public static FieldInfo[] GetPublicFields(this Type type) { #if NETFX_CORE if (type.GetTypeInfo().IsInterface) #else if (type.IsInterface) #endif { return new FieldInfo[0]; } #if NETFX_CORE return type.GetRuntimeFields().Where(p => p.IsPublic && !p.IsStatic).ToArray(); #else return type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance) .ToArray(); #endif } const string DataContract = "DataContractAttribute"; const string DataMember = "DataMemberAttribute"; const string IgnoreDataMember = "IgnoreDataMemberAttribute"; public static PropertyInfo[] GetSerializableProperties(this Type type) { var publicProperties = GetPublicProperties(type); #if NETFX_CORE var publicReadableProperties = publicProperties.Where(x => x.GetMethod != null); #else var publicReadableProperties = publicProperties.Where(x => x.GetGetMethod(false) != null); #endif if (type.IsDto()) { return !Env.IsMono ? publicReadableProperties.Where(attr => attr.IsDefined(typeof(DataMemberAttribute), false)).ToArray() : publicReadableProperties.Where(attr => attr.GetCustomAttributes(false).Any(x => x.GetType().Name == DataMember)).ToArray(); } // else return those properties that are not decorated with IgnoreDataMember return publicReadableProperties.Where(prop => !prop.GetCustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray(); } public static FieldInfo[] GetSerializableFields(this Type type) { if (type.IsDto()) { return new FieldInfo[0]; } var publicFields = GetPublicFields(type); // else return those properties that are not decorated with IgnoreDataMember return publicFields.Where(prop => !prop.GetCustomAttributes(false).Any(attr => attr.GetType().Name == IgnoreDataMember)).ToArray(); } public static bool IsDto(this Type type) { #if NETFX_CORE return type.GetTypeInfo().IsDefined(typeof(DataContractAttribute), false); #else return !Env.IsMono ? type.IsDefined(typeof(DataContractAttribute), false) : type.GetCustomAttributes(true).Any(x => x.GetType().Name == DataContract); #endif } public static bool HasAttr<T>(this Type type) where T : Attribute { #if NETFX_CORE return type.GetTypeInfo().GetCustomAttributes(true).Any(x => x.GetType() == typeof(T)); #else return type.GetCustomAttributes(true).Any(x => x.GetType() == typeof(T)); #endif } #if !SILVERLIGHT && !MONOTOUCH static readonly Dictionary<Type, FastMember.TypeAccessor> typeAccessorMap = new Dictionary<Type, FastMember.TypeAccessor>(); #endif public static DataContractAttribute GetDataContract(this Type type) { #if NETFX_CORE var dataContract = type.GetTypeInfo().GetCustomAttributes(typeof(DataContractAttribute), true) .FirstOrDefault() as DataContractAttribute; #else var dataContract = type.GetCustomAttributes(typeof(DataContractAttribute), true) .FirstOrDefault() as DataContractAttribute; #endif #if !SILVERLIGHT && !MONOTOUCH && !XBOX if (dataContract == null && Env.IsMono) return type.GetWeakDataContract(); #endif return dataContract; } public static DataMemberAttribute GetDataMember(this PropertyInfo pi) { var dataMember = pi.GetCustomAttributes(typeof(DataMemberAttribute), false) .FirstOrDefault() as DataMemberAttribute; #if !SILVERLIGHT && !MONOTOUCH && !XBOX if (dataMember == null && Env.IsMono) return pi.GetWeakDataMember(); #endif return dataMember; } #if !SILVERLIGHT && !MONOTOUCH && !XBOX public static DataContractAttribute GetWeakDataContract(this Type type) { var attr = type.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().Name == DataContract); if (attr != null) { var attrType = attr.GetType(); FastMember.TypeAccessor accessor; lock (typeAccessorMap) { if (!typeAccessorMap.TryGetValue(attrType, out accessor)) typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType()); } return new DataContractAttribute { Name = (string)accessor[attr, "Name"], Namespace = (string)accessor[attr, "Namespace"], }; } return null; } public static DataMemberAttribute GetWeakDataMember(this PropertyInfo pi) { var attr = pi.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().Name == DataMember); if (attr != null) { var attrType = attr.GetType(); FastMember.TypeAccessor accessor; lock (typeAccessorMap) { if (!typeAccessorMap.TryGetValue(attrType, out accessor)) typeAccessorMap[attrType] = accessor = FastMember.TypeAccessor.Create(attr.GetType()); } var newAttr = new DataMemberAttribute { Name = (string) accessor[attr, "Name"], EmitDefaultValue = (bool)accessor[attr, "EmitDefaultValue"], IsRequired = (bool)accessor[attr, "IsRequired"], }; var order = (int)accessor[attr, "Order"]; if (order >= 0) newAttr.Order = order; //Throws Exception if set to -1 return newAttr; } return null; } #endif } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type EventExtensionsCollectionRequest. /// </summary> public partial class EventExtensionsCollectionRequest : BaseRequest, IEventExtensionsCollectionRequest { /// <summary> /// Constructs a new EventExtensionsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public EventExtensionsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Extension to the collection via POST. /// </summary> /// <param name="extension">The Extension to add.</param> /// <returns>The created Extension.</returns> public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension) { return this.AddAsync(extension, CancellationToken.None); } /// <summary> /// Adds the specified Extension to the collection via POST. /// </summary> /// <param name="extension">The Extension to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Extension.</returns> public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; extension.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(extension.GetType().FullName)); return this.SendAsync<Extension>(extension, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IEventExtensionsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IEventExtensionsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<EventExtensionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Expand(Expression<Func<Extension, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Select(Expression<Func<Extension, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IEventExtensionsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
//------------------------------------------------------------------------------ // <copyright file="Trace.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ #define TRACE namespace System.Diagnostics { using System; using System.Collections; using System.Security.Permissions; using System.Threading; /// <devdoc> /// <para>Provides a set of properties and methods to trace the execution of your code.</para> /// </devdoc> public sealed class Trace { //// private static CorrelationManager correlationManager = null; // not creatble... // private Trace() { } //// /// <devdoc> //// /// <para>Gets the collection of listeners that is monitoring the trace output.</para> //// /// </devdoc> //// public static TraceListenerCollection Listeners //// { //// [HostProtection( SharedState = true )] //// get //// { //// // Do a full damand //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// //// return TraceInternal.Listeners; //// } //// } //// //// /// <devdoc> //// /// <para> //// /// Gets or sets whether <see cref='System.Diagnostics.Trace.Flush'/> should be called on the <see cref='System.Diagnostics.Trace.Listeners'/> after every write. //// /// </para> //// /// </devdoc> //// public static bool AutoFlush //// { //// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// get //// { //// return TraceInternal.AutoFlush; //// } //// //// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// set //// { //// TraceInternal.AutoFlush = value; //// } //// } //// //// public static bool UseGlobalLock //// { //// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// get //// { //// return TraceInternal.UseGlobalLock; //// } //// //// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// set //// { //// TraceInternal.UseGlobalLock = value; //// } //// } //// //// public static CorrelationManager CorrelationManager //// { //// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// get //// { //// if(correlationManager == null) //// correlationManager = new CorrelationManager(); //// //// return correlationManager; //// } //// } //// //// /// <devdoc> //// /// <para>Gets or sets the indent level.</para> //// /// </devdoc> //// public static int IndentLevel //// { //// get { return TraceInternal.IndentLevel; } //// //// set { TraceInternal.IndentLevel = value; } //// } //// //// //// /// <devdoc> //// /// <para> //// /// Gets or sets the number of spaces in an indent. //// /// </para> //// /// </devdoc> //// public static int IndentSize //// { //// get { return TraceInternal.IndentSize; } //// //// set { TraceInternal.IndentSize = value; } //// } /// <devdoc> /// <para>Clears the output buffer, and causes buffered data to /// be written to the <see cref='System.Diagnostics.Trace.Listeners'/>.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Flush() { //// TraceInternal.Flush(); } /// <devdoc> /// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Trace.Listeners'/> so that they no /// longer receive debugging output.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Close() { //// // Do a full damand //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// //// TraceInternal.Close(); } /// <devdoc> /// <para>Checks for a condition, and outputs the callstack if the /// condition /// is <see langword='false'/>.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition ) { //// TraceInternal.Assert( condition ); } /// <devdoc> /// <para>Checks for a condition, and displays a message if the condition is /// <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition, string message ) { //// TraceInternal.Assert( condition, message ); } /// <devdoc> /// <para>Checks for a condition, and displays both messages if the condition /// is <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition, string message, string detailMessage ) { //// TraceInternal.Assert( condition, message, detailMessage ); } /// <devdoc> /// <para>Emits or displays a message for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Fail( string message ) { //// TraceInternal.Fail( message ); } /// <devdoc> /// <para>Emits or displays both messages for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Fail( string message, string detailMessage ) { //// TraceInternal.Fail( message, detailMessage ); } public static void Refresh() { //// DiagnosticsConfiguration.Refresh(); //// Switch.RefreshAll(); //// TraceSource.RefreshAll(); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceInformation( string message ) { //// TraceInternal.TraceEvent( TraceEventType.Information, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceInformation( string format , params object[] args ) { //// TraceInternal.TraceEvent( TraceEventType.Information, 0, format, args ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceWarning( string message ) { //// TraceInternal.TraceEvent( TraceEventType.Warning, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceWarning( string format , params object[] args ) { //// TraceInternal.TraceEvent( TraceEventType.Warning, 0, format, args ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceError( string message ) { //// TraceInternal.TraceEvent( TraceEventType.Error, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceError( string format , params object[] args ) { //// TraceInternal.TraceEvent( TraceEventType.Error, 0, format, args ); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> /// collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Write( string message ) { //// TraceInternal.Write( message ); } /// <devdoc> /// <para>Writes the name of the <paramref name="value "/> /// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Write( object value ) { //// TraceInternal.Write( value ); } /// <devdoc> /// <para>Writes a category name and message to the trace listeners /// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Write( string message , string category ) { //// TraceInternal.Write( message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the value parameter to the trace listeners /// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Write( object value , string category ) { //// TraceInternal.Write( value, category ); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. /// The default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( string message ) { //// TraceInternal.WriteLine( message ); } /// <devdoc> /// <para>Writes the name of the <paramref name="value "/> parameter followed by a line terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( object value ) { //// TraceInternal.WriteLine( value ); } /// <devdoc> /// <para>Writes a category name and message followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> /// collection. The default line terminator is a carriage return followed by a line /// feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( string message , string category ) { //// TraceInternal.WriteLine( message, category ); } /// <devdoc> /// <para>Writes a <paramref name="category "/>name and the name of the <paramref name="value "/> parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( object value , string category ) { //// TraceInternal.WriteLine( value, category ); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection /// if a condition is <see langword='true'/>.</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , string message ) { //// TraceInternal.WriteIf( condition, message ); } /// <devdoc> /// <para>Writes the name of the <paramref name="value "/> /// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , object value ) { //// TraceInternal.WriteIf( condition, value ); } /// <devdoc> /// <para>Writes a category name and message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> /// collection if a condition is <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , string message , string category ) { //// TraceInternal.WriteIf( condition, message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the <paramref name="value"/> parameter to the trace /// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection /// if a condition is <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , object value , string category ) { //// TraceInternal.WriteIf( condition, value, category ); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the trace listeners in the /// <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , string message ) { //// TraceInternal.WriteLineIf( condition, message ); } /// <devdoc> /// <para>Writes the name of the <paramref name="value"/> parameter followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection /// if a condition is /// <see langword='true'/>. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , object value ) { //// TraceInternal.WriteLineIf( condition, value ); } /// <devdoc> /// <para>Writes a category name and message followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , string message , string category ) { //// TraceInternal.WriteLineIf( condition, message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the <paramref name="value "/> parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection /// if a <paramref name="condition"/> is <see langword='true'/>. The /// default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , object value , string category ) { //// TraceInternal.WriteLineIf( condition, value, category ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Indent() { //// TraceInternal.Indent(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional( "TRACE" )] public static void Unindent() { //// TraceInternal.Unindent(); } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; namespace TMPro { /// <summary> /// Contains the font asset for the specified font weight styles. /// </summary> [Serializable] public struct TMP_FontWeights { public TMP_FontAsset regularTypeface; public TMP_FontAsset italicTypeface; } [Serializable] public class TMP_FontAsset : TMP_Asset { /// <summary> /// Default Font Asset used as last resort when glyphs are missing. /// </summary> public static TMP_FontAsset defaultFontAsset { get { if (s_defaultFontAsset == null) { s_defaultFontAsset = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF"); } return s_defaultFontAsset; } } private static TMP_FontAsset s_defaultFontAsset; public enum FontAssetTypes { None = 0, SDF = 1, Bitmap = 2 }; public FontAssetTypes fontAssetType; /// <summary> /// The general information about the font. /// </summary> public FaceInfo fontInfo { get { return m_fontInfo; } } [SerializeField] private FaceInfo m_fontInfo; [SerializeField] public Texture2D atlas; // Should add a property to make this read-only. // Glyph Info [SerializeField] private List<TMP_Glyph> m_glyphInfoList; public Dictionary<int, TMP_Glyph> characterDictionary { get { if (m_characterDictionary == null) ReadFontDefinition(); return m_characterDictionary; } } private Dictionary<int, TMP_Glyph> m_characterDictionary; /// <summary> /// Dictionary containing the kerning data /// </summary> public Dictionary<int, KerningPair> kerningDictionary { get { return m_kerningDictionary; } } private Dictionary<int, KerningPair> m_kerningDictionary; /// <summary> /// /// </summary> public KerningTable kerningInfo { get { return m_kerningInfo; } } [SerializeField] private KerningTable m_kerningInfo; [SerializeField] #pragma warning disable 0169 // Property is used to create an empty Kerning Pair in the editor. private KerningPair m_kerningPair; // Used for creating a new kerning pair in Editor Panel. /// <summary> /// List containing the Fallback font assets for this font. /// </summary> [SerializeField] public List<TMP_FontAsset> fallbackFontAssets; /// <summary> /// The settings used in the Font Asset Creator when this font asset was created or edited. /// </summary> public FontAssetCreationSettings creationSettings { get { return m_CreationSettings; } set { m_CreationSettings = value; } } [SerializeField] public FontAssetCreationSettings m_CreationSettings; // FONT WEIGHTS [SerializeField] public TMP_FontWeights[] fontWeights = new TMP_FontWeights[10]; private int[] m_characterSet; // Array containing all the characters in this font asset. public float normalStyle = 0; public float normalSpacingOffset = 0; public float boldStyle = 0.75f; public float boldSpacing = 7f; public byte italicStyle = 35; public byte tabSize = 10; private byte m_oldTabSize; void OnEnable() { //Debug.Log("OnEnable has been called on " + this.name); } void OnDisable() { //Debug.Log("TextMeshPro Font Asset [" + this.name + "] has been disabled!"); } #if UNITY_EDITOR /// <summary> /// /// </summary> void OnValidate() { if (m_oldTabSize != tabSize) { m_oldTabSize = tabSize; ReadFontDefinition(); } } #endif /// <summary> /// /// </summary> /// <param name="faceInfo"></param> public void AddFaceInfo(FaceInfo faceInfo) { m_fontInfo = faceInfo; } /// <summary> /// /// </summary> /// <param name="glyphInfo"></param> public void AddGlyphInfo(TMP_Glyph[] glyphInfo) { m_glyphInfoList = new List<TMP_Glyph>(); int characterCount = glyphInfo.Length; m_fontInfo.CharacterCount = characterCount; m_characterSet = new int[characterCount]; for (int i = 0; i < characterCount; i++) { TMP_Glyph g = new TMP_Glyph(); g.id = glyphInfo[i].id; g.x = glyphInfo[i].x; g.y = glyphInfo[i].y; g.width = glyphInfo[i].width; g.height = glyphInfo[i].height; g.xOffset = glyphInfo[i].xOffset; g.yOffset = (glyphInfo[i].yOffset); g.xAdvance = glyphInfo[i].xAdvance; g.scale = 1; m_glyphInfoList.Add(g); // While iterating through list of glyphs, find the Descender & Ascender for this GlyphSet. //m_fontInfo.Ascender = Mathf.Max(m_fontInfo.Ascender, glyphInfo[i].yOffset); //m_fontInfo.Descender = Mathf.Min(m_fontInfo.Descender, glyphInfo[i].yOffset - glyphInfo[i].height); //Debug.Log(m_fontInfo.Ascender + " " + m_fontInfo.Descender); m_characterSet[i] = g.id; // Add Character ID to Array to make it easier to get the kerning pairs. } // Sort List by ID. m_glyphInfoList = m_glyphInfoList.OrderBy(s => s.id).ToList(); } /// <summary> /// /// </summary> /// <param name="kerningTable"></param> public void AddKerningInfo(KerningTable kerningTable) { m_kerningInfo = kerningTable; } /// <summary> /// /// </summary> public void ReadFontDefinition() { //Debug.Log("Reading Font Definition for " + this.name + "."); // Make sure that we have a Font Asset file assigned. if (m_fontInfo == null) { return; } // Check Font Asset type //Debug.Log(name + " " + fontAssetType); // Create new instance of GlyphInfo Dictionary for fast access to glyph info. m_characterDictionary = new Dictionary<int, TMP_Glyph>(); for (int i = 0; i < m_glyphInfoList.Count; i++) { TMP_Glyph glyph = m_glyphInfoList[i]; if (!m_characterDictionary.ContainsKey(glyph.id)) m_characterDictionary.Add(glyph.id, glyph); // Compatibility if (glyph.scale == 0) glyph.scale = 1; } //Debug.Log("PRE: BaseLine:" + m_fontInfo.Baseline + " Ascender:" + m_fontInfo.Ascender + " Descender:" + m_fontInfo.Descender); // + " Centerline:" + m_fontInfo.CenterLine); TMP_Glyph temp_charInfo = new TMP_Glyph(); // Add Character (10) LineFeed, (13) Carriage Return & Space (32) to Dictionary if they don't exists. if (m_characterDictionary.ContainsKey(32)) { m_characterDictionary[32].width = m_characterDictionary[32].xAdvance; // m_fontInfo.Ascender / 5; m_characterDictionary[32].height = m_fontInfo.Ascender - m_fontInfo.Descender; m_characterDictionary[32].yOffset= m_fontInfo.Ascender; m_characterDictionary[32].scale = 1; } else { //Debug.Log("Adding Character 32 (Space) to Dictionary for Font (" + m_fontInfo.Name + ")."); temp_charInfo = new TMP_Glyph(); temp_charInfo.id = 32; temp_charInfo.x = 0; temp_charInfo.y = 0; temp_charInfo.width = m_fontInfo.Ascender / 5; temp_charInfo.height = m_fontInfo.Ascender - m_fontInfo.Descender; temp_charInfo.xOffset = 0; temp_charInfo.yOffset = m_fontInfo.Ascender; temp_charInfo.xAdvance = m_fontInfo.PointSize / 4; temp_charInfo.scale = 1; m_characterDictionary.Add(32, temp_charInfo); } // Add Non-Breaking Space (160) if (!m_characterDictionary.ContainsKey(160)) { temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]); m_characterDictionary.Add(160, temp_charInfo); } // Add Zero Width Space (8203) if (!m_characterDictionary.ContainsKey(8203)) { temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]); temp_charInfo.width = 0; temp_charInfo.xAdvance = 0; m_characterDictionary.Add(8203, temp_charInfo); } //Add Zero Width no-break space (8288) if (!m_characterDictionary.ContainsKey(8288)) { temp_charInfo = TMP_Glyph.Clone(m_characterDictionary[32]); temp_charInfo.width = 0; temp_charInfo.xAdvance = 0; m_characterDictionary.Add(8288, temp_charInfo); } // Add Linefeed (10) if (m_characterDictionary.ContainsKey(10) == false) { //Debug.Log("Adding Character 10 (Linefeed) to Dictionary for Font (" + m_fontInfo.Name + ")."); temp_charInfo = new TMP_Glyph(); temp_charInfo.id = 10; temp_charInfo.x = 0; // m_characterDictionary[32].x; temp_charInfo.y = 0; // m_characterDictionary[32].y; temp_charInfo.width = 10; // m_characterDictionary[32].width; temp_charInfo.height = m_characterDictionary[32].height; temp_charInfo.xOffset = 0; // m_characterDictionary[32].xOffset; temp_charInfo.yOffset = m_characterDictionary[32].yOffset; temp_charInfo.xAdvance = 0; temp_charInfo.scale = 1; m_characterDictionary.Add(10, temp_charInfo); if (!m_characterDictionary.ContainsKey(13)) m_characterDictionary.Add(13, temp_charInfo); } // Add Tab Character to Dictionary. Tab is Tab Size * Space Character Width. if (m_characterDictionary.ContainsKey(9) == false) { //Debug.Log("Adding Character 9 (Tab) to Dictionary for Font (" + m_fontInfo.Name + ")."); temp_charInfo = new TMP_Glyph(); temp_charInfo.id = 9; temp_charInfo.x = m_characterDictionary[32].x; temp_charInfo.y = m_characterDictionary[32].y; temp_charInfo.width = m_characterDictionary[32].width * tabSize + (m_characterDictionary[32].xAdvance - m_characterDictionary[32].width) * (tabSize - 1); temp_charInfo.height = m_characterDictionary[32].height; temp_charInfo.xOffset = m_characterDictionary[32].xOffset; temp_charInfo.yOffset = m_characterDictionary[32].yOffset; temp_charInfo.xAdvance = m_characterDictionary[32].xAdvance * tabSize; temp_charInfo.scale = 1; m_characterDictionary.Add(9, temp_charInfo); } // Centerline is located at the center of character like { or in the middle of the lowercase o. //m_fontInfo.CenterLine = m_characterDictionary[111].yOffset - m_characterDictionary[111].height * 0.5f; // Tab Width is using the same xAdvance as space (32). m_fontInfo.TabWidth = m_characterDictionary[9].xAdvance; // Set Cap Height if (m_fontInfo.CapHeight == 0 && m_characterDictionary.ContainsKey(72)) m_fontInfo.CapHeight = m_characterDictionary[72].yOffset; // Adjust Font Scale for compatibility reasons if (m_fontInfo.Scale == 0) m_fontInfo.Scale = 1.0f; // Set Strikethrough Offset (if needed) if (m_fontInfo.strikethrough == 0) m_fontInfo.strikethrough = m_fontInfo.CapHeight / 2.5f; // Set Padding value for legacy font assets. if (m_fontInfo.Padding == 0) { if (material.HasProperty(ShaderUtilities.ID_GradientScale)) m_fontInfo.Padding = material.GetFloat(ShaderUtilities.ID_GradientScale) - 1; } // Populate Dictionary with Kerning Information m_kerningDictionary = new Dictionary<int, KerningPair>(); List<KerningPair> pairs = m_kerningInfo.kerningPairs; //Debug.Log(m_fontInfo.Name + " has " + pairs.Count + " Kerning Pairs."); for (int i = 0; i < pairs.Count; i++) { KerningPair pair = pairs[i]; // Convert legacy kerning data if (pair.xOffset != 0) pairs[i].ConvertLegacyKerningData(); KerningPairKey uniqueKey = new KerningPairKey(pair.firstGlyph, pair.secondGlyph); if (m_kerningDictionary.ContainsKey((int)uniqueKey.key) == false) { m_kerningDictionary.Add((int)uniqueKey.key, pair); } else { if (!TMP_Settings.warningsDisabled) Debug.LogWarning("Kerning Key for [" + uniqueKey.ascii_Left + "] and [" + uniqueKey.ascii_Right + "] already exists."); } } // Compute Hashcode for the font asset name hashCode = TMP_TextUtilities.GetSimpleHashCode(this.name); // Compute Hashcode for the material name materialHashCode = TMP_TextUtilities.GetSimpleHashCode(material.name); // Unload font atlas texture //ShaderUtilities.GetShaderPropertyIDs(); //Resources.UnloadAsset(material.GetTexture(ShaderUtilities.ID_MainTex)); // Initialize Font Weights if needed //InitializeFontWeights(); } /// <summary> /// Function to sort the list of glyphs. /// </summary> public void SortGlyphs() { if (m_glyphInfoList == null || m_glyphInfoList.Count == 0) return; m_glyphInfoList = m_glyphInfoList.OrderBy(item => item.id).ToList(); } /// <summary> /// Function to check if a certain character exists in the font asset. /// </summary> /// <param name="character"></param> /// <returns></returns> public bool HasCharacter(int character) { if (m_characterDictionary == null) return false; if (m_characterDictionary.ContainsKey(character)) return true; return false; } /// <summary> /// Function to check if a certain character exists in the font asset. /// </summary> /// <param name="character"></param> /// <returns></returns> public bool HasCharacter(char character) { if (m_characterDictionary == null) return false; if (m_characterDictionary.ContainsKey(character)) return true; return false; } /// <summary> /// Function to check if a character is contained in the font asset with the option to also check through fallback font assets. /// </summary> /// <param name="character"></param> /// <param name="searchFallbacks"></param> /// <returns></returns> public bool HasCharacter(char character, bool searchFallbacks) { // Read font asset definition if it hasn't already been done. if (m_characterDictionary == null) { ReadFontDefinition(); if (m_characterDictionary == null) return false; } // Check font asset if (m_characterDictionary.ContainsKey(character)) return true; if (searchFallbacks) { // Check font asset fallbacks if (fallbackFontAssets != null && fallbackFontAssets.Count > 0) { for (int i = 0; i < fallbackFontAssets.Count && fallbackFontAssets[i] != null; i++) { if (fallbackFontAssets[i].HasCharacter_Internal(character, searchFallbacks)) return true; } } // Check general fallback font assets. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0) { for (int i = 0; i < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[i] != null; i++) { if (TMP_Settings.fallbackFontAssets[i].characterDictionary == null) TMP_Settings.fallbackFontAssets[i].ReadFontDefinition(); if (TMP_Settings.fallbackFontAssets[i].characterDictionary != null && TMP_Settings.fallbackFontAssets[i].HasCharacter_Internal(character, searchFallbacks)) return true; } } // Check TMP Settings Default Font Asset if (TMP_Settings.defaultFontAsset != null) { if (TMP_Settings.defaultFontAsset.characterDictionary == null) TMP_Settings.defaultFontAsset.ReadFontDefinition(); if (TMP_Settings.defaultFontAsset.characterDictionary != null && TMP_Settings.defaultFontAsset.HasCharacter_Internal(character, searchFallbacks)) return true; } } return false; } /// <summary> /// Function to check if a character is contained in a font asset with the option to also check through fallback font assets. /// This private implementation does not search the fallback font asset in the TMP Settings file. /// </summary> /// <param name="character"></param> /// <param name="searchFallbacks"></param> /// <returns></returns> bool HasCharacter_Internal(char character, bool searchFallbacks) { // Read font asset definition if it hasn't already been done. if (m_characterDictionary == null) { ReadFontDefinition(); if (m_characterDictionary == null) return false; } // Check font asset if (m_characterDictionary.ContainsKey(character)) return true; if (searchFallbacks) { // Check Font Asset Fallback fonts. if (fallbackFontAssets != null && fallbackFontAssets.Count > 0) { for (int i = 0; i < fallbackFontAssets.Count && fallbackFontAssets[i] != null; i++) { if (fallbackFontAssets[i].HasCharacter_Internal(character, searchFallbacks)) return true; } } } return false; } /// <summary> /// Function to check if certain characters exists in the font asset. Function returns a list of missing characters. /// </summary> /// <param name="character"></param> /// <returns></returns> public bool HasCharacters(string text, out List<char> missingCharacters) { if (m_characterDictionary == null) { missingCharacters = null; return false; } missingCharacters = new List<char>(); for (int i = 0; i < text.Length; i++) { if (!m_characterDictionary.ContainsKey(text[i])) missingCharacters.Add(text[i]); } if (missingCharacters.Count == 0) return true; return false; } /// <summary> /// Function to check if certain characters exists in the font asset. Function returns false if any characters are missing. /// </summary> /// <param name="text">String containing the characters to check</param> /// <returns></returns> public bool HasCharacters(string text) { if (m_characterDictionary == null) return false; for (int i = 0; i < text.Length; i++) { if (!m_characterDictionary.ContainsKey(text[i])) return false; } return true; } /// <summary> /// Function to extract all the characters from a font asset. /// </summary> /// <param name="fontAsset"></param> /// <returns></returns> public static string GetCharacters(TMP_FontAsset fontAsset) { string characters = string.Empty; for (int i = 0; i < fontAsset.m_glyphInfoList.Count; i++) { characters += (char)fontAsset.m_glyphInfoList[i].id; } return characters; } /// <summary> /// Function which returns an array that contains all the characters from a font asset. /// </summary> /// <param name="fontAsset"></param> /// <returns></returns> public static int[] GetCharactersArray(TMP_FontAsset fontAsset) { int[] characters = new int[fontAsset.m_glyphInfoList.Count]; for (int i = 0; i < fontAsset.m_glyphInfoList.Count; i++) { characters[i] = fontAsset.m_glyphInfoList[i].id; } return characters; } } }
/* Created by Team "GT Dead Week" Chenglong Jiang Arnaud Golinvaux Michael Landes Josephine Simon Chuan Yao */ using UnityEngine; using System.Collections; public delegate void JumpDelegate (); public class ThirdPersonController : MonoBehaviour { public Rigidbody target; // The object we're steering public float speed = 4f, walkSpeedDownscale = 2.0f, turnSpeed = 2.0f, mouseTurnSpeed = 0.3f, jumpSpeed = 1.0f; // Tweak to ajust character responsiveness public LayerMask groundLayers = -1; // Which layers should be walkable? // NOTICE: Make sure that the target collider is not in any of these layers! public float groundedCheckOffset = 0.7f; // Tweak so check starts from just within target footing public bool showGizmos = true, // Turn this off to reduce gizmo clutter if needed requireLock = true, // Turn this off if the camera should be controllable even without cursor lock controlLock = false; // Turn this on if you want mouse lock controlled by this script public JumpDelegate onJump = null; // Assign to this delegate to respond to the controller jumping private const float inputThreshold = 0.01f, groundDrag = 5.0f, directionalJumpFactor = 0.7f; // Tweak these to adjust behaviour relative to speed private const float groundedDistance = 0.75f; // Tweak if character lands too soon or gets stuck "in air" often private bool grounded; public bool canRun; public bool isActing; // Switch to true when the player is taking actions including running public bool hasJump; // Switch to true after each jump public bool Grounded // Make our grounded status available for other components { get { return grounded; } } void Reset () // Run setup on component attach, so it is visually more clear which references are used { Setup (); } void Setup () // If target is not set, try using fallbacks { if (target == null) { target = GetComponent<Rigidbody> (); } } void Start () // Verify setup, configure rigidbody { Setup (); // Retry setup if references were cleared post-add if (target == null) { Debug.LogError ("No target assigned. Please correct and restart."); enabled = false; return; } target.freezeRotation = true; // We will be controlling the rotation of the target, so we tell the physics system to leave it be canRun = true; isActing = false; } void Update () // Handle rotation here to ensure smooth application. { float rotationAmount; if (Input.GetMouseButton (1) && (!requireLock || controlLock || Screen.lockCursor)) // If the right mouse button is held, rotation is locked to the mouse { if (controlLock) { Screen.lockCursor = true; } rotationAmount = Input.GetAxis ("Mouse X") * mouseTurnSpeed * Time.deltaTime; } else { if (controlLock) { Screen.lockCursor = false; } rotationAmount = Input.GetAxis ("Horizontal") * turnSpeed * Time.deltaTime; } target.transform.RotateAround (target.transform.up, rotationAmount); if (Input.GetButtonDown ("ToggleWalk")) { canRun = !canRun; } } float SidestepAxisInput // If the right mouse button is held, the horizontal axis also turns into sidestep handling { get { if (Input.GetMouseButton (1)) { float sidestep = Input.GetAxis ("Sidestep"), horizontal = Input.GetAxis ("Horizontal"); return Mathf.Abs (sidestep) > Mathf.Abs (horizontal) ? sidestep : horizontal; } else { return Input.GetAxis ("Sidestep"); } } } void FixedUpdate () // Handle movement here since physics will only be calculated in fixed frames anyway { grounded = Physics.Raycast ( target.transform.position + target.transform.up * groundedCheckOffset, target.transform.up * -1, groundedDistance, groundLayers ); // Shoot a ray downward to see if we're touching the ground //Debug.Log ((target.transform.position + target.transform.up * -groundedCheckOffset).ToString () + " " + groundedDistance.ToString()); if (grounded) { target.drag = groundDrag; // Apply drag when we're grounded if (Input.GetButton ("Jump")) // Handle jumping { target.AddForce ( jumpSpeed * target.transform.up + target.velocity.normalized * directionalJumpFactor, ForceMode.Impulse ); // When jumping, we set the velocity upward with our jump speed // plus some application of directional movement if (onJump != null) { onJump (); } //isActing = true; hasJump = true; } else // Only allow movement controls if we did not just jump { Vector3 movement = Input.GetAxis ("Vertical") * target.transform.forward + SidestepAxisInput * target.transform.right; float appliedSpeed = speed / walkSpeedDownscale; if (canRun && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { //Debug.Log("Running!"); appliedSpeed *= walkSpeedDownscale; isActing = true; } else { //Debug.Log("Walking!"); isActing = false; } if (Input.GetAxis ("Vertical") < 0.0f) // Scale down applied speed if walking backwards { appliedSpeed /= walkSpeedDownscale; } if (movement.magnitude > inputThreshold) // Only apply movement if we have sufficient input { target.AddForce (movement.normalized * appliedSpeed, ForceMode.Impulse); } else // If we are grounded and don't have significant input, just stop horizontal movement { target.velocity = new Vector3 (0.0f, target.velocity.y, 0.0f); return; } } } else { target.drag = 0.0f; // If we're airborne, we should have no drag } } void OnDrawGizmos () // Use gizmos to gain information about the state of your setup { if (!showGizmos || target == null) { return; } Gizmos.color = grounded ? Color.blue : Color.red; Gizmos.DrawLine (target.transform.position + target.transform.up * -groundedCheckOffset, target.transform.position + target.transform.up * -(groundedCheckOffset + groundedDistance)); } }
/* * Copyright (c) 2006-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.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. */ using System; using System.Collections.Generic; using OpenMetaverse.StructuredData; namespace OpenMetaverse { public partial class Primitive : IEquatable<Primitive> { // Used for packing and unpacking parameters protected const float CUT_QUANTA = 0.00002f; protected const float SCALE_QUANTA = 0.01f; protected const float SHEAR_QUANTA = 0.01f; protected const float TAPER_QUANTA = 0.01f; protected const float REV_QUANTA = 0.015f; protected const float HOLLOW_QUANTA = 0.00002f; #region Subclasses /// <summary> /// Parameters used to construct a visual representation of a primitive /// </summary> public struct ConstructionData { private const byte PROFILE_MASK = 0x0F; private const byte HOLE_MASK = 0xF0; /// <summary></summary> public byte profileCurve; /// <summary></summary> public PathCurve PathCurve; /// <summary></summary> public float PathEnd; /// <summary></summary> public float PathRadiusOffset; /// <summary></summary> public float PathSkew; /// <summary></summary> public float PathScaleX; /// <summary></summary> public float PathScaleY; /// <summary></summary> public float PathShearX; /// <summary></summary> public float PathShearY; /// <summary></summary> public float PathTaperX; /// <summary></summary> public float PathTaperY; /// <summary></summary> public float PathBegin; /// <summary></summary> public float PathTwist; /// <summary></summary> public float PathTwistBegin; /// <summary></summary> public float PathRevolutions; /// <summary></summary> public float ProfileBegin; /// <summary></summary> public float ProfileEnd; /// <summary></summary> public float ProfileHollow; /// <summary></summary> public Material Material; /// <summary></summary> public byte State; /// <summary></summary> public PCode PCode; #region Properties /// <summary>Attachment point to an avatar</summary> public AttachmentPoint AttachmentPoint { get { return (AttachmentPoint)Utils.SwapWords(State); } set { State = (byte)Utils.SwapWords((byte)value); } } /// <summary></summary> public ProfileCurve ProfileCurve { get { return (ProfileCurve)(profileCurve & PROFILE_MASK); } set { profileCurve &= HOLE_MASK; profileCurve |= (byte)value; } } /// <summary></summary> public HoleType ProfileHole { get { return (HoleType)(profileCurve & HOLE_MASK); } set { profileCurve &= PROFILE_MASK; profileCurve |= (byte)value; } } /// <summary></summary> public Vector2 PathBeginScale { get { Vector2 begin = new Vector2(1f, 1f); if (PathScaleX > 1f) begin.X = 2f - PathScaleX; if (PathScaleY > 1f) begin.Y = 2f - PathScaleY; return begin; } } /// <summary></summary> public Vector2 PathEndScale { get { Vector2 end = new Vector2(1f, 1f); if (PathScaleX < 1f) end.X = PathScaleX; if (PathScaleY < 1f) end.Y = PathScaleY; return end; } } #endregion Properties } /// <summary> /// Information on the flexible properties of a primitive /// </summary> public class FlexibleData { /// <summary></summary> public int Softness; /// <summary></summary> public float Gravity; /// <summary></summary> public float Drag; /// <summary></summary> public float Wind; /// <summary></summary> public float Tension; /// <summary></summary> public Vector3 Force; /// <summary> /// Default constructor /// </summary> public FlexibleData() { } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="pos"></param> public FlexibleData(byte[] data, int pos) { if (data.Length >= 5) { Softness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7); Tension = (float)(data[pos++] & 0x7F) / 10.0f; Drag = (float)(data[pos++] & 0x7F) / 10.0f; Gravity = (float)(data[pos++] / 10.0f) - 10.0f; Wind = (float)data[pos++] / 10.0f; Force = new Vector3(data, pos); } else { Softness = 0; Tension = 0.0f; Drag = 0.0f; Gravity = 0.0f; Wind = 0.0f; Force = Vector3.Zero; } } /// <summary> /// /// </summary> /// <returns></returns> public byte[] GetBytes() { byte[] data = new byte[16]; int i = 0; // Softness is packed in the upper bits of tension and drag data[i] = (byte)((Softness & 2) << 6); data[i + 1] = (byte)((Softness & 1) << 7); data[i++] |= (byte)((byte)(Tension * 10.01f) & 0x7F); data[i++] |= (byte)((byte)(Drag * 10.01f) & 0x7F); data[i++] = (byte)((Gravity + 10.0f) * 10.01f); data[i++] = (byte)(Wind * 10.01f); Force.GetBytes().CopyTo(data, i); return data; } /// <summary> /// /// </summary> /// <returns></returns> public OSD GetOSD() { OSDMap map = new OSDMap(); map["simulate_lod"] = OSD.FromInteger(Softness); map["gravity"] = OSD.FromReal(Gravity); map["air_friction"] = OSD.FromReal(Drag); map["wind_sensitivity"] = OSD.FromReal(Wind); map["tension"] = OSD.FromReal(Tension); map["user_force"] = OSD.FromVector3(Force); return map; } public static FlexibleData FromOSD(OSD osd) { FlexibleData flex = new FlexibleData(); if (osd.Type == OSDType.Map) { OSDMap map = (OSDMap)osd; flex.Softness = map["simulate_lod"].AsInteger(); flex.Gravity = (float)map["gravity"].AsReal(); flex.Drag = (float)map["air_friction"].AsReal(); flex.Wind = (float)map["wind_sensitivity"].AsReal(); flex.Tension = (float)map["tension"].AsReal(); flex.Force = ((OSDArray)map["user_force"]).AsVector3(); } return flex; } public override int GetHashCode() { return Softness.GetHashCode() ^ Gravity.GetHashCode() ^ Drag.GetHashCode() ^ Wind.GetHashCode() ^ Tension.GetHashCode() ^ Force.GetHashCode(); } } /// <summary> /// Information on the light properties of a primitive /// </summary> public class LightData { /// <summary></summary> public Color4 Color; /// <summary></summary> public float Intensity; /// <summary></summary> public float Radius; /// <summary></summary> public float Cutoff; /// <summary></summary> public float Falloff; /// <summary> /// Default constructor /// </summary> public LightData() { } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="pos"></param> public LightData(byte[] data, int pos) { if (data.Length - pos >= 16) { Color = new Color4(data, pos, false); Radius = Utils.BytesToFloat(data, pos + 4); Cutoff = Utils.BytesToFloat(data, pos + 8); Falloff = Utils.BytesToFloat(data, pos + 12); // Alpha in color is actually intensity Intensity = Color.A; Color.A = 1f; } else { Color = Color4.Black; Radius = 0f; Cutoff = 0f; Falloff = 0f; Intensity = 0f; } } /// <summary> /// /// </summary> /// <returns></returns> public byte[] GetBytes() { byte[] data = new byte[16]; // Alpha channel in color is intensity Color4 tmpColor = Color; tmpColor.A = Intensity; tmpColor.GetBytes().CopyTo(data, 0); Utils.FloatToBytes(Radius).CopyTo(data, 4); Utils.FloatToBytes(Cutoff).CopyTo(data, 8); Utils.FloatToBytes(Falloff).CopyTo(data, 12); return data; } public OSD GetOSD() { OSDMap map = new OSDMap(); map["color"] = OSD.FromColor4(Color); map["intensity"] = OSD.FromReal(Intensity); map["radius"] = OSD.FromReal(Radius); map["cutoff"] = OSD.FromReal(Cutoff); map["falloff"] = OSD.FromReal(Falloff); return map; } public static LightData FromOSD(OSD osd) { LightData light = new LightData(); if (osd.Type == OSDType.Map) { OSDMap map = (OSDMap)osd; light.Color = ((OSDArray)map["color"]).AsColor4(); light.Intensity = (float)map["intensity"].AsReal(); light.Radius = (float)map["radius"].AsReal(); light.Cutoff = (float)map["cutoff"].AsReal(); light.Falloff = (float)map["falloff"].AsReal(); } return light; } public override int GetHashCode() { return Color.GetHashCode() ^ Intensity.GetHashCode() ^ Radius.GetHashCode() ^ Cutoff.GetHashCode() ^ Falloff.GetHashCode(); } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return String.Format("Color: {0} Intensity: {1} Radius: {2} Cutoff: {3} Falloff: {4}", Color, Intensity, Radius, Cutoff, Falloff); } } /// <summary> /// Information on the sculpt properties of a sculpted primitive /// </summary> public class SculptData { public UUID SculptTexture; private byte type; public SculptType Type { get { return (SculptType)(type & 7); } set { type = (byte)value; } } /// <summary> /// Render inside out (inverts the normals). /// </summary> public bool Invert { get { return ((type & (byte)SculptType.Invert) != 0); } } /// <summary> /// Render an X axis mirror of the sculpty. /// </summary> public bool Mirror { get { return ((type & (byte)SculptType.Mirror) != 0); } } /// <summary> /// Default constructor /// </summary> public SculptData() { } /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="pos"></param> public SculptData(byte[] data, int pos) { if (data.Length >= 17) { SculptTexture = new UUID(data, pos); type = data[pos + 16]; } else { SculptTexture = UUID.Zero; type = (byte)SculptType.None; } } public byte[] GetBytes() { byte[] data = new byte[17]; SculptTexture.GetBytes().CopyTo(data, 0); data[16] = (byte)Type; return data; } public OSD GetOSD() { OSDMap map = new OSDMap(); map["texture"] = OSD.FromUUID(SculptTexture); map["type"] = OSD.FromInteger(type); return map; } public static SculptData FromOSD(OSD osd) { SculptData sculpt = new SculptData(); if (osd.Type == OSDType.Map) { OSDMap map = (OSDMap)osd; sculpt.SculptTexture = map["texture"].AsUUID(); sculpt.type = (byte)map["type"].AsInteger(); } return sculpt; } public override int GetHashCode() { return SculptTexture.GetHashCode() ^ type.GetHashCode(); } } /// <summary> /// Extended properties to describe an object /// </summary> public class ObjectProperties { /// <summary></summary> public UUID ObjectID; /// <summary></summary> public UUID CreatorID; /// <summary></summary> public UUID OwnerID; /// <summary></summary> public UUID GroupID; /// <summary></summary> public DateTime CreationDate; /// <summary></summary> public Permissions Permissions; /// <summary></summary> public int OwnershipCost; /// <summary></summary> public SaleType SaleType; /// <summary></summary> public int SalePrice; /// <summary></summary> public byte AggregatePerms; /// <summary></summary> public byte AggregatePermTextures; /// <summary></summary> public byte AggregatePermTexturesOwner; /// <summary></summary> public ObjectCategory Category; /// <summary></summary> public short InventorySerial; /// <summary></summary> public UUID ItemID; /// <summary></summary> public UUID FolderID; /// <summary></summary> public UUID FromTaskID; /// <summary></summary> public UUID LastOwnerID; /// <summary></summary> public string Name; /// <summary></summary> public string Description; /// <summary></summary> public string TouchName; /// <summary></summary> public string SitName; /// <summary></summary> public UUID[] TextureIDs; /// <summary> /// Default constructor /// </summary> public ObjectProperties() { Name = String.Empty; Description = String.Empty; TouchName = String.Empty; SitName = String.Empty; } /// <summary> /// Set the properties that are set in an ObjectPropertiesFamily packet /// </summary> /// <param name="props"><seealso cref="ObjectProperties"/> that has /// been partially filled by an ObjectPropertiesFamily packet</param> public void SetFamilyProperties(ObjectProperties props) { ObjectID = props.ObjectID; OwnerID = props.OwnerID; GroupID = props.GroupID; Permissions = props.Permissions; OwnershipCost = props.OwnershipCost; SaleType = props.SaleType; SalePrice = props.SalePrice; Category = props.Category; LastOwnerID = props.LastOwnerID; Name = props.Name; Description = props.Description; } public byte[] GetTextureIDBytes() { if (TextureIDs == null || TextureIDs.Length == 0) return Utils.EmptyBytes; byte[] bytes = new byte[16 * TextureIDs.Length]; for (int i = 0; i < TextureIDs.Length; i++) TextureIDs[i].ToBytes(bytes, 16 * i); return bytes; } } #endregion Subclasses #region Public Members /// <summary></summary> public UUID ID; /// <summary></summary> public UUID GroupID; /// <summary></summary> public uint LocalID; /// <summary></summary> public uint ParentID; /// <summary></summary> public ulong RegionHandle; /// <summary></summary> public PrimFlags Flags; /// <summary>Foliage type for this primitive. Only applicable if this /// primitive is foliage</summary> public Tree TreeSpecies; /// <summary>Unknown</summary> public byte[] ScratchPad; /// <summary></summary> public Vector3 Position; /// <summary></summary> public Vector3 Scale; /// <summary></summary> public Quaternion Rotation = Quaternion.Identity; /// <summary></summary> public Vector3 Velocity; /// <summary></summary> public Vector3 AngularVelocity; /// <summary></summary> public Vector3 Acceleration; /// <summary></summary> public Vector4 CollisionPlane; /// <summary></summary> public FlexibleData Flexible; /// <summary></summary> public LightData Light; /// <summary></summary> public SculptData Sculpt; /// <summary></summary> public ClickAction ClickAction; /// <summary></summary> public UUID Sound; /// <summary>Identifies the owner if audio or a particle system is /// active</summary> public UUID OwnerID; /// <summary></summary> public SoundFlags SoundFlags; /// <summary></summary> public float SoundGain; /// <summary></summary> public float SoundRadius; /// <summary></summary> public string Text; /// <summary></summary> public Color4 TextColor; /// <summary></summary> public string MediaURL; /// <summary></summary> public JointType Joint; /// <summary></summary> public Vector3 JointPivot; /// <summary></summary> public Vector3 JointAxisOrAnchor; /// <summary></summary> public NameValue[] NameValues; /// <summary></summary> public ConstructionData PrimData; /// <summary></summary> public ObjectProperties Properties; #endregion Public Members #region Properties /// <summary>Uses basic heuristics to estimate the primitive shape</summary> public PrimType Type { get { if (Sculpt != null && Sculpt.Type != SculptType.None) return PrimType.Sculpt; bool linearPath = (PrimData.PathCurve == PathCurve.Line || PrimData.PathCurve == PathCurve.Flexible); float scaleY = PrimData.PathScaleY; if (linearPath) { switch (PrimData.ProfileCurve) { case ProfileCurve.Circle: return PrimType.Cylinder; case ProfileCurve.Square: return PrimType.Box; case ProfileCurve.IsoTriangle: case ProfileCurve.EqualTriangle: case ProfileCurve.RightTriangle: return PrimType.Prism; case ProfileCurve.HalfCircle: default: return PrimType.Unknown; } } else { switch (PrimData.PathCurve) { case PathCurve.Flexible: return PrimType.Unknown; case PathCurve.Circle: switch (PrimData.ProfileCurve) { case ProfileCurve.Circle: if (scaleY > 0.75f) return PrimType.Sphere; else return PrimType.Torus; case ProfileCurve.HalfCircle: return PrimType.Sphere; case ProfileCurve.EqualTriangle: return PrimType.Ring; case ProfileCurve.Square: if (scaleY <= 0.75f) return PrimType.Tube; else return PrimType.Unknown; default: return PrimType.Unknown; } case PathCurve.Circle2: if (PrimData.ProfileCurve == ProfileCurve.Circle) return PrimType.Sphere; else return PrimType.Unknown; default: return PrimType.Unknown; } } } } #endregion Properties #region Constructors /// <summary> /// Default constructor /// </summary> public Primitive() { // Default a few null property values to String.Empty Text = String.Empty; MediaURL = String.Empty; } public Primitive(Primitive prim) { ID = prim.ID; GroupID = prim.GroupID; LocalID = prim.LocalID; ParentID = prim.ParentID; RegionHandle = prim.RegionHandle; Flags = prim.Flags; TreeSpecies = prim.TreeSpecies; if (prim.ScratchPad != null) { ScratchPad = new byte[prim.ScratchPad.Length]; Buffer.BlockCopy(prim.ScratchPad, 0, ScratchPad, 0, ScratchPad.Length); } else ScratchPad = Utils.EmptyBytes; Position = prim.Position; Scale = prim.Scale; Rotation = prim.Rotation; Velocity = prim.Velocity; AngularVelocity = prim.AngularVelocity; Acceleration = prim.Acceleration; CollisionPlane = prim.CollisionPlane; Flexible = prim.Flexible; Light = prim.Light; Sculpt = prim.Sculpt; ClickAction = prim.ClickAction; Sound = prim.Sound; OwnerID = prim.OwnerID; SoundFlags = prim.SoundFlags; SoundGain = prim.SoundGain; SoundRadius = prim.SoundRadius; Text = prim.Text; TextColor = prim.TextColor; MediaURL = prim.MediaURL; Joint = prim.Joint; JointPivot = prim.JointPivot; JointAxisOrAnchor = prim.JointAxisOrAnchor; if (prim.NameValues != null) { if (NameValues == null || NameValues.Length != prim.NameValues.Length) NameValues = new NameValue[prim.NameValues.Length]; Array.Copy(prim.NameValues, NameValues, prim.NameValues.Length); } else NameValues = null; PrimData = prim.PrimData; Properties = prim.Properties; // FIXME: Get a real copy constructor for TextureEntry instead of serializing to bytes and back if (prim.Textures != null) { byte[] textureBytes = prim.Textures.GetBytes(); Textures = new TextureEntry(textureBytes, 0, textureBytes.Length); } else { Textures = null; } TextureAnim = prim.TextureAnim; ParticleSys = prim.ParticleSys; } #endregion Constructors #region Public Methods public virtual OSD GetOSD() { OSDMap path = new OSDMap(14); path["begin"] = OSD.FromReal(PrimData.PathBegin); path["curve"] = OSD.FromInteger((int)PrimData.PathCurve); path["end"] = OSD.FromReal(PrimData.PathEnd); path["radius_offset"] = OSD.FromReal(PrimData.PathRadiusOffset); path["revolutions"] = OSD.FromReal(PrimData.PathRevolutions); path["scale_x"] = OSD.FromReal(PrimData.PathScaleX); path["scale_y"] = OSD.FromReal(PrimData.PathScaleY); path["shear_x"] = OSD.FromReal(PrimData.PathShearX); path["shear_y"] = OSD.FromReal(PrimData.PathShearY); path["skew"] = OSD.FromReal(PrimData.PathSkew); path["taper_x"] = OSD.FromReal(PrimData.PathTaperX); path["taper_y"] = OSD.FromReal(PrimData.PathTaperY); path["twist"] = OSD.FromReal(PrimData.PathTwist); path["twist_begin"] = OSD.FromReal(PrimData.PathTwistBegin); OSDMap profile = new OSDMap(4); profile["begin"] = OSD.FromReal(PrimData.ProfileBegin); profile["curve"] = OSD.FromInteger((int)PrimData.ProfileCurve); profile["hole"] = OSD.FromInteger((int)PrimData.ProfileHole); profile["end"] = OSD.FromReal(PrimData.ProfileEnd); profile["hollow"] = OSD.FromReal(PrimData.ProfileHollow); OSDMap volume = new OSDMap(2); volume["path"] = path; volume["profile"] = profile; OSDMap prim = new OSDMap(9); if (Properties != null) { prim["name"] = OSD.FromString(Properties.Name); prim["description"] = OSD.FromString(Properties.Description); } else { prim["name"] = OSD.FromString("Object"); prim["description"] = OSD.FromString(String.Empty); } prim["phantom"] = OSD.FromBoolean(((Flags & PrimFlags.Phantom) != 0)); prim["physical"] = OSD.FromBoolean(((Flags & PrimFlags.Physics) != 0)); prim["position"] = OSD.FromVector3(Position); prim["rotation"] = OSD.FromQuaternion(Rotation); prim["scale"] = OSD.FromVector3(Scale); prim["material"] = OSD.FromInteger((int)PrimData.Material); prim["shadows"] = OSD.FromBoolean(((Flags & PrimFlags.CastShadows) != 0)); prim["parentid"] = OSD.FromInteger(ParentID); prim["volume"] = volume; if (Textures != null) prim["textures"] = Textures.GetOSD(); if (Light != null) prim["light"] = Light.GetOSD(); if (Flexible != null) prim["flex"] = Flexible.GetOSD(); if (Sculpt != null) prim["sculpt"] = Sculpt.GetOSD(); return prim; } public static Primitive FromOSD(OSD osd) { Primitive prim = new Primitive(); Primitive.ConstructionData data; OSDMap map = (OSDMap)osd; OSDMap volume = (OSDMap)map["volume"]; OSDMap path = (OSDMap)volume["path"]; OSDMap profile = (OSDMap)volume["profile"]; #region Path/Profile data.profileCurve = (byte)0; data.State = 0; data.Material = (Material)map["material"].AsInteger(); data.PCode = PCode.Prim; // TODO: Put this in SD data.PathBegin = (float)path["begin"].AsReal(); data.PathCurve = (PathCurve)path["curve"].AsInteger(); data.PathEnd = (float)path["end"].AsReal(); data.PathRadiusOffset = (float)path["radius_offset"].AsReal(); data.PathRevolutions = (float)path["revolutions"].AsReal(); data.PathScaleX = (float)path["scale_x"].AsReal(); data.PathScaleY = (float)path["scale_y"].AsReal(); data.PathShearX = (float)path["shear_x"].AsReal(); data.PathShearY = (float)path["shear_y"].AsReal(); data.PathSkew = (float)path["skew"].AsReal(); data.PathTaperX = (float)path["taper_x"].AsReal(); data.PathTaperY = (float)path["taper_y"].AsReal(); data.PathTwist = (float)path["twist"].AsReal(); data.PathTwistBegin = (float)path["twist_begin"].AsReal(); data.ProfileBegin = (float)profile["begin"].AsReal(); data.ProfileEnd = (float)profile["end"].AsReal(); data.ProfileHollow = (float)profile["hollow"].AsReal(); data.ProfileCurve = (ProfileCurve)profile["curve"].AsInteger(); data.ProfileHole = (HoleType)profile["hole"].AsInteger(); #endregion Path/Profile prim.PrimData = data; if (map["phantom"].AsBoolean()) prim.Flags |= PrimFlags.Phantom; if (map["physical"].AsBoolean()) prim.Flags |= PrimFlags.Physics; if (map["shadows"].AsBoolean()) prim.Flags |= PrimFlags.CastShadows; prim.ParentID = (uint)map["parentid"].AsInteger(); prim.Position = ((OSDArray)map["position"]).AsVector3(); prim.Rotation = ((OSDArray)map["rotation"]).AsQuaternion(); prim.Scale = ((OSDArray)map["scale"]).AsVector3(); prim.Flexible = FlexibleData.FromOSD(map["flex"]); prim.Light = LightData.FromOSD(map["light"]); prim.Sculpt = SculptData.FromOSD(map["sculpt"]); prim.Textures = TextureEntry.FromOSD(map["textures"]); prim.Properties = new ObjectProperties(); if (!string.IsNullOrEmpty(map["name"].AsString())) { prim.Properties.Name = map["name"].AsString(); } if (!string.IsNullOrEmpty(map["description"].AsString())) { prim.Properties.Description = map["description"].AsString(); } return prim; } public int SetExtraParamsFromBytes(byte[] data, int pos) { int i = pos; int totalLength = 1; if (data.Length == 0 || pos >= data.Length) return 0; byte extraParamCount = data[i++]; for (int k = 0; k < extraParamCount; k++) { ExtraParamType type = (ExtraParamType)Utils.BytesToUInt16(data, i); i += 2; uint paramLength = Utils.BytesToUInt(data, i); i += 4; if (type == ExtraParamType.Flexible) Flexible = new FlexibleData(data, i); else if (type == ExtraParamType.Light) Light = new LightData(data, i); else if (type == ExtraParamType.Sculpt) Sculpt = new SculptData(data, i); i += (int)paramLength; totalLength += (int)paramLength + 6; } return totalLength; } public byte[] GetExtraParamsBytes() { byte[] flexible = null; byte[] light = null; byte[] sculpt = null; byte[] buffer = null; int size = 1; int pos = 0; byte count = 0; if (Flexible != null) { flexible = Flexible.GetBytes(); size += flexible.Length + 6; ++count; } if (Light != null) { light = Light.GetBytes(); size += light.Length + 6; ++count; } if (Sculpt != null) { sculpt = Sculpt.GetBytes(); size += sculpt.Length + 6; ++count; } buffer = new byte[size]; buffer[0] = count; ++pos; if (flexible != null) { Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Flexible), 0, buffer, pos, 2); pos += 2; Buffer.BlockCopy(Utils.UIntToBytes((uint)flexible.Length), 0, buffer, pos, 4); pos += 4; Buffer.BlockCopy(flexible, 0, buffer, pos, flexible.Length); pos += flexible.Length; } if (light != null) { Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Light), 0, buffer, pos, 2); pos += 2; Buffer.BlockCopy(Utils.UIntToBytes((uint)light.Length), 0, buffer, pos, 4); pos += 4; Buffer.BlockCopy(light, 0, buffer, pos, light.Length); pos += light.Length; } if (sculpt != null) { Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Sculpt), 0, buffer, pos, 2); pos += 2; Buffer.BlockCopy(Utils.UIntToBytes((uint)sculpt.Length), 0, buffer, pos, 4); pos += 4; Buffer.BlockCopy(sculpt, 0, buffer, pos, sculpt.Length); pos += sculpt.Length; } return buffer; } #endregion Public Methods #region Overrides public override bool Equals(object obj) { return (obj is Primitive) ? this == (Primitive)obj : false; } public bool Equals(Primitive other) { return this == other; } public override string ToString() { switch (PrimData.PCode) { case PCode.Prim: return String.Format("{0} ({1})", Type, ID); default: return String.Format("{0} ({1})", PrimData.PCode, ID); } } public override int GetHashCode() { return Position.GetHashCode() ^ Velocity.GetHashCode() ^ Acceleration.GetHashCode() ^ Rotation.GetHashCode() ^ AngularVelocity.GetHashCode() ^ ClickAction.GetHashCode() ^ (Flexible != null ? Flexible.GetHashCode() : 0) ^ (Light != null ? Light.GetHashCode() : 0) ^ (Sculpt != null ? Sculpt.GetHashCode() : 0) ^ Flags.GetHashCode() ^ PrimData.Material.GetHashCode() ^ MediaURL.GetHashCode() ^ //TODO: NameValues? (Properties != null ? Properties.OwnerID.GetHashCode() : 0) ^ ParentID.GetHashCode() ^ PrimData.PathBegin.GetHashCode() ^ PrimData.PathCurve.GetHashCode() ^ PrimData.PathEnd.GetHashCode() ^ PrimData.PathRadiusOffset.GetHashCode() ^ PrimData.PathRevolutions.GetHashCode() ^ PrimData.PathScaleX.GetHashCode() ^ PrimData.PathScaleY.GetHashCode() ^ PrimData.PathShearX.GetHashCode() ^ PrimData.PathShearY.GetHashCode() ^ PrimData.PathSkew.GetHashCode() ^ PrimData.PathTaperX.GetHashCode() ^ PrimData.PathTaperY.GetHashCode() ^ PrimData.PathTwist.GetHashCode() ^ PrimData.PathTwistBegin.GetHashCode() ^ PrimData.PCode.GetHashCode() ^ PrimData.ProfileBegin.GetHashCode() ^ PrimData.ProfileCurve.GetHashCode() ^ PrimData.ProfileEnd.GetHashCode() ^ PrimData.ProfileHollow.GetHashCode() ^ ParticleSys.GetHashCode() ^ TextColor.GetHashCode() ^ TextureAnim.GetHashCode() ^ (Textures != null ? Textures.GetHashCode() : 0) ^ SoundRadius.GetHashCode() ^ Scale.GetHashCode() ^ Sound.GetHashCode() ^ PrimData.State.GetHashCode() ^ Text.GetHashCode() ^ TreeSpecies.GetHashCode(); } #endregion Overrides #region Operators public static bool operator ==(Primitive lhs, Primitive rhs) { if ((Object)lhs == null || (Object)rhs == null) { return (Object)rhs == (Object)lhs; } return (lhs.ID == rhs.ID); } public static bool operator !=(Primitive lhs, Primitive rhs) { if ((Object)lhs == null || (Object)rhs == null) { return (Object)rhs != (Object)lhs; } return !(lhs.ID == rhs.ID); } #endregion Operators #region Parameter Packing Methods public static ushort PackBeginCut(float beginCut) { return (ushort)Math.Round(beginCut / CUT_QUANTA); } public static ushort PackEndCut(float endCut) { return (ushort)(50000 - (ushort)Math.Round(endCut / CUT_QUANTA)); } public static byte PackPathScale(float pathScale) { return (byte)(200 - (byte)Math.Round(pathScale / SCALE_QUANTA)); } public static sbyte PackPathShear(float pathShear) { return (sbyte)Math.Round(pathShear / SHEAR_QUANTA); } /// <summary> /// Packs PathTwist, PathTwistBegin, PathRadiusOffset, and PathSkew /// parameters in to signed eight bit values /// </summary> /// <param name="pathTwist">Floating point parameter to pack</param> /// <returns>Signed eight bit value containing the packed parameter</returns> public static sbyte PackPathTwist(float pathTwist) { return (sbyte)Math.Round(pathTwist / SCALE_QUANTA); } public static sbyte PackPathTaper(float pathTaper) { return (sbyte)Math.Round(pathTaper / TAPER_QUANTA); } public static byte PackPathRevolutions(float pathRevolutions) { return (byte)Math.Round((pathRevolutions - 1f) / REV_QUANTA); } public static ushort PackProfileHollow(float profileHollow) { return (ushort)Math.Round(profileHollow / HOLLOW_QUANTA); } #endregion Parameter Packing Methods #region Parameter Unpacking Methods public static float UnpackBeginCut(ushort beginCut) { return (float)beginCut * CUT_QUANTA; } public static float UnpackEndCut(ushort endCut) { return (float)(50000 - endCut) * CUT_QUANTA; } public static float UnpackPathScale(byte pathScale) { return (float)(200 - pathScale) * SCALE_QUANTA; } public static float UnpackPathShear(sbyte pathShear) { return (float)pathShear * SHEAR_QUANTA; } /// <summary> /// Unpacks PathTwist, PathTwistBegin, PathRadiusOffset, and PathSkew /// parameters from signed eight bit integers to floating point values /// </summary> /// <param name="pathTwist">Signed eight bit value to unpack</param> /// <returns>Unpacked floating point value</returns> public static float UnpackPathTwist(sbyte pathTwist) { return (float)pathTwist * SCALE_QUANTA; } public static float UnpackPathTaper(sbyte pathTaper) { return (float)pathTaper * TAPER_QUANTA; } public static float UnpackPathRevolutions(byte pathRevolutions) { return (float)pathRevolutions * REV_QUANTA + 1f; } public static float UnpackProfileHollow(ushort profileHollow) { return (float)profileHollow * HOLLOW_QUANTA; } #endregion Parameter Unpacking Methods } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type double with 4 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct dmat4x2 : IReadOnlyList<double>, IEquatable<dmat4x2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public double m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public double m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public double m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public double m11; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public double m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public double m21; /// <summary> /// Column 3, Rows 0 /// </summary> [DataMember] public double m30; /// <summary> /// Column 3, Rows 1 /// </summary> [DataMember] public double m31; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public dmat4x2(double m00, double m01, double m10, double m11, double m20, double m21, double m30, double m31) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m20 = m20; this.m21 = m21; this.m30 = m30; this.m31 = m31; } /// <summary> /// Constructs this matrix from a dmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a dmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a dmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a dmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = 0.0; this.m21 = 0.0; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1, dvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = 0.0; this.m31 = 0.0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public dmat4x2(dvec2 c0, dvec2 c1, dvec2 c2, dvec2 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = c3.x; this.m31 = c3.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public double[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 }, { m30, m31 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public double[] Values1D => new[] { m00, m01, m10, m11, m20, m21, m30, m31 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public dvec2 Column0 { get { return new dvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public dvec2 Column1 { get { return new dvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public dvec2 Column2 { get { return new dvec2(m20, m21); } set { m20 = value.x; m21 = value.y; } } /// <summary> /// Gets or sets the column nr 3 /// </summary> public dvec2 Column3 { get { return new dvec2(m30, m31); } set { m30 = value.x; m31 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public dvec4 Row0 { get { return new dvec4(m00, m10, m20, m30); } set { m00 = value.x; m10 = value.y; m20 = value.z; m30 = value.w; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public dvec4 Row1 { get { return new dvec4(m01, m11, m21, m31); } set { m01 = value.x; m11 = value.y; m21 = value.z; m31 = value.w; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static dmat4x2 Zero { get; } = new dmat4x2(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-ones matrix /// </summary> public static dmat4x2 Ones { get; } = new dmat4x2(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0); /// <summary> /// Predefined identity matrix /// </summary> public static dmat4x2 Identity { get; } = new dmat4x2(1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static dmat4x2 AllMaxValue { get; } = new dmat4x2(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static dmat4x2 DiagonalMaxValue { get; } = new dmat4x2(double.MaxValue, 0.0, 0.0, double.MaxValue, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static dmat4x2 AllMinValue { get; } = new dmat4x2(double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue, double.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static dmat4x2 DiagonalMinValue { get; } = new dmat4x2(double.MinValue, 0.0, 0.0, double.MinValue, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-Epsilon matrix /// </summary> public static dmat4x2 AllEpsilon { get; } = new dmat4x2(double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon, double.Epsilon); /// <summary> /// Predefined diagonal-Epsilon matrix /// </summary> public static dmat4x2 DiagonalEpsilon { get; } = new dmat4x2(double.Epsilon, 0.0, 0.0, double.Epsilon, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-NaN matrix /// </summary> public static dmat4x2 AllNaN { get; } = new dmat4x2(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN); /// <summary> /// Predefined diagonal-NaN matrix /// </summary> public static dmat4x2 DiagonalNaN { get; } = new dmat4x2(double.NaN, 0.0, 0.0, double.NaN, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-NegativeInfinity matrix /// </summary> public static dmat4x2 AllNegativeInfinity { get; } = new dmat4x2(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity); /// <summary> /// Predefined diagonal-NegativeInfinity matrix /// </summary> public static dmat4x2 DiagonalNegativeInfinity { get; } = new dmat4x2(double.NegativeInfinity, 0.0, 0.0, double.NegativeInfinity, 0.0, 0.0, 0.0, 0.0); /// <summary> /// Predefined all-PositiveInfinity matrix /// </summary> public static dmat4x2 AllPositiveInfinity { get; } = new dmat4x2(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity); /// <summary> /// Predefined diagonal-PositiveInfinity matrix /// </summary> public static dmat4x2 DiagonalPositiveInfinity { get; } = new dmat4x2(double.PositiveInfinity, 0.0, 0.0, double.PositiveInfinity, 0.0, 0.0, 0.0, 0.0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<double> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; yield return m20; yield return m21; yield return m30; yield return m31; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (4 x 2 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public double this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; case 4: return m20; case 5: return m21; case 6: return m30; case 7: return m31; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; case 4: this.m20 = value; break; case 5: this.m21 = value; break; case 6: this.m30 = value; break; case 7: this.m31 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public double this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(dmat4x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m30.Equals(rhs.m30) && m31.Equals(rhs.m31)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is dmat4x2 && Equals((dmat4x2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(dmat4x2 lhs, dmat4x2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(dmat4x2 lhs, dmat4x2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m30.GetHashCode()) * 397) ^ m31.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public dmat2x4 Transposed => new dmat2x4(m00, m10, m20, m30, m01, m11, m21, m31); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public double MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public double MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => (((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31))); /// <summary> /// Returns the sum of all fields. /// </summary> public double Sum => (((m00 + m01) + (m10 + m11)) + ((m20 + m21) + (m30 + m31))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m20) + Math.Abs(m21)) + (Math.Abs(m30) + Math.Abs(m31)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public double NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m30)), Math.Abs(m31)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m20), p) + Math.Pow((double)Math.Abs(m21), p)) + (Math.Pow((double)Math.Abs(m30), p) + Math.Pow((double)Math.Abs(m31), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat2x4 -> dmat2. /// </summary> public static dmat2 operator*(dmat4x2 lhs, dmat2x4 rhs) => new dmat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13))); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat3x4 -> dmat3x2. /// </summary> public static dmat3x2 operator*(dmat4x2 lhs, dmat3x4 rhs) => new dmat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23))); /// <summary> /// Executes a matrix-matrix-multiplication dmat4x2 * dmat4 -> dmat4x2. /// </summary> public static dmat4x2 operator*(dmat4x2 lhs, dmat4 rhs) => new dmat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23)), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + (lhs.m20 * rhs.m32 + lhs.m30 * rhs.m33)), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + (lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33))); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static dvec2 operator*(dmat4x2 m, dvec4 v) => new dvec2(((m.m00 * v.x + m.m10 * v.y) + (m.m20 * v.z + m.m30 * v.w)), ((m.m01 * v.x + m.m11 * v.y) + (m.m21 * v.z + m.m31 * v.w))); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static dmat4x2 CompMul(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21, A.m30 * B.m30, A.m31 * B.m31); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static dmat4x2 CompDiv(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21, A.m30 / B.m30, A.m31 / B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static dmat4x2 CompAdd(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21, A.m30 + B.m30, A.m31 + B.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static dmat4x2 CompSub(dmat4x2 A, dmat4x2 B) => new dmat4x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21, A.m30 - B.m30, A.m31 - B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static dmat4x2 operator+(dmat4x2 lhs, dmat4x2 rhs) => new dmat4x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m30 + rhs.m30, lhs.m31 + rhs.m31); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static dmat4x2 operator+(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m30 + rhs, lhs.m31 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static dmat4x2 operator+(double lhs, dmat4x2 rhs) => new dmat4x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m30, lhs + rhs.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static dmat4x2 operator-(dmat4x2 lhs, dmat4x2 rhs) => new dmat4x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m30 - rhs.m30, lhs.m31 - rhs.m31); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static dmat4x2 operator-(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m30 - rhs, lhs.m31 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static dmat4x2 operator-(double lhs, dmat4x2 rhs) => new dmat4x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m30, lhs - rhs.m31); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static dmat4x2 operator/(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m30 / rhs, lhs.m31 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static dmat4x2 operator/(double lhs, dmat4x2 rhs) => new dmat4x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m30, lhs / rhs.m31); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static dmat4x2 operator*(dmat4x2 lhs, double rhs) => new dmat4x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m30 * rhs, lhs.m31 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static dmat4x2 operator*(double lhs, dmat4x2 rhs) => new dmat4x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m30, lhs * rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat4x2 operator<(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m30 < rhs.m30, lhs.m31 < rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m30 < rhs, lhs.m31 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(double lhs, dmat4x2 rhs) => new bmat4x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m30, lhs < rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat4x2 operator<=(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m30 <= rhs.m30, lhs.m31 <= rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m30 <= rhs, lhs.m31 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(double lhs, dmat4x2 rhs) => new bmat4x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m30, lhs <= rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat4x2 operator>(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m30 > rhs.m30, lhs.m31 > rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m30 > rhs, lhs.m31 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(double lhs, dmat4x2 rhs) => new bmat4x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m30, lhs > rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat4x2 operator>=(dmat4x2 lhs, dmat4x2 rhs) => new bmat4x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m30 >= rhs.m30, lhs.m31 >= rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(dmat4x2 lhs, double rhs) => new bmat4x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m30 >= rhs, lhs.m31 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(double lhs, dmat4x2 rhs) => new bmat4x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m30, lhs >= rhs.m31); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Framework.Serialization.External { /// <summary> /// Serialize and deserialize user inventory items as an external format. /// </summary> public class UserInventoryItemSerializer { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Dictionary<string, Action<InventoryItemBase, XmlTextReader>> m_InventoryItemXmlProcessors = new Dictionary<string, Action<InventoryItemBase, XmlTextReader>>(); #region InventoryItemBase Processor initialization static UserInventoryItemSerializer() { m_InventoryItemXmlProcessors.Add("Name", ProcessName); m_InventoryItemXmlProcessors.Add("ID", ProcessID); m_InventoryItemXmlProcessors.Add("InvType", ProcessInvType); m_InventoryItemXmlProcessors.Add("CreatorUUID", ProcessCreatorUUID); m_InventoryItemXmlProcessors.Add("CreatorID", ProcessCreatorID); m_InventoryItemXmlProcessors.Add("CreatorData", ProcessCreatorData); m_InventoryItemXmlProcessors.Add("CreationDate", ProcessCreationDate); m_InventoryItemXmlProcessors.Add("Owner", ProcessOwner); m_InventoryItemXmlProcessors.Add("Description", ProcessDescription); m_InventoryItemXmlProcessors.Add("AssetType", ProcessAssetType); m_InventoryItemXmlProcessors.Add("AssetID", ProcessAssetID); m_InventoryItemXmlProcessors.Add("SaleType", ProcessSaleType); m_InventoryItemXmlProcessors.Add("SalePrice", ProcessSalePrice); m_InventoryItemXmlProcessors.Add("BasePermissions", ProcessBasePermissions); m_InventoryItemXmlProcessors.Add("CurrentPermissions", ProcessCurrentPermissions); m_InventoryItemXmlProcessors.Add("EveryOnePermissions", ProcessEveryOnePermissions); m_InventoryItemXmlProcessors.Add("NextPermissions", ProcessNextPermissions); m_InventoryItemXmlProcessors.Add("Flags", ProcessFlags); m_InventoryItemXmlProcessors.Add("GroupID", ProcessGroupID); m_InventoryItemXmlProcessors.Add("GroupOwned", ProcessGroupOwned); } #endregion #region InventoryItemBase Processors private static void ProcessName(InventoryItemBase item, XmlTextReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessID(InventoryItemBase item, XmlTextReader reader) { item.ID = Util.ReadUUID(reader, "ID"); } private static void ProcessInvType(InventoryItemBase item, XmlTextReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessCreatorUUID(InventoryItemBase item, XmlTextReader reader) { item.CreatorId = reader.ReadElementContentAsString("CreatorUUID", String.Empty); } private static void ProcessCreatorID(InventoryItemBase item, XmlTextReader reader) { // when it exists, this overrides the previous item.CreatorId = reader.ReadElementContentAsString("CreatorID", String.Empty); } private static void ProcessCreationDate(InventoryItemBase item, XmlTextReader reader) { item.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessOwner(InventoryItemBase item, XmlTextReader reader) { item.Owner = Util.ReadUUID(reader, "Owner"); } private static void ProcessDescription(InventoryItemBase item, XmlTextReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessAssetType(InventoryItemBase item, XmlTextReader reader) { item.AssetType = reader.ReadElementContentAsInt("AssetType", String.Empty); } private static void ProcessAssetID(InventoryItemBase item, XmlTextReader reader) { item.AssetID = Util.ReadUUID(reader, "AssetID"); } private static void ProcessSaleType(InventoryItemBase item, XmlTextReader reader) { item.SaleType = (byte)reader.ReadElementContentAsInt("SaleType", String.Empty); } private static void ProcessSalePrice(InventoryItemBase item, XmlTextReader reader) { item.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessBasePermissions(InventoryItemBase item, XmlTextReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessCurrentPermissions(InventoryItemBase item, XmlTextReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessEveryOnePermissions(InventoryItemBase item, XmlTextReader reader) { item.EveryOnePermissions = (uint)reader.ReadElementContentAsInt("EveryOnePermissions", String.Empty); } private static void ProcessNextPermissions(InventoryItemBase item, XmlTextReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessFlags(InventoryItemBase item, XmlTextReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessGroupID(InventoryItemBase item, XmlTextReader reader) { item.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessGroupOwned(InventoryItemBase item, XmlTextReader reader) { item.GroupOwned = Util.ReadBoolean(reader); } private static void ProcessCreatorData(InventoryItemBase item, XmlTextReader reader) { item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } #endregion /// <summary> /// Deserialize item /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(byte[] serialization) { return Deserialize(Encoding.ASCII.GetString(serialization, 0, serialization.Length)); } /// <summary> /// Deserialize settings /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static InventoryItemBase Deserialize(string serialization) { InventoryItemBase item = new InventoryItemBase(); using (XmlTextReader reader = new XmlTextReader(new StringReader(serialization))) { reader.ReadStartElement("InventoryItem"); ExternalRepresentationUtils.ExecuteReadProcessors<InventoryItemBase>( item, m_InventoryItemXmlProcessors, reader); reader.ReadEndElement(); // InventoryItem } //m_log.DebugFormat("[XXX]: parsed InventoryItemBase {0} - {1}", obj.Name, obj.UUID); return item; } public static string Serialize(InventoryItemBase inventoryItem, Dictionary<string, object> options, IUserAccountService userAccountService) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("InventoryItem"); writer.WriteStartElement("Name"); writer.WriteString(inventoryItem.Name); writer.WriteEndElement(); writer.WriteStartElement("ID"); writer.WriteString(inventoryItem.ID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("InvType"); writer.WriteString(inventoryItem.InvType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CreatorUUID"); writer.WriteString(OspResolver.MakeOspa(inventoryItem.CreatorIdAsUuid, userAccountService)); writer.WriteEndElement(); writer.WriteStartElement("CreationDate"); writer.WriteString(inventoryItem.CreationDate.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Owner"); writer.WriteString(inventoryItem.Owner.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Description"); writer.WriteString(inventoryItem.Description); writer.WriteEndElement(); writer.WriteStartElement("AssetType"); writer.WriteString(inventoryItem.AssetType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("AssetID"); writer.WriteString(inventoryItem.AssetID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SaleType"); writer.WriteString(inventoryItem.SaleType.ToString()); writer.WriteEndElement(); writer.WriteStartElement("SalePrice"); writer.WriteString(inventoryItem.SalePrice.ToString()); writer.WriteEndElement(); writer.WriteStartElement("BasePermissions"); writer.WriteString(inventoryItem.BasePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("CurrentPermissions"); writer.WriteString(inventoryItem.CurrentPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("EveryOnePermissions"); writer.WriteString(inventoryItem.EveryOnePermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("NextPermissions"); writer.WriteString(inventoryItem.NextPermissions.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Flags"); writer.WriteString(inventoryItem.Flags.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupID"); writer.WriteString(inventoryItem.GroupID.ToString()); writer.WriteEndElement(); writer.WriteStartElement("GroupOwned"); writer.WriteString(inventoryItem.GroupOwned.ToString()); writer.WriteEndElement(); if (options.ContainsKey("creators") && !string.IsNullOrEmpty(inventoryItem.CreatorData)) writer.WriteElementString("CreatorData", inventoryItem.CreatorData); else if (options.ContainsKey("home")) { if (userAccountService != null) { UserAccount account = userAccountService.GetUserAccount(UUID.Zero, inventoryItem.CreatorIdAsUuid); if (account != null) { string creatorData = ExternalRepresentationUtils.CalcCreatorData((string)options["home"], inventoryItem.CreatorIdAsUuid, account.FirstName + " " + account.LastName); writer.WriteElementString("CreatorData", creatorData); } writer.WriteElementString("CreatorID", inventoryItem.CreatorId); } } writer.WriteEndElement(); writer.Close(); sw.Close(); return sw.ToString(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session. /// </summary> internal sealed partial class SessionStateInternal { #region Functions /// <summary> /// Add an new SessionState function entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateFunctionEntry entry) { ScriptBlock sb = entry.ScriptBlock.Clone(); FunctionInfo fn = this.SetFunction(entry.Name, sb, null, entry.Options, false, CommandOrigin.Internal, this.ExecutionContext, entry.HelpFile, true); fn.Visibility = entry.Visibility; fn.Module = entry.Module; fn.ScriptBlock.LanguageMode = entry.ScriptBlock.LanguageMode ?? PSLanguageMode.FullLanguage; } /// <summary> /// Gets a flattened view of the functions that are visible using /// the current scope as a reference and filtering the functions in /// the other scopes based on the scoping rules. /// </summary> /// <returns> /// An IDictionary representing the visible functions. /// </returns> internal IDictionary<string, FunctionInfo> GetFunctionTable() { SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); Dictionary<string, FunctionInfo> result = new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase); foreach (SessionStateScope scope in scopeEnumerator) { foreach (FunctionInfo entry in scope.FunctionTable.Values) { if (!result.ContainsKey(entry.Name)) { result.Add(entry.Name, entry); } } } return result; } /// <summary> /// Gets an IEnumerable for the function table for a given scope. /// </summary> /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> internal IDictionary<string, FunctionInfo> GetFunctionTableAtScope(string scopeID) { Dictionary<string, FunctionInfo> result = new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase); SessionStateScope scope = GetScopeByID(scopeID); foreach (FunctionInfo entry in scope.FunctionTable.Values) { // Make sure the function/filter isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || scope == _currentScope) { result.Add(entry.Name, entry); } } return result; } /// <summary> /// List of functions/filters to export from this session state object... /// </summary> internal List<FunctionInfo> ExportedFunctions { get; } = new List<FunctionInfo>(); internal bool UseExportList { get; set; } = false; /// <summary> /// Set to true when module functions are being explicitly exported using Export-ModuleMember. /// </summary> internal bool FunctionsExported { get; set; } /// <summary> /// Set to true when any processed module functions are being explicitly exported using '*' wildcard. /// </summary> internal bool FunctionsExportedWithWildcard { get { return _functionsExportedWithWildcard; } set { Dbg.Assert((value), "This property should never be set/reset to false"); if (value) { _functionsExportedWithWildcard = value; } } } private bool _functionsExportedWithWildcard; /// <summary> /// Set to true if module loading is performed under a manifest that explicitly exports functions (no wildcards) /// </summary> internal bool ManifestWithExplicitFunctionExport { get; set; } /// <summary> /// Get a functions out of session state. /// </summary> /// <param name="name"> /// name of function to look up /// </param> /// <param name="origin"> /// Origin of the command that called this API... /// </param> /// <returns> /// The value of the specified function. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal FunctionInfo GetFunction(string name, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } FunctionInfo result = null; FunctionLookupPath lookupPath = new FunctionLookupPath(name); FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher(this, lookupPath, origin); if (searcher.MoveNext()) { result = ((IEnumerator<FunctionInfo>)searcher).Current; } return (IsFunctionVisibleInDebugger(result, origin)) ? result : null; } private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin origin) { // Ensure the returned function item is not exposed across language boundaries when in // a debugger breakpoint or nested prompt. // A debugger breakpoint/nested prompt has access to all current scoped functions. // This includes both running commands from the prompt or via a debugger Action scriptblock. // Early out. // Always allow built-in functions needed for command line debugging. if ((this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) || (fnInfo == null) || (fnInfo.Name.Equals("prompt", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("Clear-Host", StringComparison.Ordinal))) { return true; } // Check both InNestedPrompt and Debugger.InBreakpoint to ensure we don't miss a case. // Function is not visible if function and context language modes are different. var runspace = this.ExecutionContext.CurrentRunspace; if ((runspace != null) && (runspace.InNestedPrompt || (runspace.Debugger?.InBreakpoint == true)) && (fnInfo.DefiningLanguageMode.HasValue && (fnInfo.DefiningLanguageMode != this.ExecutionContext.LanguageMode))) { return false; } return true; } /// <summary> /// Get a functions out of session state. /// </summary> /// <param name="name"> /// name of function to look up /// </param> /// <returns> /// The value of the specified function. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal FunctionInfo GetFunction(string name) { return GetFunction(name, CommandOrigin.Internal); } private static IEnumerable<string> GetFunctionAliases(IParameterMetadataProvider ipmp) { if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; var attributes = ipmp.Body.ParamBlock.Attributes; foreach (var attributeAst in attributes) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); if (attributeType == typeof(AliasAttribute)) { var cvv = new ConstantValueVisitor { AttributeArgument = true }; for (int i = 0; i < attributeAst.PositionalArguments.Count; i++) { yield return Compiler.s_attrArgToStringConverter.Target(Compiler.s_attrArgToStringConverter, attributeAst.PositionalArguments[i].Accept(cvv)); } } } } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunctionRaw( string name, ScriptBlock function, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); var functionInfo = searcher.InitialScope.SetFunction(name, function, null, options, false, origin, ExecutionContext); foreach (var aliasName in GetFunctionAliases(function.Ast as IParameterMetadataProvider)) { searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin); } return functionInfo; } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin) { return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, null); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, string helpFile) { return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, helpFile, false); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, ExecutionContext context, string helpFile) { return SetFunction(name, function, originalFunction, options, force, origin, context, helpFile, false); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <param name="isPreValidated"> /// Set to true if it is a regular function (meaning, we do not need to check if the script contains JobDefinition Attribute and then process it) /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, ExecutionContext context, string helpFile, bool isPreValidated) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); return searcher.InitialScope.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// The origin of the caller /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); FunctionInfo result = null; SessionStateScope scope = searcher.InitialScope; if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; name = searcher.Name; if (path.IsPrivate) { // Need to add the Private flag FunctionInfo existingFunction = scope.GetFunction(name); options |= existingFunction.Options; result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } else { if (path.IsPrivate) { result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } return result; } /// <summary> /// Set a function in the current scope of session state. /// /// BUGBUG: this overload is preserved because a lot of tests use reflection to /// call it. The tests should be fixed and this API eventually removed. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction(string name, ScriptBlock function, bool force) { return SetFunction(name, function, null, force, CommandOrigin.Internal); } /// <summary> /// Removes a function from the function table. /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="origin"> /// THe origin of the caller of this API /// </param> /// <param name="force"> /// If true, the function is removed even if it is ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } // Use the scope enumerator to find an existing function SessionStateScope scope = _currentScope; FunctionLookupPath path = new FunctionLookupPath(name); FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; } scope.RemoveFunction(name, force); } /// <summary> /// Removes a function from the function table. /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="force"> /// If true, the function is removed even if it is ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, bool force) { RemoveFunction(name, force, CommandOrigin.Internal); } /// <summary> /// Removes a function from the function table /// if the function was imported from the given module. /// /// BUGBUG: This is only used by the implicit remoting functions... /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="module"> /// Module the function might be imported from. /// </param> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, PSModuleInfo module) { Dbg.Assert(module != null, "Caller should verify that module parameter is not null"); FunctionInfo func = GetFunction(name) as FunctionInfo; if (func != null && func.ScriptBlock != null && func.ScriptBlock.File != null && func.ScriptBlock.File.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { RemoveFunction(name, true); } } #endregion Functions } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { private sealed class DockDragHandler : DragHandler { private class DockIndicator : DragForm { #region IHitTest private interface IHitTest { DockStyle HitTest(Point pt); DockStyle Status { get; set; } } #endregion #region PanelIndicator private class PanelIndicator : PictureBox, IHitTest { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_Active; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_Active; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_Active; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_Active; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_Active; public PanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } #endregion PanelIndicator #region PaneIndicator private class PaneIndicator : PictureBox, IHitTest { private struct HotSpotIndex { public HotSpotIndex(int x, int y, DockStyle dockStyle) { m_x = x; m_y = y; m_dockStyle = dockStyle; } private int m_x; public int X { get { return m_x; } } private int m_y; public int Y { get { return m_y; } } private DockStyle m_dockStyle; public DockStyle DockStyle { get { return m_dockStyle; } } } private static Bitmap _bitmapPaneDiamond = Resources.DockIndicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.DockIndicator_PaneDiamond_Left; private static Bitmap _bitmapPaneDiamondRight = Resources.DockIndicator_PaneDiamond_Right; private static Bitmap _bitmapPaneDiamondTop = Resources.DockIndicator_PaneDiamond_Top; private static Bitmap _bitmapPaneDiamondBottom = Resources.DockIndicator_PaneDiamond_Bottom; private static Bitmap _bitmapPaneDiamondFill = Resources.DockIndicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.DockIndicator_PaneDiamond_HotSpot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotSpotIndex; private static HotSpotIndex[] _hotSpots = new HotSpotIndex[] { new HotSpotIndex(1, 0, DockStyle.Top), new HotSpotIndex(0, 1, DockStyle.Left), new HotSpotIndex(1, 1, DockStyle.Fill), new HotSpotIndex(2, 1, DockStyle.Right), new HotSpotIndex(1, 2, DockStyle.Bottom) }; private static GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public PaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public static GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } #endregion PaneIndicator #region consts private int _PanelIndicatorMargin = 10; #endregion private DockDragHandler m_dragHandler; public DockIndicator(DockDragHandler dragHandler) { m_dragHandler = dragHandler; Controls.AddRange(new Control[] { PaneDiamond, PanelLeft, PanelRight, PanelTop, PanelBottom, PanelFill }); Region = new Region(Rectangle.Empty); } private PaneIndicator m_paneDiamond = null; private PaneIndicator PaneDiamond { get { if (m_paneDiamond == null) m_paneDiamond = new PaneIndicator(); return m_paneDiamond; } } private PanelIndicator m_panelLeft = null; private PanelIndicator PanelLeft { get { if (m_panelLeft == null) m_panelLeft = new PanelIndicator(DockStyle.Left); return m_panelLeft; } } private PanelIndicator m_panelRight = null; private PanelIndicator PanelRight { get { if (m_panelRight == null) m_panelRight = new PanelIndicator(DockStyle.Right); return m_panelRight; } } private PanelIndicator m_panelTop = null; private PanelIndicator PanelTop { get { if (m_panelTop == null) m_panelTop = new PanelIndicator(DockStyle.Top); return m_panelTop; } } private PanelIndicator m_panelBottom = null; private PanelIndicator PanelBottom { get { if (m_panelBottom == null) m_panelBottom = new PanelIndicator(DockStyle.Bottom); return m_panelBottom; } } private PanelIndicator m_panelFill = null; private PanelIndicator PanelFill { get { if (m_panelFill == null) m_panelFill = new PanelIndicator(DockStyle.Fill); return m_panelFill; } } private bool m_fullPanelEdge = false; public bool FullPanelEdge { get { return m_fullPanelEdge; } set { if (m_fullPanelEdge == value) return; m_fullPanelEdge = value; RefreshChanges(); } } public DockDragHandler DragHandler { get { return m_dragHandler; } } public DockPanel DockPanel { get { return DragHandler.DockPanel; } } private DockPane m_dockPane = null; public DockPane DockPane { get { return m_dockPane; } internal set { if (m_dockPane == value) return; DockPane oldDisplayingPane = DisplayingPane; m_dockPane = value; if (oldDisplayingPane != DisplayingPane) RefreshChanges(); } } private IHitTest m_hitTest = null; private IHitTest HitTestResult { get { return m_hitTest; } set { if (m_hitTest == value) return; if (m_hitTest != null) m_hitTest.Status = DockStyle.None; m_hitTest = value; } } private DockPane DisplayingPane { get { return ShouldPaneDiamondVisible() ? DockPane : null; } } private void RefreshChanges() { Region region = new Region(Rectangle.Empty); Rectangle rectDockArea = FullPanelEdge ? DockPanel.DockArea : DockPanel.DocumentWindowBounds; rectDockArea = RectangleToClient(DockPanel.RectangleToScreen(rectDockArea)); if (ShouldPanelIndicatorVisible(DockState.DockLeft)) { PanelLeft.Location = new Point(rectDockArea.X + _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelLeft.Visible = true; region.Union(PanelLeft.Bounds); } else PanelLeft.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockRight)) { PanelRight.Location = new Point(rectDockArea.X + rectDockArea.Width - PanelRight.Width - _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelRight.Visible = true; region.Union(PanelRight.Bounds); } else PanelRight.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockTop)) { PanelTop.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelTop.Width) / 2, rectDockArea.Y + _PanelIndicatorMargin); PanelTop.Visible = true; region.Union(PanelTop.Bounds); } else PanelTop.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockBottom)) { PanelBottom.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelBottom.Width) / 2, rectDockArea.Y + rectDockArea.Height - PanelBottom.Height - _PanelIndicatorMargin); PanelBottom.Visible = true; region.Union(PanelBottom.Bounds); } else PanelBottom.Visible = false; if (ShouldPanelIndicatorVisible(DockState.Document)) { Rectangle rectDocumentWindow = RectangleToClient(DockPanel.RectangleToScreen(DockPanel.DocumentWindowBounds)); PanelFill.Location = new Point(rectDocumentWindow.X + (rectDocumentWindow.Width - PanelFill.Width) / 2, rectDocumentWindow.Y + (rectDocumentWindow.Height - PanelFill.Height) / 2); PanelFill.Visible = true; region.Union(PanelFill.Bounds); } else PanelFill.Visible = false; if (ShouldPaneDiamondVisible()) { Rectangle rect = RectangleToClient(DockPane.RectangleToScreen(DockPane.ClientRectangle)); PaneDiamond.Location = new Point(rect.Left + (rect.Width - PaneDiamond.Width) / 2, rect.Top + (rect.Height - PaneDiamond.Height) / 2); PaneDiamond.Visible = true; using (GraphicsPath graphicsPath = PaneIndicator.DisplayingGraphicsPath.Clone() as GraphicsPath) { Point[] pts = new Point[] { new Point(PaneDiamond.Left, PaneDiamond.Top), new Point(PaneDiamond.Right, PaneDiamond.Top), new Point(PaneDiamond.Left, PaneDiamond.Bottom) }; using (Matrix matrix = new Matrix(PaneDiamond.ClientRectangle, pts)) { graphicsPath.Transform(matrix); } region.Union(graphicsPath); } } else PaneDiamond.Visible = false; Region = region; } private bool ShouldPanelIndicatorVisible(DockState dockState) { if (!Visible) return false; if (DockPanel.DockWindows[dockState].Visible) return false; return DragHandler.DragSource.IsDockStateValid(dockState); } private bool ShouldPaneDiamondVisible() { if (DockPane == null) return false; if (!DockPanel.AllowEndUserNestedDocking) return false; return DragHandler.DragSource.CanDockTo(DockPane); } public override void Show(bool bActivate) { base.Show(bActivate); Bounds = SystemInformation.VirtualScreen; RefreshChanges(); } public void TestDrop() { Point pt = Control.MousePosition; DockPane = DockHelper.PaneAtPoint(pt, DockPanel); if (TestDrop(PanelLeft, pt) != DockStyle.None) HitTestResult = PanelLeft; else if (TestDrop(PanelRight, pt) != DockStyle.None) HitTestResult = PanelRight; else if (TestDrop(PanelTop, pt) != DockStyle.None) HitTestResult = PanelTop; else if (TestDrop(PanelBottom, pt) != DockStyle.None) HitTestResult = PanelBottom; else if (TestDrop(PanelFill, pt) != DockStyle.None) HitTestResult = PanelFill; else if (TestDrop(PaneDiamond, pt) != DockStyle.None) HitTestResult = PaneDiamond; else HitTestResult = null; if (HitTestResult != null) { if (HitTestResult is PaneIndicator) DragHandler.Outline.Show(DockPane, HitTestResult.Status); else DragHandler.Outline.Show(DockPanel, HitTestResult.Status, FullPanelEdge); } } private static DockStyle TestDrop(IHitTest hitTest, Point pt) { return hitTest.Status = hitTest.HitTest(pt); } } private class DockOutline : DockOutlineBase { public DockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = SystemColors.ActiveCaption; DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) DragForm.Region = new Region(Rectangle.Empty); else if (DragForm.Region != null) DragForm.Region = null; } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; DragForm.Region = region; } } public DockDragHandler(DockPanel panel) : base(panel) { } public new IDockDragSource DragSource { get { return base.DragSource as IDockDragSource; } set { base.DragSource = value; } } private DockOutlineBase m_outline; public DockOutlineBase Outline { get { return m_outline; } private set { m_outline = value; } } private DockIndicator m_indicator; private DockIndicator Indicator { get { return m_indicator; } set { m_indicator = value; } } private Rectangle m_floatOutlineBounds; private Rectangle FloatOutlineBounds { get { return m_floatOutlineBounds; } set { m_floatOutlineBounds = value; } } public void BeginDrag(IDockDragSource dragSource) { DragSource = dragSource; if (!BeginDrag()) { DragSource = null; return; } Outline = new DockOutline(); Indicator = new DockIndicator(this); Indicator.Show(false); FloatOutlineBounds = DragSource.BeginDrag(StartMousePosition); } protected override void OnDragging() { TestDrop(); } protected override void OnEndDrag(bool abort) { DockPanel.SuspendLayout(true); Outline.Close(); Indicator.Close(); EndDrag(abort); // Queue a request to layout all children controls DockPanel.PerformMdiClientLayout(); DockPanel.ResumeLayout(true, true); DragSource.EndDrag(); DragSource = null; } private void TestDrop() { Outline.FlagTestDrop = false; Indicator.FullPanelEdge = ((Control.ModifierKeys & Keys.Shift) != 0); if ((Control.ModifierKeys & Keys.Control) == 0) { Indicator.TestDrop(); if (!Outline.FlagTestDrop) { DockPane pane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (pane != null && DragSource.IsDockStateValid(pane.DockState)) pane.TestDrop(DragSource, Outline); } if (!Outline.FlagTestDrop && DragSource.IsDockStateValid(DockState.Float)) { FloatWindow floatWindow = DockHelper.FloatWindowAtPoint(Control.MousePosition, DockPanel); if (floatWindow != null) floatWindow.TestDrop(DragSource, Outline); } } else Indicator.DockPane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (!Outline.FlagTestDrop) { if (DragSource.IsDockStateValid(DockState.Float)) { Rectangle rect = FloatOutlineBounds; rect.Offset(Control.MousePosition.X - StartMousePosition.X, Control.MousePosition.Y - StartMousePosition.Y); Outline.Show(rect); } } if (!Outline.FlagTestDrop) { Cursor.Current = Cursors.No; Outline.Show(); } else Cursor.Current = DragControl.Cursor; } private void EndDrag(bool abort) { if (abort) return; if (!Outline.FloatWindowBounds.IsEmpty) DragSource.FloatAt(Outline.FloatWindowBounds); else if (Outline.DockTo is DockPane) { DockPane pane = Outline.DockTo as DockPane; DragSource.DockTo(pane, Outline.Dock, Outline.ContentIndex); } else if (Outline.DockTo is DockPanel) { DockPanel panel = Outline.DockTo as DockPanel; panel.UpdateDockWindowZOrder(Outline.Dock, Outline.FlagFullEdge); DragSource.DockTo(panel, Outline.Dock); } } } private DockDragHandler m_dockDragHandler = null; private DockDragHandler GetDockDragHandler() { if (m_dockDragHandler == null) m_dockDragHandler = new DockDragHandler(this); return m_dockDragHandler; } internal void BeginDrag(IDockDragSource dragSource) { GetDockDragHandler().BeginDrag(dragSource); } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass(typeof(global::android.widget.BaseAdapter_))] public abstract partial class BaseAdapter : java.lang.Object, ListAdapter, SpinnerAdapter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BaseAdapter() { InitJNI(); } protected BaseAdapter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getCount10997; public abstract int getCount(); internal static global::MonoJavaBridge.MethodId _getItem10998; public abstract global::java.lang.Object getItem(int arg0); internal static global::MonoJavaBridge.MethodId _getItemId10999; public abstract long getItemId(int arg0); internal static global::MonoJavaBridge.MethodId _getView11000; public abstract global::android.view.View getView(int arg0, android.view.View arg1, android.view.ViewGroup arg2); internal static global::MonoJavaBridge.MethodId _isEmpty11001; public virtual bool isEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter._isEmpty11001); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._isEmpty11001); } internal static global::MonoJavaBridge.MethodId _isEnabled11002; public virtual bool isEnabled(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter._isEnabled11002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._isEnabled11002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _registerDataSetObserver11003; public virtual void registerDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter._registerDataSetObserver11003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._registerDataSetObserver11003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterDataSetObserver11004; public virtual void unregisterDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter._unregisterDataSetObserver11004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._unregisterDataSetObserver11004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _areAllItemsEnabled11005; public virtual bool areAllItemsEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter._areAllItemsEnabled11005); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._areAllItemsEnabled11005); } internal static global::MonoJavaBridge.MethodId _hasStableIds11006; public virtual bool hasStableIds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter._hasStableIds11006); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._hasStableIds11006); } internal static global::MonoJavaBridge.MethodId _getItemViewType11007; public virtual int getItemViewType(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.BaseAdapter._getItemViewType11007, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._getItemViewType11007, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getViewTypeCount11008; public virtual int getViewTypeCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.BaseAdapter._getViewTypeCount11008); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._getViewTypeCount11008); } internal static global::MonoJavaBridge.MethodId _getDropDownView11009; public virtual global::android.view.View getDropDownView(int arg0, android.view.View arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter._getDropDownView11009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._getDropDownView11009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _notifyDataSetChanged11010; public virtual void notifyDataSetChanged() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter._notifyDataSetChanged11010); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._notifyDataSetChanged11010); } internal static global::MonoJavaBridge.MethodId _notifyDataSetInvalidated11011; public virtual void notifyDataSetInvalidated() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter._notifyDataSetInvalidated11011); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._notifyDataSetInvalidated11011); } internal static global::MonoJavaBridge.MethodId _BaseAdapter11012; public BaseAdapter() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.BaseAdapter.staticClass, global::android.widget.BaseAdapter._BaseAdapter11012); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.BaseAdapter.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/BaseAdapter")); global::android.widget.BaseAdapter._getCount10997 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getCount", "()I"); global::android.widget.BaseAdapter._getItem10998 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getItem", "(I)Ljava/lang/Object;"); global::android.widget.BaseAdapter._getItemId10999 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getItemId", "(I)J"); global::android.widget.BaseAdapter._getView11000 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.BaseAdapter._isEmpty11001 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "isEmpty", "()Z"); global::android.widget.BaseAdapter._isEnabled11002 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "isEnabled", "(I)Z"); global::android.widget.BaseAdapter._registerDataSetObserver11003 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.widget.BaseAdapter._unregisterDataSetObserver11004 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.widget.BaseAdapter._areAllItemsEnabled11005 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "areAllItemsEnabled", "()Z"); global::android.widget.BaseAdapter._hasStableIds11006 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "hasStableIds", "()Z"); global::android.widget.BaseAdapter._getItemViewType11007 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getItemViewType", "(I)I"); global::android.widget.BaseAdapter._getViewTypeCount11008 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getViewTypeCount", "()I"); global::android.widget.BaseAdapter._getDropDownView11009 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "getDropDownView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.BaseAdapter._notifyDataSetChanged11010 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "notifyDataSetChanged", "()V"); global::android.widget.BaseAdapter._notifyDataSetInvalidated11011 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "notifyDataSetInvalidated", "()V"); global::android.widget.BaseAdapter._BaseAdapter11012 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.BaseAdapter))] public sealed partial class BaseAdapter_ : android.widget.BaseAdapter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BaseAdapter_() { InitJNI(); } internal BaseAdapter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getCount11013; public override int getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.BaseAdapter_._getCount11013); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.BaseAdapter_.staticClass, global::android.widget.BaseAdapter_._getCount11013); } internal static global::MonoJavaBridge.MethodId _getItem11014; public override global::java.lang.Object getItem(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter_._getItem11014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter_.staticClass, global::android.widget.BaseAdapter_._getItem11014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getItemId11015; public override long getItemId(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.BaseAdapter_._getItemId11015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.BaseAdapter_.staticClass, global::android.widget.BaseAdapter_._getItemId11015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getView11016; public override global::android.view.View getView(int arg0, android.view.View arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter_._getView11016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.BaseAdapter_.staticClass, global::android.widget.BaseAdapter_._getView11016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.BaseAdapter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/BaseAdapter")); global::android.widget.BaseAdapter_._getCount11013 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter_.staticClass, "getCount", "()I"); global::android.widget.BaseAdapter_._getItem11014 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter_.staticClass, "getItem", "(I)Ljava/lang/Object;"); global::android.widget.BaseAdapter_._getItemId11015 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter_.staticClass, "getItemId", "(I)J"); global::android.widget.BaseAdapter_._getView11016 = @__env.GetMethodIDNoThrow(global::android.widget.BaseAdapter_.staticClass, "getView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); } } }
/* * Copyright (c) 2007-2008, Second Life Reverse Engineering Team * 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. * - Neither the name of the Second Life Reverse Engineering Team 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. */ using System; using System.Collections.Generic; namespace libsecondlife { /// <summary> /// The InternalDictionary class is used through the library for storing key/value pairs. /// It is intended to be a replacement for the generic Dictionary class and should /// be used in its place. It contains several methods for allowing access to the data from /// outside the library that are read only and thread safe. /// /// </summary> /// <typeparam name="TKey">Key <see langword="Tkey"/></typeparam> /// <typeparam name="TValue">Value <see langword="TValue"/></typeparam> public class InternalDictionary<TKey, TValue> { internal Dictionary<TKey, TValue> Dictionary; /// <summary> /// Gets the number of Key/Value pairs contained in the <seealso cref="T:InternalDictionary"/> /// </summary> public int Count { get { return Dictionary.Count; } } /// <summary> /// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class /// with the specified key/value, has the default initial capacity. /// </summary> /// <example> /// <code> /// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value. /// public InternalDictionary&lt;string, int&gt; testDict = new InternalDictionary&lt;string, int&gt;(); /// </code> /// </example> public InternalDictionary() { Dictionary = new Dictionary<TKey, TValue>(); } /// <summary> /// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class /// with the specified key/value, has its initial valies copied from the specified /// <seealso cref="T:System.Collections.Generic.Dictionary"/> /// </summary> /// <param name="dictionary"><seealso cref="T:System.Collections.Generic.Dictionary"/> /// to copy initial values from</param> /// <example> /// <code> /// // initialize a new InternalDictionary named testAvName with a UUID as the key and an string as the value. /// // populates with copied values from example KeyNameCache Dictionary. /// /// // create source dictionary /// Dictionary&lt;LLUUID, string&gt; KeyNameCache = new Dictionary&lt;LLUUID, string&gt;(); /// KeyNameCache.Add("8300f94a-7970-7810-cf2c-fc9aa6cdda24", "Jack Avatar"); /// KeyNameCache.Add("27ba1e40-13f7-0708-3e98-5819d780bd62", "Jill Avatar"); /// /// // Initialize new dictionary. /// public InternalDictionary&lt;LLUUID, string&gt; testAvName = new InternalDictionary&lt;LLUUID, string&gt;(KeyNameCache); /// </code> /// </example> public InternalDictionary(IDictionary<TKey, TValue> dictionary) { Dictionary = new Dictionary<TKey, TValue>(dictionary); } /// <summary> /// Initializes a new instance of the <seealso cref="T:libsecondlife.InternalDictionary"/> Class /// with the specified key/value, With its initial capacity specified. /// </summary> /// <param name="capacity">Initial size of dictionary</param> /// <example> /// <code> /// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value, /// // initially allocated room for 10 entries. /// public InternalDictionary&lt;string, int&gt; testDict = new InternalDictionary&lt;string, int&gt;(10); /// </code> /// </example> public InternalDictionary(int capacity) { Dictionary = new Dictionary<TKey, TValue>(capacity); } /// <summary> /// Try to get entry from <seealso cref="T:libsecondlife.InternalDictionary"/> with specified key /// </summary> /// <param name="key">Key to use for lookup</param> /// <param name="value">Value returned</param> /// <returns><see langword="true"/> if specified key exists, <see langword="false"/> if not found</returns> /// <example> /// <code> /// // find your avatar using the Simulator.ObjectsAvatars InternalDictionary: /// Avatar av; /// if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.AgentID, out av)) /// Console.WriteLine("Found Avatar {0}", av.Name); /// </code> /// <seealso cref="Simulator.ObjectsAvatars"/> /// </example> public bool TryGetValue(TKey key, out TValue value) { return Dictionary.TryGetValue(key, out value); } /// <summary> /// Finds the specified match. /// </summary> /// <param name="match">The match.</param> /// <returns>Matched value</returns> /// <example> /// <code> /// // use a delegate to find a prim in the ObjectsPrimitives InternalDictionary /// // with the ID 95683496 /// uint findID = 95683496; /// Primitive findPrim = sim.ObjectsPrimitives.Find( /// delegate(Primitive prim) { return prim.ID == findID; }); /// </code> /// </example> public TValue Find(Predicate<TValue> match) { lock (Dictionary) { foreach (TValue value in Dictionary.Values) { if (match(value)) return value; } } return default(TValue); } /// <summary>Find All items in an <seealso cref="T:InternalDictionary"/></summary> /// <param name="match">return matching items.</param> /// <returns>a <seealso cref="T:System.Collections.Generic.List"/> containing found items.</returns> /// <example> /// Find All prims within 20 meters and store them in a List /// <code> /// int radius = 20; /// List&lt;Primitive&gt; prims = Client.Network.CurrentSim.ObjectsPrimitives.FindAll( /// delegate(Primitive prim) { /// LLVector3 pos = prim.Position; /// return ((prim.ParentID == 0) &amp;&amp; (pos != LLVector3.Zero) &amp;&amp; (LLVector3.Dist(pos, location) &lt; radius)); /// } /// ); ///</code> ///</example> public List<TValue> FindAll(Predicate<TValue> match) { List<TValue> found = new List<TValue>(); lock (Dictionary) { foreach (KeyValuePair<TKey, TValue> kvp in Dictionary) { if (match(kvp.Value)) found.Add(kvp.Value); } } return found; } /// <summary>Perform an <seealso cref="T:System.Action"/> on each entry in an <seealso cref="T:libsecondlife.InternalDictionary"/></summary> /// <param name="action"><seealso cref="T:System.Action"/> to perform</param> /// <example> /// <code> /// // Iterates over the ObjectsPrimitives InternalDictionary and prints out some information. /// Client.Network.CurrentSim.ObjectsPrimitives.ForEach( /// delegate(Primitive prim) /// { /// if (prim.Text != null) /// { /// Console.WriteLine("NAME={0} ID = {1} TEXT = '{2}'", /// prim.PropertiesFamily.Name, prim.ID, prim.Text); /// } /// }); ///</code> ///</example> public void ForEach(Action<TValue> action) { lock (Dictionary) { foreach (TValue value in Dictionary.Values) { action(value); } } } /// <summary>Perform an <seealso cref="T:System.Action"/> on each key of an <seealso cref="T:libsecondlife.InternalDictionary"/></summary> /// <param name="action"><seealso cref="T:System.Action"/> to perform</param> public void ForEach(Action<TKey> action) { lock (Dictionary) { foreach (TKey key in Dictionary.Keys) { action(key); } } } /// <summary>Check if Key exists in Dictionary</summary> /// <param name="key">Key to check for</param> /// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns> public bool ContainsKey(TKey key) { lock(Dictionary) return Dictionary.ContainsKey(key); } /// <summary>Check if Value exists in Dictionary</summary> /// <param name="value">Value to check for</param> /// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns> public bool ContainsValue(TValue value) { lock(Dictionary) return Dictionary.ContainsValue(value); } /// <summary> /// Adds the specified key to the dictionary, dictionary locking is not performed, /// <see cref="SafeAdd"/> /// </summary> /// <param name="key">The key</param> /// <param name="value">The value</param> internal void Add(TKey key, TValue value) { Dictionary.Add(key, value); } /// <summary> /// Removes the specified key, dictionary locking is not performed /// </summary> /// <param name="key">The key.</param> /// <returns><see langword="true"/> if successful, <see langword="false"/> otherwise</returns> internal bool Remove(TKey key) { return Dictionary.Remove(key); } /// <summary> /// Safely add a key/value pair to the dictionary /// </summary> /// <param name="key">The key</param> /// <param name="value">The value</param> internal void SafeAdd(TKey key, TValue value) { lock (Dictionary) Dictionary.Add(key, value); } /// <summary> /// Safely Removes an item from the InternalDictionary /// </summary> /// <param name="key">The key</param> /// <returns><see langword="true"/> if successful, <see langword="false"/> otherwise</returns> internal bool SafeRemove(TKey key) { lock (Dictionary) return Dictionary.Remove(key); } /// <summary> /// Indexer for the dictionary /// </summary> /// <param name="key">The key</param> /// <returns>The value</returns> internal TValue this[TKey key] { get { return Dictionary[key]; } set { Dictionary[key] = value; } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using NUnit.Framework; using Quartz.Impl; using Quartz.Impl.Calendar; using Quartz.Impl.Matchers; using Quartz.Impl.Triggers; using Quartz.Job; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.Tests.Unit.Simpl { /// <summary> /// Unit test for RAMJobStore. These tests were submitted by Johannes Zillmann /// as part of issue QUARTZ-306. /// </summary> [TestFixture] public class RAMJobStoreTest { private IJobStore fJobStore; private JobDetailImpl fJobDetail; private SampleSignaler fSignaler; [SetUp] public void SetUp() { fJobStore = new RAMJobStore(); fSignaler = new SampleSignaler(); fJobStore.Initialize(null, fSignaler); fJobStore.SchedulerStarted(); fJobDetail = new JobDetailImpl("job1", "jobGroup1", typeof (NoOpJob)); fJobDetail.Durable = true; fJobStore.StoreJob(fJobDetail, false); } [Test] public void TestAcquireNextTrigger() { DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(200), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(50), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger1", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(100), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; Assert.AreEqual(0, fJobStore.AcquireNextTriggers(d.AddMilliseconds(10), 1, TimeSpan.Zero).Count); Assert.AreEqual(trigger2, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger1, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero).Count); // release trigger3 fJobStore.ReleaseAcquiredTrigger(trigger3); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]); } [Test] public void TestAcquireNextTriggerBatch() { DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger early = new SimpleTriggerImpl("early", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d, d.AddMilliseconds(5), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200000), d.AddMilliseconds(200005), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200100), d.AddMilliseconds(200105), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger3", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200200), d.AddMilliseconds(200205), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger4 = new SimpleTriggerImpl("trigger4", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200300), d.AddMilliseconds(200305), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger10 = new SimpleTriggerImpl("trigger10", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(500000), d.AddMilliseconds(700000), 2, TimeSpan.FromSeconds(2)); early.ComputeFirstFireTimeUtc(null); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); trigger4.ComputeFirstFireTimeUtc(null); trigger10.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(early, false); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); fJobStore.StoreTrigger(trigger4, false); fJobStore.StoreTrigger(trigger10, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; IList<IOperableTrigger> acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 4, TimeSpan.FromSeconds(1)); Assert.AreEqual(4, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); acquiredTriggers = this.fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 5, TimeSpan.FromMilliseconds(1000)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 6, TimeSpan.FromSeconds(1)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(1), 5, TimeSpan.Zero); Assert.AreEqual(2, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(250), 5, TimeSpan.FromMilliseconds(199)); Assert.AreEqual(5, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(150), 5, TimeSpan.FromMilliseconds(50L)); Assert.AreEqual(4, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); } [Test] public void TestTriggerStates() { IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(TriggerState.None, fJobStore.GetTriggerState(trigger.Key)); fJobStore.StoreTrigger(trigger, false); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); fJobStore.PauseTrigger(trigger.Key); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(trigger.Key)); fJobStore.ResumeTrigger(trigger.Key); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); fJobStore.ReleaseAcquiredTrigger(trigger); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1)).Count); } [Test] public void TestRemoveCalendarWhenTriggersPresent() { // QRTZNET-29 IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); ICalendar cal = new MonthlyCalendar(); fJobStore.StoreTrigger(trigger, false); fJobStore.StoreCalendar("cal", cal, false, true); fJobStore.RemoveCalendar("cal"); } [Test] public void TestStoreTriggerReplacesTrigger() { string jobName = "StoreTriggerReplacesTrigger"; string jobGroup = "StoreTriggerReplacesTriggerGroup"; JobDetailImpl detail = new JobDetailImpl(jobName, jobGroup, typeof (NoOpJob)); fJobStore.StoreJob(detail, false); string trName = "StoreTriggerReplacesTrigger"; string trGroup = "StoreTriggerReplacesTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.Now); tr.JobKey = new JobKey(jobName, jobGroup); tr.CalendarName = null; fJobStore.StoreTrigger(tr, false); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); tr.CalendarName = "NonExistingCalendar"; fJobStore.StoreTrigger(tr, true); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); Assert.AreEqual(tr.CalendarName, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup)).CalendarName, "StoreJob doesn't replace triggers"); bool exceptionRaised = false; try { fJobStore.StoreTrigger(tr, false); } catch (ObjectAlreadyExistsException) { exceptionRaised = true; } Assert.IsTrue(exceptionRaised, "an attempt to store duplicate trigger succeeded"); } [Test] public void PauseJobGroupPausesNewJob() { string jobName1 = "PauseJobGroupPausesNewJob"; string jobName2 = "PauseJobGroupPausesNewJob2"; string jobGroup = "PauseJobGroupPausesNewJobGroup"; JobDetailImpl detail = new JobDetailImpl(jobName1, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); fJobStore.PauseJobs(GroupMatcher<JobKey>.GroupEquals(jobGroup)); detail = new JobDetailImpl(jobName2, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); string trName = "PauseJobGroupPausesNewJobTrigger"; string trGroup = "PauseJobGroupPausesNewJobTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.UtcNow); tr.JobKey = new JobKey(jobName2, jobGroup); fJobStore.StoreTrigger(tr, false); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(tr.Key)); } [Test] public void TestRetrieveJob_NoJobFound() { RAMJobStore store = new RAMJobStore(); IJobDetail job = store.RetrieveJob(new JobKey("not", "existing")); Assert.IsNull(job); } [Test] public void TestRetrieveTrigger_NoTriggerFound() { RAMJobStore store = new RAMJobStore(); IOperableTrigger trigger = store.RetrieveTrigger(new TriggerKey("not", "existing")); Assert.IsNull(trigger); } [Test] public void testStoreAndRetrieveJobs() { RAMJobStore store = new RAMJobStore(); // Store jobs. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, false); } // Retrieve jobs. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); } } [Test] public void TestStoreAndRetrieveTriggers() { RAMJobStore store = new RAMJobStore(); // Store jobs and triggers. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, true); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).Build(); store.StoreTrigger((IOperableTrigger) trigger, true); } // Retrieve job and trigger. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); TriggerKey triggerKey = new TriggerKey("job" + i); ITrigger storedTrigger = store.RetrieveTrigger(triggerKey); Assert.AreEqual(triggerKey, storedTrigger.Key); } } [Test] public void TestAcquireTriggers() { ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); RAMJobStore store = new RAMJobStore(); store.Initialize(loadHelper, schedSignaler); // Setup: Store jobs and triggers. DateTime startTime0 = DateTime.UtcNow.AddMinutes(1).ToUniversalTime(); // a min from now. for (int i = 0; i < 10; i++) { DateTime startTime = startTime0.AddMinutes(i*1); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire one trigger at a time for (int i = 0; i < 10; i++) { DateTimeOffset noLaterThan = startTime0.AddMinutes(i); int maxCount = 1; TimeSpan timeWindow = TimeSpan.Zero; IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(1, triggers.Count); Assert.AreEqual("job" + i, triggers[0].Key.Name); // Let's remove the trigger now. store.RemoveJob(triggers[0].JobKey); } } [Test] public void TestAcquireTriggersInBatch() { ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); RAMJobStore store = new RAMJobStore(); store.Initialize(loadHelper, schedSignaler); // Setup: Store jobs and triggers. DateTimeOffset startTime0 = DateTimeOffset.UtcNow.AddMinutes(1); // a min from now. for (int i = 0; i < 10; i++) { DateTimeOffset startTime = startTime0.AddMinutes(i); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire batch of triggers at a time DateTimeOffset noLaterThan = startTime0.AddMinutes(10); int maxCount = 7; TimeSpan timeWindow = TimeSpan.FromMinutes(8); IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(7, triggers.Count); for (int i = 0; i < 7; i++) { Assert.AreEqual("job" + i, triggers[i].Key.Name); } } public class SampleSignaler : ISchedulerSignaler { internal int fMisfireCount = 0; public void NotifyTriggerListenersMisfired(ITrigger trigger) { fMisfireCount++; } public void NotifySchedulerListenersFinalized(ITrigger trigger) { } public void SignalSchedulingChange(DateTimeOffset? candidateNewNextFireTimeUtc) { } public void NotifySchedulerListenersError(string message, SchedulerException jpe) { } public void NotifySchedulerListenersJobDeleted(JobKey jobKey) { } } } }
#region License //============================================================================= // Velox.DB - Portable .NET ORM // // Copyright (c) 2015 Philippe Leybaert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //============================================================================= #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using Velox.DB.Core; namespace Velox.DB { public class MemoryDataProvider : IDataProvider { private class CompositeKey { private readonly Dictionary<string,object> _keyValues; public CompositeKey(Dictionary<string,object> keyValues) { _keyValues = keyValues; } public CompositeKey(OrmSchema schema, SerializedEntity o) { _keyValues = schema.PrimaryKeys.ToDictionary(pk => pk.MappedName, pk => o[pk.MappedName]); } public override int GetHashCode() { return _keyValues.Aggregate(0, (current, t) => current ^ t.Value.GetHashCode() ^ t.Key.GetHashCode()); } public override bool Equals(object obj) { var other = (CompositeKey) obj; return _keyValues.All(pk => other._keyValues.ContainsKey(pk.Key) && pk.Value.Equals(other._keyValues[pk.Key])); } } private class StorageBucket { private readonly List<Dictionary<string, object>> _objects = new List<Dictionary<string, object>>(); private readonly Dictionary<CompositeKey,Dictionary<string,object>> _indexedObjects = new Dictionary<CompositeKey, Dictionary<string, object>>(); private readonly SafeDictionary<string, long> _autoIncrementCounters = new SafeDictionary<string, long>(); private long NextIncrementCounter(string fieldName) { var counter = _autoIncrementCounters[fieldName] + 1; _autoIncrementCounters[fieldName] = counter; return counter; } private void Purge() { _autoIncrementCounters.Clear(); _objects.Clear(); } public BucketAccessor Accessor() { return new BucketAccessor(this); } public class BucketAccessor : IDisposable { private readonly StorageBucket _bucket; public BucketAccessor(StorageBucket bucket) { _bucket = bucket; Monitor.Enter(_bucket); } public void Dispose() { Monitor.Exit(_bucket); } public long NextIncrementCounter(string fieldName) { return _bucket.NextIncrementCounter(fieldName); } public void Purge() { _bucket.Purge(); } public List<Dictionary<string, object>> Objects => _bucket._objects; public Dictionary<CompositeKey, Dictionary<string, object>> IndexedObjects => _bucket._indexedObjects; } } private readonly SafeDictionary<OrmSchema,StorageBucket> _buckets = new SafeDictionary<OrmSchema, StorageBucket>(); private StorageBucket.BucketAccessor GetBucket(OrmSchema schema) { return (_buckets[schema] ?? (_buckets[schema] = new StorageBucket())).Accessor(); } public object GetScalar(Aggregate aggregate, INativeQuerySpec nativeQuerySpec, OrmSchema schema) { throw new NotSupportedException(); } public IEnumerable<SerializedEntity> GetObjects(INativeQuerySpec querySpec, OrmSchema schema) { if (querySpec != null) throw new NotSupportedException(); using (var bucket = GetBucket(schema)) { return from o in bucket.Objects select new SerializedEntity(o); } } public IEnumerable<SerializedEntity> GetObjectsWithPrefetch(INativeQuerySpec filter, OrmSchema schema, IEnumerable<OrmSchema.Relation> prefetchRelations, out IEnumerable<Dictionary<OrmSchema.Relation, SerializedEntity>> relatedEntities) { throw new NotSupportedException(); } public ObjectWriteResult WriteObject(SerializedEntity o, bool createNew, OrmSchema schema) { var result = new ObjectWriteResult(); using (var bucket = GetBucket(schema)) { if (createNew) { foreach (var incrementKey in schema.IncrementKeys.Where(incrementKey => o[incrementKey.MappedName].Convert<long>() == 0)) { o[incrementKey.MappedName] = bucket.NextIncrementCounter(incrementKey.FieldName).Convert(incrementKey.FieldType); result.OriginalUpdated = true; } var storedObject = o.AsDictionary(); bucket.Objects.Add(storedObject); bucket.IndexedObjects[new CompositeKey(schema,o)] = storedObject; result.Added = true; result.Success = true; } else { if (schema.PrimaryKeys.Length > 0) { for (int i = 0; i < bucket.Objects.Count; i++) { if (schema.PrimaryKeys.All(primaryKey => Equals(bucket.Objects[i][primaryKey.MappedName], o[primaryKey.MappedName]))) { var compositeKey = new CompositeKey(schema, o); var storedObject = o.AsDictionary(); bucket.Objects[i] = storedObject; bucket.IndexedObjects[compositeKey] = storedObject; result.Success = true; break; } } } else { result.Success = false; } } } return result; } public SerializedEntity ReadObject(Dictionary<string,object> keys, OrmSchema schema) { using (var bucket = GetBucket(schema)) { var compositeKey = new CompositeKey(keys); if (!bucket.IndexedObjects.ContainsKey(compositeKey)) return null; var storedObject = bucket.IndexedObjects[compositeKey]; return new SerializedEntity(storedObject); } } public bool DeleteObject(SerializedEntity o, OrmSchema schema) { using (var bucket = GetBucket(schema)) { for (int i = 0; i < bucket.Objects.Count; i++) { if (schema.PrimaryKeys.All(primaryKey => Equals(bucket.Objects[i][primaryKey.MappedName], o[primaryKey.MappedName]))) { bucket.IndexedObjects.Remove(bucket.IndexedObjects.First(kv => kv.Value == bucket.Objects[i]).Key); bucket.Objects.RemoveAt(i); return true; } } } return false; } public bool DeleteObjects(INativeQuerySpec filter, OrmSchema schema) { throw new NotSupportedException(); } public QuerySpec CreateQuerySpec(FilterSpec filter, ScalarSpec expression, SortOrderSpec sortOrder, int? skip, int? take, OrmSchema schema) { throw new NotSupportedException(); } public bool SupportsQueryTranslation(QueryExpression expression) { return false; } public bool SupportsRelationPrefetch => false; public bool CreateOrUpdateTable(OrmSchema schema, bool recreateTable, bool recreateIndexes) { return true; // NOP } public int ExecuteSql(string sql, QueryParameterCollection parameters) { throw new NotSupportedException(); } public IEnumerable<SerializedEntity> Query(string sql, QueryParameterCollection parameters) { throw new NotSupportedException(); } public IEnumerable<object> QueryScalar(string sql, QueryParameterCollection parameters) { throw new NotSupportedException(); } public void Purge(OrmSchema schema) { using (var bucket = GetBucket(schema)) { bucket.Purge(); } } public void Dispose() { _buckets.Clear(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using Ode.NET; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; using log4net; namespace OpenSim.Region.Physics.OdePlugin { /// <summary> /// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves. /// </summary> public enum dParam : int { LowStop = 0, HiStop = 1, Vel = 2, FMax = 3, FudgeFactor = 4, Bounce = 5, CFM = 6, StopERP = 7, StopCFM = 8, LoStop2 = 256, HiStop2 = 257, Vel2 = 258, FMax2 = 259, StopERP2 = 7 + 256, StopCFM2 = 8 + 256, LoStop3 = 512, HiStop3 = 513, Vel3 = 514, FMax3 = 515, StopERP3 = 7 + 512, StopCFM3 = 8 + 512 } public class OdeCharacter : PhysicsActor { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Vector3 _position; private d.Vector3 _zeroPosition; // private d.Matrix3 m_StandUpRotation; private bool _zeroFlag = false; private bool m_lastUpdateSent = false; private Vector3 _velocity; private Vector3 _target_velocity; private Vector3 _acceleration; private Vector3 m_rotationalVelocity; private float m_mass = 80f; public float m_density = 60f; private bool m_pidControllerActive = true; public float PID_D = 800.0f; public float PID_P = 900.0f; //private static float POSTURE_SERVO = 10000.0f; public float CAPSULE_RADIUS = 0.37f; public float CAPSULE_LENGTH = 2.140599f; public float m_tensor = 3800000f; public float heightFudgeFactor = 0.52f; public float walkDivisor = 1.3f; public float runDivisor = 0.8f; private bool flying = false; private bool m_iscolliding = false; private bool m_iscollidingGround = false; private bool m_wascolliding = false; private bool m_wascollidingGround = false; private bool m_iscollidingObj = false; private bool m_alwaysRun = false; private bool m_hackSentFall = false; private bool m_hackSentFly = false; private int m_requestedUpdateFrequency = 0; private Vector3 m_taintPosition = Vector3.Zero; public uint m_localID = 0; public bool m_returnCollisions = false; // taints and their non-tainted counterparts public bool m_isPhysical = false; // the current physical status public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing) public float MinimumGroundFlightOffset = 3f; private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes. private float m_tiltMagnitudeWhenProjectedOnXYPlane = 0.1131371f; // used to introduce a fixed tilt because a straight-up capsule falls through terrain, probably a bug in terrain collider private float m_buoyancy = 0f; // private CollisionLocker ode; private string m_name = String.Empty; private bool[] m_colliderarr = new bool[11]; private bool[] m_colliderGroundarr = new bool[11]; // Default we're a Character private CollisionCategories m_collisionCategories = (CollisionCategories.Character); // Default, Collide with Other Geometries, spaces, bodies and characters. private CollisionCategories m_collisionFlags = (CollisionCategories.Geom | CollisionCategories.Space | CollisionCategories.Body | CollisionCategories.Character | CollisionCategories.Land); public IntPtr Body = IntPtr.Zero; private OdeScene _parent_scene; public IntPtr Shell = IntPtr.Zero; public IntPtr Amotor = IntPtr.Zero; public d.Mass ShellMass; public bool collidelock = false; public int m_eventsubscription = 0; private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate(); // unique UUID of this character object public UUID m_uuid; public bool bad = false; public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, CollisionLocker dode, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor) { m_uuid = UUID.Random(); if (pos.IsFinite()) { if (pos.Z > 9999999f) { pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5; } if (pos.Z < -90000f) { pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5; } _position = pos; m_taintPosition.X = pos.X; m_taintPosition.Y = pos.Y; m_taintPosition.Z = pos.Z; } else { _position = new Vector3(((float)_parent_scene.WorldExtents.X * 0.5f), ((float)_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f); m_taintPosition.X = _position.X; m_taintPosition.Y = _position.Y; m_taintPosition.Z = _position.Z; m_log.Warn("[PHYSICS]: Got NaN Position on Character Create"); } _parent_scene = parent_scene; PID_D = pid_d; PID_P = pid_p; CAPSULE_RADIUS = capsule_radius; m_tensor = tensor; m_density = density; heightFudgeFactor = height_fudge_factor; walkDivisor = walk_divisor; runDivisor = rundivisor; // m_StandUpRotation = // new d.Matrix3(0.5f, 0.7071068f, 0.5f, -0.7071068f, 0f, 0.7071068f, 0.5f, -0.7071068f, // 0.5f); for (int i = 0; i < 11; i++) { m_colliderarr[i] = false; } CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f; //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString()); m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH; m_isPhysical = false; // current status: no ODE information exists m_tainted_isPhysical = true; // new tainted status: need to create ODE information _parent_scene.AddPhysicsActorTaint(this); m_name = avName; } public override int PhysicsActorType { get { return (int) ActorTypes.Agent; } set { return; } } /// <summary> /// If this is set, the avatar will move faster /// </summary> public override bool SetAlwaysRun { get { return m_alwaysRun; } set { m_alwaysRun = value; } } public override uint LocalID { set { m_localID = value; } } public override bool Grabbed { set { return; } } public override bool Selected { set { return; } } public override float Buoyancy { get { return m_buoyancy; } set { m_buoyancy = value; } } public override bool FloatOnWater { set { return; } } public override bool IsPhysical { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool Flying { get { return flying; } set { flying = value; } } /// <summary> /// Returns if the avatar is colliding in general. /// This includes the ground and objects and avatar. /// </summary> public override bool IsColliding { get { return m_iscolliding; } set { int i; int truecount = 0; int falsecount = 0; if (m_colliderarr.Length >= 10) { for (i = 0; i < 10; i++) { m_colliderarr[i] = m_colliderarr[i + 1]; } } m_colliderarr[10] = value; for (i = 0; i < 11; i++) { if (m_colliderarr[i]) { truecount++; } else { falsecount++; } } // Equal truecounts and false counts means we're colliding with something. if (falsecount > 1.2*truecount) { m_iscolliding = false; } else { m_iscolliding = true; } if (m_wascolliding != m_iscolliding) { //base.SendCollisionUpdate(new CollisionEventUpdate()); } m_wascolliding = m_iscolliding; } } /// <summary> /// Returns if an avatar is colliding with the ground /// </summary> public override bool CollidingGround { get { return m_iscollidingGround; } set { // Collisions against the ground are not really reliable // So, to get a consistant value we have to average the current result over time // Currently we use 1 second = 10 calls to this. int i; int truecount = 0; int falsecount = 0; if (m_colliderGroundarr.Length >= 10) { for (i = 0; i < 10; i++) { m_colliderGroundarr[i] = m_colliderGroundarr[i + 1]; } } m_colliderGroundarr[10] = value; for (i = 0; i < 11; i++) { if (m_colliderGroundarr[i]) { truecount++; } else { falsecount++; } } // Equal truecounts and false counts means we're colliding with something. if (falsecount > 1.2*truecount) { m_iscollidingGround = false; } else { m_iscollidingGround = true; } if (m_wascollidingGround != m_iscollidingGround) { //base.SendCollisionUpdate(new CollisionEventUpdate()); } m_wascollidingGround = m_iscollidingGround; } } /// <summary> /// Returns if the avatar is colliding with an object /// </summary> public override bool CollidingObj { get { return m_iscollidingObj; } set { m_iscollidingObj = value; if (value) m_pidControllerActive = false; else m_pidControllerActive = true; } } /// <summary> /// turn the PID controller on or off. /// The PID Controller will turn on all by itself in many situations /// </summary> /// <param name="status"></param> public void SetPidStatus(bool status) { m_pidControllerActive = status; } public override bool Stopped { get { return _zeroFlag; } } /// <summary> /// This 'puts' an avatar somewhere in the physics space. /// Not really a good choice unless you 'know' it's a good /// spot otherwise you're likely to orbit the avatar. /// </summary> public override Vector3 Position { get { return _position; } set { if (Body == IntPtr.Zero || Shell == IntPtr.Zero) { if (value.IsFinite()) { if (value.Z > 9999999f) { value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5; } if (value.Z < -90000f) { value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5; } _position.X = value.X; _position.Y = value.Y; _position.Z = value.Z; m_taintPosition.X = value.X; m_taintPosition.Y = value.Y; m_taintPosition.Z = value.Z; _parent_scene.AddPhysicsActorTaint(this); } else { m_log.Warn("[PHYSICS]: Got a NaN Position from Scene on a Character"); } } } } public override Vector3 RotationalVelocity { get { return m_rotationalVelocity; } set { m_rotationalVelocity = value; } } /// <summary> /// This property sets the height of the avatar only. We use the height to make sure the avatar stands up straight /// and use it to offset landings properly /// </summary> public override Vector3 Size { get { return new Vector3(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); } set { if (value.IsFinite()) { m_pidControllerActive = true; Vector3 SetSize = value; m_tainted_CAPSULE_LENGTH = (SetSize.Z*1.15f) - CAPSULE_RADIUS*2.0f; //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString()); Velocity = Vector3.Zero; _parent_scene.AddPhysicsActorTaint(this); } else { m_log.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character"); } } } private void AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3 movementVector) { movementVector.Z = 0f; float magnitude = (float)Math.Sqrt((double)(movementVector.X * movementVector.X + movementVector.Y * movementVector.Y)); if (magnitude < 0.1f) return; // normalize the velocity vector float invMagnitude = 1.0f / magnitude; movementVector.X *= invMagnitude; movementVector.Y *= invMagnitude; // if we change the capsule heading too often, the capsule can fall down // therefore we snap movement vector to just 1 of 4 predefined directions (ne, nw, se, sw), // meaning only 4 possible capsule tilt orientations if (movementVector.X > 0) { // east if (movementVector.Y > 0) { // northeast movementVector.X = (float)Math.Sqrt(2.0); movementVector.Y = (float)Math.Sqrt(2.0); } else { // southeast movementVector.X = (float)Math.Sqrt(2.0); movementVector.Y = -(float)Math.Sqrt(2.0); } } else { // west if (movementVector.Y > 0) { // northwest movementVector.X = -(float)Math.Sqrt(2.0); movementVector.Y = (float)Math.Sqrt(2.0); } else { // southwest movementVector.X = -(float)Math.Sqrt(2.0); movementVector.Y = -(float)Math.Sqrt(2.0); } } // movementVector.Z is zero // calculate tilt components based on desired amount of tilt and current (snapped) heading. // the "-" sign is to force the tilt to be OPPOSITE the direction of movement. float xTiltComponent = -movementVector.X * m_tiltMagnitudeWhenProjectedOnXYPlane; float yTiltComponent = -movementVector.Y * m_tiltMagnitudeWhenProjectedOnXYPlane; //m_log.Debug("[PHYSICS] changing avatar tilt"); d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, xTiltComponent); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, xTiltComponent); // must be same as lowstop, else a different, spurious tilt is introduced d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, yTiltComponent); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, yTiltComponent); // same as lowstop d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, 0f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop } /// <summary> /// This creates the Avatar's physical Surrogate at the position supplied /// </summary> /// <param name="npositionX"></param> /// <param name="npositionY"></param> /// <param name="npositionZ"></param> // WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access // to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only // place that is safe to call this routine AvatarGeomAndBodyCreation. private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ, float tensor) { //CAPSULE_LENGTH = -5; //CAPSULE_RADIUS = -5; int dAMotorEuler = 1; _parent_scene.waitForSpaceUnlock(_parent_scene.space); if (CAPSULE_LENGTH <= 0) { m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!"); CAPSULE_LENGTH = 0.01f; } if (CAPSULE_RADIUS <= 0) { m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!"); CAPSULE_RADIUS = 0.01f; } Shell = d.CreateCapsule(_parent_scene.space, CAPSULE_RADIUS, CAPSULE_LENGTH); d.GeomSetCategoryBits(Shell, (int)m_collisionCategories); d.GeomSetCollideBits(Shell, (int)m_collisionFlags); d.MassSetCapsuleTotal(out ShellMass, m_mass, 2, CAPSULE_RADIUS, CAPSULE_LENGTH); Body = d.BodyCreate(_parent_scene.world); d.BodySetPosition(Body, npositionX, npositionY, npositionZ); _position.X = npositionX; _position.Y = npositionY; _position.Z = npositionZ; m_taintPosition.X = npositionX; m_taintPosition.Y = npositionY; m_taintPosition.Z = npositionZ; d.BodySetMass(Body, ref ShellMass); d.Matrix3 m_caprot; // 90 Stand up on the cap of the capped cyllinder if (_parent_scene.IsAvCapsuleTilted) { d.RFromAxisAndAngle(out m_caprot, 1, 0, 1, (float)(Math.PI / 2)); } else { d.RFromAxisAndAngle(out m_caprot, 0, 0, 1, (float)(Math.PI / 2)); } d.GeomSetRotation(Shell, ref m_caprot); d.BodySetRotation(Body, ref m_caprot); d.GeomSetBody(Shell, Body); // The purpose of the AMotor here is to keep the avatar's physical // surrogate from rotating while moving Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero); d.JointAttach(Amotor, Body, IntPtr.Zero); d.JointSetAMotorMode(Amotor, dAMotorEuler); d.JointSetAMotorNumAxes(Amotor, 3); d.JointSetAMotorAxis(Amotor, 0, 0, 1, 0, 0); d.JointSetAMotorAxis(Amotor, 1, 0, 0, 1, 0); d.JointSetAMotorAxis(Amotor, 2, 0, 0, 0, 1); d.JointSetAMotorAngle(Amotor, 0, 0); d.JointSetAMotorAngle(Amotor, 1, 0); d.JointSetAMotorAngle(Amotor, 2, 0); // These lowstops and high stops are effectively (no wiggle room) if (_parent_scene.IsAvCapsuleTilted) { d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.000000000001f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.000000000001f); } else { #region Documentation of capsule motor LowStop and HighStop parameters // Intentionally introduce some tilt into the capsule by setting // the motor stops to small epsilon values. This small tilt prevents // the capsule from falling into the terrain; a straight-up capsule // (with -0..0 motor stops) falls into the terrain for reasons yet // to be comprehended in their entirety. #endregion AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3.Zero); d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, 0.08f); d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f); d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, 0.08f); d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.08f); // must be same as lowstop, else a different, spurious tilt is introduced d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.08f); // same as lowstop } // Fudge factor is 1f by default, we're setting it to 0. We don't want it to Fudge or the // capped cyllinder will fall over d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f); d.JointSetAMotorParam(Amotor, (int)dParam.FMax, tensor); //d.Matrix3 bodyrotation = d.BodyGetRotation(Body); //d.QfromR( //d.Matrix3 checkrotation = new d.Matrix3(0.7071068,0.5, -0.7071068, // //m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22); //standupStraight(); } // /// <summary> /// Uses the capped cyllinder volume formula to calculate the avatar's mass. /// This may be used in calculations in the scene/scenepresence /// </summary> public override float Mass { get { float AVvolume = (float) (Math.PI*Math.Pow(CAPSULE_RADIUS, 2)*CAPSULE_LENGTH); return m_density*AVvolume; } } public override void link(PhysicsActor obj) { } public override void delink() { } public override void LockAngularMotion(Vector3 axis) { } // This code is very useful. Written by DanX0r. We're just not using it right now. // Commented out to prevent a warning. // // private void standupStraight() // { // // The purpose of this routine here is to quickly stabilize the Body while it's popped up in the air. // // The amotor needs a few seconds to stabilize so without it, the avatar shoots up sky high when you // // change appearance and when you enter the simulator // // After this routine is done, the amotor stabilizes much quicker // d.Vector3 feet; // d.Vector3 head; // d.BodyGetRelPointPos(Body, 0.0f, 0.0f, -1.0f, out feet); // d.BodyGetRelPointPos(Body, 0.0f, 0.0f, 1.0f, out head); // float posture = head.Z - feet.Z; // // restoring force proportional to lack of posture: // float servo = (2.5f - posture) * POSTURE_SERVO; // d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, servo, 0.0f, 0.0f, 1.0f); // d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, -servo, 0.0f, 0.0f, -1.0f); // //d.Matrix3 bodyrotation = d.BodyGetRotation(Body); // //m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22); // } public override Vector3 Force { get { return _target_velocity; } set { return; } } public override int VehicleType { get { return 0; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, Vector3 value) { } public override void VehicleRotationParam(int param, Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } public override void SetVolumeDetect(int param) { } public override Vector3 CenterOfMass { get { return Vector3.Zero; } } public override Vector3 GeometricCenter { get { return Vector3.Zero; } } public override PrimitiveBaseShape Shape { set { return; } } public override Vector3 Velocity { get { // There's a problem with Vector3.Zero! Don't Use it Here! if (_zeroFlag) return Vector3.Zero; m_lastUpdateSent = false; return _velocity; } set { if (value.IsFinite()) { m_pidControllerActive = true; _target_velocity = value; } else { m_log.Warn("[PHYSICS]: Got a NaN velocity from Scene in a Character"); } } } public override Vector3 Torque { get { return Vector3.Zero; } set { return; } } public override float CollisionScore { get { return 0f; } set { } } public override bool Kinematic { get { return false; } set { } } public override Quaternion Orientation { get { return Quaternion.Identity; } set { //Matrix3 or = Orientation.ToRotationMatrix(); //d.Matrix3 ord = new d.Matrix3(or.m00, or.m10, or.m20, or.m01, or.m11, or.m21, or.m02, or.m12, or.m22); //d.BodySetRotation(Body, ref ord); } } public override Vector3 Acceleration { get { return _acceleration; } } public void SetAcceleration(Vector3 accel) { m_pidControllerActive = true; _acceleration = accel; } /// <summary> /// Adds the force supplied to the Target Velocity /// The PID controller takes this target velocity and tries to make it a reality /// </summary> /// <param name="force"></param> public override void AddForce(Vector3 force, bool pushforce) { if (force.IsFinite()) { if (pushforce) { m_pidControllerActive = false; force *= 100f; doForce(force); // If uncommented, things get pushed off world // // m_log.Debug("Push!"); // _target_velocity.X += force.X; // _target_velocity.Y += force.Y; // _target_velocity.Z += force.Z; } else { m_pidControllerActive = true; _target_velocity.X += force.X; _target_velocity.Y += force.Y; _target_velocity.Z += force.Z; } } else { m_log.Warn("[PHYSICS]: Got a NaN force applied to a Character"); } //m_lastUpdateSent = false; } public override void AddAngularForce(Vector3 force, bool pushforce) { } /// <summary> /// After all of the forces add up with 'add force' we apply them with doForce /// </summary> /// <param name="force"></param> public void doForce(Vector3 force) { if (!collidelock) { d.BodyAddForce(Body, force.X, force.Y, force.Z); //d.BodySetRotation(Body, ref m_StandUpRotation); //standupStraight(); } } public override void SetMomentum(Vector3 momentum) { } /// <summary> /// Called from Simulate /// This is the avatar's movement control + PID Controller /// </summary> /// <param name="timeStep"></param> public void Move(float timeStep, List<OdeCharacter> defects) { // no lock; for now it's only called from within Simulate() // If the PID Controller isn't active then we set our force // calculating base velocity to the current position if (Body == IntPtr.Zero) return; if (m_pidControllerActive == false) { _zeroPosition = d.BodyGetPosition(Body); } //PidStatus = true; d.Vector3 localpos = d.BodyGetPosition(Body); Vector3 localPos = new Vector3(localpos.X, localpos.Y, localpos.Z); if (!localPos.IsFinite()) { m_log.Warn("[PHYSICS]: Avatar Position is non-finite!"); defects.Add(this); // _parent_scene.RemoveCharacter(this); // destroy avatar capsule and related ODE data if (Amotor != IntPtr.Zero) { // Kill the Amotor d.JointDestroy(Amotor); Amotor = IntPtr.Zero; } //kill the Geometry _parent_scene.waitForSpaceUnlock(_parent_scene.space); if (Body != IntPtr.Zero) { //kill the body d.BodyDestroy(Body); Body = IntPtr.Zero; } if (Shell != IntPtr.Zero) { d.GeomDestroy(Shell); _parent_scene.geom_name_map.Remove(Shell); Shell = IntPtr.Zero; } return; } Vector3 vec = Vector3.Zero; d.Vector3 vel = d.BodyGetLinearVel(Body); float movementdivisor = 1f; if (!m_alwaysRun) { movementdivisor = walkDivisor; } else { movementdivisor = runDivisor; } // if velocity is zero, use position control; otherwise, velocity control if (_target_velocity.X == 0.0f && _target_velocity.Y == 0.0f && _target_velocity.Z == 0.0f && m_iscolliding) { // keep track of where we stopped. No more slippin' & slidin' if (!_zeroFlag) { _zeroFlag = true; _zeroPosition = d.BodyGetPosition(Body); } if (m_pidControllerActive) { // We only want to deactivate the PID Controller if we think we want to have our surrogate // react to the physics scene by moving it's position. // Avatar to Avatar collisions // Prim to avatar collisions d.Vector3 pos = d.BodyGetPosition(Body); vec.X = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2); vec.Y = (_target_velocity.Y - vel.Y)*(PID_D) + (_zeroPosition.Y - pos.Y)* (PID_P * 2); if (flying) { vec.Z = (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P; } } //PidStatus = true; } else { m_pidControllerActive = true; _zeroFlag = false; if (m_iscolliding && !flying) { // We're standing on something vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D); vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D); } else if (m_iscolliding && flying) { // We're flying and colliding with something vec.X = ((_target_velocity.X/movementdivisor) - vel.X)*(PID_D / 16); vec.Y = ((_target_velocity.Y/movementdivisor) - vel.Y)*(PID_D / 16); } else if (!m_iscolliding && flying) { // we're in mid air suspended vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D/6); vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D/6); } if (m_iscolliding && !flying && _target_velocity.Z > 0.0f) { // We're colliding with something and we're not flying but we're moving // This means we're walking or running. d.Vector3 pos = d.BodyGetPosition(Body); vec.Z = (_target_velocity.Z - vel.Z)*PID_D + (_zeroPosition.Z - pos.Z)*PID_P; if (_target_velocity.X > 0) { vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D; } if (_target_velocity.Y > 0) { vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D; } } else if (!m_iscolliding && !flying) { // we're not colliding and we're not flying so that means we're falling! // m_iscolliding includes collisions with the ground. // d.Vector3 pos = d.BodyGetPosition(Body); if (_target_velocity.X > 0) { vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D; } if (_target_velocity.Y > 0) { vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D; } } if (flying) { vec.Z = (_target_velocity.Z - vel.Z) * (PID_D); } } if (flying) { vec.Z += ((-1 * _parent_scene.gravityz)*m_mass); //Added for auto fly height. Kitto Flora //d.Vector3 pos = d.BodyGetPosition(Body); float target_altitude = _parent_scene.GetTerrainHeightAtXY(_position.X, _position.Y) + MinimumGroundFlightOffset; if (_position.Z < target_altitude) { vec.Z += (target_altitude - _position.Z) * PID_P * 5.0f; } // end add Kitto Flora } if (vec.IsFinite()) { doForce(vec); if (!_zeroFlag) { AlignAvatarTiltWithCurrentDirectionOfMovement(vec); } } else { m_log.Warn("[PHYSICS]: Got a NaN force vector in Move()"); m_log.Warn("[PHYSICS]: Avatar Position is non-finite!"); defects.Add(this); // _parent_scene.RemoveCharacter(this); // destroy avatar capsule and related ODE data if (Amotor != IntPtr.Zero) { // Kill the Amotor d.JointDestroy(Amotor); Amotor = IntPtr.Zero; } //kill the Geometry _parent_scene.waitForSpaceUnlock(_parent_scene.space); if (Body != IntPtr.Zero) { //kill the body d.BodyDestroy(Body); Body = IntPtr.Zero; } if (Shell != IntPtr.Zero) { d.GeomDestroy(Shell); _parent_scene.geom_name_map.Remove(Shell); Shell = IntPtr.Zero; } } } /// <summary> /// Updates the reported position and velocity. This essentially sends the data up to ScenePresence. /// </summary> public void UpdatePositionAndVelocity() { // no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit! d.Vector3 vec; try { vec = d.BodyGetPosition(Body); } catch (NullReferenceException) { bad = true; _parent_scene.BadCharacter(this); vec = new d.Vector3(_position.X, _position.Y, _position.Z); base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem! m_log.WarnFormat("[ODEPLUGIN]: Avatar Null reference for Avatar {0}, physical actor {1}", m_name, m_uuid); } // kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!) if (vec.X < 0.0f) vec.X = 0.0f; if (vec.Y < 0.0f) vec.Y = 0.0f; if (vec.X > (int)_parent_scene.WorldExtents.X - 0.05f) vec.X = (int)_parent_scene.WorldExtents.X - 0.05f; if (vec.Y > (int)_parent_scene.WorldExtents.Y - 0.05f) vec.Y = (int)_parent_scene.WorldExtents.Y - 0.05f; _position.X = vec.X; _position.Y = vec.Y; _position.Z = vec.Z; // Did we move last? = zeroflag // This helps keep us from sliding all over if (_zeroFlag) { _velocity.X = 0.0f; _velocity.Y = 0.0f; _velocity.Z = 0.0f; // Did we send out the 'stopped' message? if (!m_lastUpdateSent) { m_lastUpdateSent = true; //base.RequestPhysicsterseUpdate(); } } else { m_lastUpdateSent = false; try { vec = d.BodyGetLinearVel(Body); } catch (NullReferenceException) { vec.X = _velocity.X; vec.Y = _velocity.Y; vec.Z = _velocity.Z; } _velocity.X = (vec.X); _velocity.Y = (vec.Y); _velocity.Z = (vec.Z); if (_velocity.Z < -6 && !m_hackSentFall) { m_hackSentFall = true; m_pidControllerActive = false; } else if (flying && !m_hackSentFly) { //m_hackSentFly = true; //base.SendCollisionUpdate(new CollisionEventUpdate()); } else { m_hackSentFly = false; m_hackSentFall = false; } } } /// <summary> /// Cleanup the things we use in the scene. /// </summary> public void Destroy() { m_tainted_isPhysical = false; _parent_scene.AddPhysicsActorTaint(this); } public override void CrossingFailure() { } public override Vector3 PIDTarget { set { return; } } public override bool PIDActive { set { return; } } public override float PIDTau { set { return; } } public override float PIDHoverHeight { set { return; } } public override bool PIDHoverActive { set { return; } } public override PIDHoverType PIDHoverType { set { return; } } public override float PIDHoverTau { set { return; } } public override Quaternion APIDTarget{ set { return; } } public override bool APIDActive{ set { return; } } public override float APIDStrength{ set { return; } } public override float APIDDamping{ set { return; } } public override void SubscribeEvents(int ms) { m_requestedUpdateFrequency = ms; m_eventsubscription = ms; _parent_scene.addCollisionEventReporting(this); } public override void UnSubscribeEvents() { _parent_scene.remCollisionEventReporting(this); m_requestedUpdateFrequency = 0; m_eventsubscription = 0; } public void AddCollisionEvent(uint CollidedWith, ContactPoint contact) { if (m_eventsubscription > 0) { CollisionEventsThisFrame.addCollider(CollidedWith, contact); } } public void SendCollisions() { if (m_eventsubscription > m_requestedUpdateFrequency) { if (CollisionEventsThisFrame != null) { base.SendCollisionUpdate(CollisionEventsThisFrame); } CollisionEventsThisFrame = new CollisionEventUpdate(); m_eventsubscription = 0; } } public override bool SubscribedEvents() { if (m_eventsubscription > 0) return true; return false; } public void ProcessTaints(float timestep) { if (m_tainted_isPhysical != m_isPhysical) { if (m_tainted_isPhysical) { // Create avatar capsule and related ODE data if (!(Shell == IntPtr.Zero && Body == IntPtr.Zero && Amotor == IntPtr.Zero)) { m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - " + (Shell!=IntPtr.Zero ? "Shell ":"") + (Body!=IntPtr.Zero ? "Body ":"") + (Amotor!=IntPtr.Zero ? "Amotor ":"")); } AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z, m_tensor); _parent_scene.geom_name_map[Shell] = m_name; _parent_scene.actor_name_map[Shell] = (PhysicsActor)this; _parent_scene.AddCharacter(this); } else { _parent_scene.RemoveCharacter(this); // destroy avatar capsule and related ODE data if (Amotor != IntPtr.Zero) { // Kill the Amotor d.JointDestroy(Amotor); Amotor = IntPtr.Zero; } //kill the Geometry _parent_scene.waitForSpaceUnlock(_parent_scene.space); if (Body != IntPtr.Zero) { //kill the body d.BodyDestroy(Body); Body = IntPtr.Zero; } if (Shell != IntPtr.Zero) { d.GeomDestroy(Shell); _parent_scene.geom_name_map.Remove(Shell); Shell = IntPtr.Zero; } } m_isPhysical = m_tainted_isPhysical; } if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH) { if (Shell != IntPtr.Zero && Body != IntPtr.Zero && Amotor != IntPtr.Zero) { m_pidControllerActive = true; // no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate() d.JointDestroy(Amotor); float prevCapsule = CAPSULE_LENGTH; CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH; //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString()); d.BodyDestroy(Body); d.GeomDestroy(Shell); AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2), m_tensor); Velocity = Vector3.Zero; _parent_scene.geom_name_map[Shell] = m_name; _parent_scene.actor_name_map[Shell] = (PhysicsActor)this; } else { m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - " + (Shell==IntPtr.Zero ? "Shell ":"") + (Body==IntPtr.Zero ? "Body ":"") + (Amotor==IntPtr.Zero ? "Amotor ":"")); } } if (!m_taintPosition.ApproxEquals(_position, 0.05f)) { if (Body != IntPtr.Zero) { d.BodySetPosition(Body, m_taintPosition.X, m_taintPosition.Y, m_taintPosition.Z); _position.X = m_taintPosition.X; _position.Y = m_taintPosition.Y; _position.Z = m_taintPosition.Z; } } } internal void AddCollisionFrameTime(int p) { // protect it from overflow crashing if (m_eventsubscription + p >= int.MaxValue) m_eventsubscription = 0; m_eventsubscription += p; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class TransferCodingHeaderValueTest { [Fact] public void Ctor_ValueNull_Throw() { AssertExtensions.Throws<ArgumentException>("value", () => { new TransferCodingHeaderValue(null); }); } [Fact] public void Ctor_ValueEmpty_Throw() { // null and empty should be treated the same. So we also throw for empty strings. AssertExtensions.Throws<ArgumentException>("value", () => { new TransferCodingHeaderValue(string.Empty); }); } [Fact] public void Ctor_TransferCodingInvalidFormat_ThrowFormatException() { // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. AssertFormatException(" custom "); AssertFormatException("custom;"); AssertFormatException("ch??nked"); AssertFormatException("\"chunked\""); AssertFormatException("custom; name=value"); } [Fact] public void Ctor_TransferCodingValidFormat_SuccessfullyCreated() { TransferCodingHeaderValue transferCoding = new TransferCodingHeaderValue("custom"); Assert.Equal("custom", transferCoding.Value); Assert.Equal(0, transferCoding.Parameters.Count); } [Fact] public void Parameters_AddNull_Throw() { TransferCodingHeaderValue transferCoding = new TransferCodingHeaderValue("custom"); Assert.Throws<ArgumentNullException>(() => { transferCoding.Parameters.Add(null); }); } [Fact] public void ToString_UseDifferentTransferCodings_AllSerializedCorrectly() { TransferCodingHeaderValue transferCoding = new TransferCodingHeaderValue("custom"); Assert.Equal("custom", transferCoding.ToString()); transferCoding.Parameters.Add(new NameValueHeaderValue("paramName", "\"param value\"")); Assert.Equal("custom; paramName=\"param value\"", transferCoding.ToString()); transferCoding.Parameters.Add(new NameValueHeaderValue("paramName2", "\"param value2\"")); Assert.Equal("custom; paramName=\"param value\"; paramName2=\"param value2\"", transferCoding.ToString()); } [Fact] public void GetHashCode_UseTransferCodingWithAndWithoutParameters_SameOrDifferentHashCodes() { TransferCodingHeaderValue transferCoding1 = new TransferCodingHeaderValue("custom"); TransferCodingHeaderValue transferCoding2 = new TransferCodingHeaderValue("CUSTOM"); TransferCodingHeaderValue transferCoding3 = new TransferCodingHeaderValue("custom"); transferCoding3.Parameters.Add(new NameValueHeaderValue("name", "value")); TransferCodingHeaderValue transferCoding4 = new TransferCodingHeaderValue("custom"); transferCoding4.Parameters.Add(new NameValueHeaderValue("NAME", "VALUE")); TransferCodingHeaderValue transferCoding5 = new TransferCodingHeaderValue("custom"); transferCoding5.Parameters.Add(new NameValueHeaderValue("name", "\"value\"")); TransferCodingHeaderValue transferCoding6 = new TransferCodingHeaderValue("custom"); transferCoding6.Parameters.Add(new NameValueHeaderValue("name", "\"VALUE\"")); TransferCodingHeaderValue transferCoding7 = new TransferCodingHeaderValue("custom"); transferCoding7.Parameters.Add(new NameValueHeaderValue("name", "\"VALUE\"")); transferCoding7.Parameters.Clear(); Assert.Equal(transferCoding1.GetHashCode(), transferCoding2.GetHashCode()); Assert.NotEqual(transferCoding1.GetHashCode(), transferCoding3.GetHashCode()); Assert.Equal(transferCoding3.GetHashCode(), transferCoding4.GetHashCode()); Assert.NotEqual(transferCoding5.GetHashCode(), transferCoding6.GetHashCode()); Assert.Equal(transferCoding1.GetHashCode(), transferCoding7.GetHashCode()); } [Fact] public void Equals_UseTransferCodingWithAndWithoutParameters_EqualOrNotEqualNoExceptions() { TransferCodingHeaderValue transferCoding1 = new TransferCodingHeaderValue("custom"); TransferCodingHeaderValue transferCoding2 = new TransferCodingHeaderValue("CUSTOM"); TransferCodingHeaderValue transferCoding3 = new TransferCodingHeaderValue("custom"); transferCoding3.Parameters.Add(new NameValueHeaderValue("name", "value")); TransferCodingHeaderValue transferCoding4 = new TransferCodingHeaderValue("custom"); transferCoding4.Parameters.Add(new NameValueHeaderValue("NAME", "VALUE")); TransferCodingHeaderValue transferCoding5 = new TransferCodingHeaderValue("custom"); transferCoding5.Parameters.Add(new NameValueHeaderValue("name", "\"value\"")); TransferCodingHeaderValue transferCoding6 = new TransferCodingHeaderValue("custom"); transferCoding6.Parameters.Add(new NameValueHeaderValue("name", "\"VALUE\"")); TransferCodingHeaderValue transferCoding7 = new TransferCodingHeaderValue("custom"); transferCoding7.Parameters.Add(new NameValueHeaderValue("name", "\"VALUE\"")); transferCoding7.Parameters.Clear(); Assert.False(transferCoding1.Equals(null), "Compare to <null>."); Assert.True(transferCoding1.Equals(transferCoding2), "Different casing."); Assert.False(transferCoding1.Equals(transferCoding3), "No params vs. custom param."); Assert.True(transferCoding3.Equals(transferCoding4), "Params have different casing."); Assert.False(transferCoding5.Equals(transferCoding6), "Param value are quoted strings with different casing."); Assert.True(transferCoding1.Equals(transferCoding7), "no vs. empty parameters collection."); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { TransferCodingHeaderValue source = new TransferCodingHeaderValue("custom"); TransferCodingHeaderValue clone = (TransferCodingHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Value, clone.Value); Assert.Equal(0, clone.Parameters.Count); source.Parameters.Add(new NameValueHeaderValue("custom", "customValue")); clone = (TransferCodingHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Value, clone.Value); Assert.Equal(1, clone.Parameters.Count); Assert.Equal("custom", clone.Parameters.ElementAt(0).Name); Assert.Equal("customValue", clone.Parameters.ElementAt(0).Value); } [Fact] public void GetTransferCodingLength_DifferentValidScenarios_AllReturnNonZero() { TransferCodingHeaderValue result = null; Assert.Equal(7, TransferCodingHeaderValue.GetTransferCodingLength("chunked", 0, DummyCreator, out result)); Assert.Equal("chunked", result.Value); Assert.Equal(0, result.Parameters.Count); Assert.Equal(5, TransferCodingHeaderValue.GetTransferCodingLength("gzip , chunked", 0, DummyCreator, out result)); Assert.Equal("gzip", result.Value); Assert.Equal(0, result.Parameters.Count); Assert.Equal(18, TransferCodingHeaderValue.GetTransferCodingLength("custom; name=value", 0, DummyCreator, out result)); Assert.Equal("custom", result.Value); Assert.Equal(1, result.Parameters.Count); Assert.Equal("name", result.Parameters.ElementAt(0).Name); Assert.Equal("value", result.Parameters.ElementAt(0).Value); // Note that TransferCodingHeaderValue recognizes the first transfer-coding as valid, even though it is // followed by an invalid character. The parser will call GetTransferCodingLength() starting at the invalid // character which will result in GetTransferCodingLength() returning 0 (see next test). Assert.Equal(26, TransferCodingHeaderValue.GetTransferCodingLength( " custom;name1=value1;name2 , \u4F1A", 1, DummyCreator, out result)); Assert.Equal("custom", result.Value); Assert.Equal(2, result.Parameters.Count); Assert.Equal("name1", result.Parameters.ElementAt(0).Name); Assert.Equal("value1", result.Parameters.ElementAt(0).Value); Assert.Equal("name2", result.Parameters.ElementAt(1).Name); Assert.Null(result.Parameters.ElementAt(1).Value); // There will be no exception for invalid characters. GetTransferCodingLength() will just return a length // of 0. The caller needs to validate if that's OK or not. Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("\u4F1A", 0, DummyCreator, out result)); Assert.Equal(45, TransferCodingHeaderValue.GetTransferCodingLength( " custom ; name1 =\r\n \"value1\" ; name2 = value2 , next", 2, DummyCreator, out result)); Assert.Equal("custom", result.Value); Assert.Equal(2, result.Parameters.Count); Assert.Equal("name1", result.Parameters.ElementAt(0).Name); Assert.Equal("\"value1\"", result.Parameters.ElementAt(0).Value); Assert.Equal("name2", result.Parameters.ElementAt(1).Name); Assert.Equal("value2", result.Parameters.ElementAt(1).Value); Assert.Equal(32, TransferCodingHeaderValue.GetTransferCodingLength( " custom;name1=value1;name2=value2,next", 1, DummyCreator, out result)); Assert.Equal("custom", result.Value); Assert.Equal(2, result.Parameters.Count); Assert.Equal("name1", result.Parameters.ElementAt(0).Name); Assert.Equal("value1", result.Parameters.ElementAt(0).Value); Assert.Equal("name2", result.Parameters.ElementAt(1).Name); Assert.Equal("value2", result.Parameters.ElementAt(1).Value); } [Fact] public void GetTransferCodingLength_DifferentInvalidScenarios_AllReturnZero() { TransferCodingHeaderValue result = null; Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength(" custom", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("custom;", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("custom;name=", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("custom;name=value;", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("custom;name=,value;", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength("custom;", 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength(null, 0, DummyCreator, out result)); Assert.Null(result); Assert.Equal(0, TransferCodingHeaderValue.GetTransferCodingLength(string.Empty, 0, DummyCreator, out result)); Assert.Null(result); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { TransferCodingHeaderValue expected = new TransferCodingHeaderValue("custom"); CheckValidParse("\r\n custom ", expected); CheckValidParse("custom", expected); // We don't have to test all possible input strings, since most of the pieces are handled by other parsers. // The purpose of this test is to verify that these other parsers are combined correctly to build a // transfer-coding parser. expected.Parameters.Add(new NameValueHeaderValue("name", "value")); CheckValidParse("\r\n custom ; name = value ", expected); CheckValidParse(" custom;name=value", expected); CheckValidParse(" custom ; name=value", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("custom; name=value;"); CheckInvalidParse("custom; name1=value1; name2=value2;"); CheckInvalidParse(",,custom"); CheckInvalidParse(" , , custom"); CheckInvalidParse("\r\n custom , chunked"); CheckInvalidParse("\r\n custom , , , chunked"); CheckInvalidParse("custom , \u4F1A"); CheckInvalidParse("\r\n , , custom ; name = value "); CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" ,,"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { TransferCodingHeaderValue expected = new TransferCodingHeaderValue("custom"); CheckValidTryParse("\r\n custom ", expected); CheckValidTryParse("custom", expected); // We don't have to test all possible input strings, since most of the pieces are handled by other parsers. // The purpose of this test is to verify that these other parsers are combined correctly to build a // transfer-coding parser. expected.Parameters.Add(new NameValueHeaderValue("name", "value")); CheckValidTryParse("\r\n custom ; name = value ", expected); CheckValidTryParse(" custom;name=value", expected); CheckValidTryParse(" custom ; name=value", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("custom; name=value;"); CheckInvalidTryParse("custom; name1=value1; name2=value2;"); CheckInvalidTryParse(",,custom"); CheckInvalidTryParse(" , , custom"); CheckInvalidTryParse("\r\n custom , chunked"); CheckInvalidTryParse("\r\n custom , , , chunked"); CheckInvalidTryParse("custom , \u4F1A"); CheckInvalidTryParse("\r\n , , custom ; name = value "); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" ,,"); } #region Helper methods private void CheckValidParse(string input, TransferCodingHeaderValue expectedResult) { TransferCodingHeaderValue result = TransferCodingHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { TransferCodingHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, TransferCodingHeaderValue expectedResult) { TransferCodingHeaderValue result = null; Assert.True(TransferCodingHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { TransferCodingHeaderValue result = null; Assert.False(TransferCodingHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void AssertFormatException(string transferCoding) { Assert.Throws<FormatException>(() => { new TransferCodingHeaderValue(transferCoding); }); } private static TransferCodingHeaderValue DummyCreator() { return new TransferCodingHeaderValue(); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Support; using ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Index { /// <summary>This is just a "splitter" class: it lets you wrap two /// DocFieldConsumer instances as a single consumer. /// </summary> sealed class DocFieldConsumers : DocFieldConsumer { private void InitBlock() { docFreeList = new PerDoc[1]; } internal DocFieldConsumer one; internal DocFieldConsumer two; public DocFieldConsumers(DocFieldConsumer one, DocFieldConsumer two) { InitBlock(); this.one = one; this.two = two; } internal override void SetFieldInfos(FieldInfos fieldInfos) { base.SetFieldInfos(fieldInfos); one.SetFieldInfos(fieldInfos); two.SetFieldInfos(fieldInfos); } public override void Flush(IDictionary<DocFieldConsumerPerThread, ICollection<DocFieldConsumerPerField>> threadsAndFields, SegmentWriteState state) { var oneThreadsAndFields = new HashMap<DocFieldConsumerPerThread, ICollection<DocFieldConsumerPerField>>(); var twoThreadsAndFields = new HashMap<DocFieldConsumerPerThread, ICollection<DocFieldConsumerPerField>>(); foreach(var entry in threadsAndFields) { DocFieldConsumersPerThread perThread = (DocFieldConsumersPerThread) entry.Key; ICollection<DocFieldConsumerPerField> fields = entry.Value; IEnumerator<DocFieldConsumerPerField> fieldsIt = fields.GetEnumerator(); ICollection<DocFieldConsumerPerField> oneFields = new HashSet<DocFieldConsumerPerField>(); ICollection<DocFieldConsumerPerField> twoFields = new HashSet<DocFieldConsumerPerField>(); while (fieldsIt.MoveNext()) { DocFieldConsumersPerField perField = (DocFieldConsumersPerField) fieldsIt.Current; oneFields.Add(perField.one); twoFields.Add(perField.two); } oneThreadsAndFields[perThread.one] = oneFields; twoThreadsAndFields[perThread.two] = twoFields; } one.Flush(oneThreadsAndFields, state); two.Flush(twoThreadsAndFields, state); } public override void CloseDocStore(SegmentWriteState state) { try { one.CloseDocStore(state); } finally { two.CloseDocStore(state); } } public override void Abort() { try { one.Abort(); } finally { two.Abort(); } } public override bool FreeRAM() { bool any = one.FreeRAM(); any |= two.FreeRAM(); return any; } public override DocFieldConsumerPerThread AddThread(DocFieldProcessorPerThread docFieldProcessorPerThread) { return new DocFieldConsumersPerThread(docFieldProcessorPerThread, this, one.AddThread(docFieldProcessorPerThread), two.AddThread(docFieldProcessorPerThread)); } internal PerDoc[] docFreeList; internal int freeCount; internal int allocCount; internal PerDoc GetPerDoc() { lock (this) { if (freeCount == 0) { allocCount++; if (allocCount > docFreeList.Length) { // Grow our free list up front to make sure we have // enough space to recycle all outstanding PerDoc // instances System.Diagnostics.Debug.Assert(allocCount == 1 + docFreeList.Length); docFreeList = new PerDoc[ArrayUtil.GetNextSize(allocCount)]; } return new PerDoc(this); } else return docFreeList[--freeCount]; } } internal void FreePerDoc(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(freeCount < docFreeList.Length); docFreeList[freeCount++] = perDoc; } } internal class PerDoc:DocumentsWriter.DocWriter { public PerDoc(DocFieldConsumers enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(DocFieldConsumers enclosingInstance) { this.enclosingInstance = enclosingInstance; } private DocFieldConsumers enclosingInstance; public DocFieldConsumers Enclosing_Instance { get { return enclosingInstance; } } internal DocumentsWriter.DocWriter one; internal DocumentsWriter.DocWriter two; public override long SizeInBytes() { return one.SizeInBytes() + two.SizeInBytes(); } public override void Finish() { try { try { one.Finish(); } finally { two.Finish(); } } finally { Enclosing_Instance.FreePerDoc(this); } } public override void Abort() { try { try { one.Abort(); } finally { two.Abort(); } } finally { Enclosing_Instance.FreePerDoc(this); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableList{T}"/>. /// </summary> public static class ImmutableList { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>() { return ImmutableList<T>.Empty; } /// <summary> /// Creates a new immutable collection prefilled with the specified item. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="item">The item to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(T item) { return ImmutableList<T>.Empty.Add(item); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> CreateRange<T>(IEnumerable<T> items) { return ImmutableList<T>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(params T[] items) { return ImmutableList<T>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable list builder. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableList<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } /// <summary> /// Enumerates a sequence exactly once and produces an immutable list of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="source">The sequence to enumerate.</param> /// <returns>An immutable list.</returns> [Pure] public static ImmutableList<TSource> ToImmutableList<TSource>(this IEnumerable<TSource> source) { var existingList = source as ImmutableList<TSource>; if (existingList != null) { return existingList; } return ImmutableList<TSource>.Empty.AddRange(source); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> [Pure] public static IImmutableList<T> Replace<T>(this IImmutableList<T> list, T oldValue, T newValue) { Requires.NotNull(list, nameof(list)); return list.Replace(oldValue, newValue, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified value from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="value">The value to remove.</param> /// <returns>A new list with the element removed, or this list if the element is not in this list.</returns> [Pure] public static IImmutableList<T> Remove<T>(this IImmutableList<T> list, T value) { Requires.NotNull(list, nameof(list)); return list.Remove(value, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> [Pure] public static IImmutableList<T> RemoveRange<T>(this IImmutableList<T> list, IEnumerable<T> items) { Requires.NotNull(list, nameof(list)); return list.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, 0, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, 0, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, startIndex, list.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// <see cref="IImmutableList{T}"/>, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, nameof(list)); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// <see cref="IImmutableList{T}"/>, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, nameof(list)); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the <see cref="IImmutableList{T}"/> that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, nameof(list)); if (list.Count == 0 && startIndex == 0) { return -1; } return list.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the <see cref="IImmutableList{T}"/> that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, nameof(list)); return list.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the ConTurnosAnticipadosAusente class. /// </summary> [Serializable] public partial class ConTurnosAnticipadosAusenteCollection : ReadOnlyList<ConTurnosAnticipadosAusente, ConTurnosAnticipadosAusenteCollection> { public ConTurnosAnticipadosAusenteCollection() {} } /// <summary> /// This is Read-only wrapper class for the CON_TurnosAnticipadosAusentes view. /// </summary> [Serializable] public partial class ConTurnosAnticipadosAusente : ReadOnlyRecord<ConTurnosAnticipadosAusente>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_TurnosAnticipadosAusentes", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarCantidadTurnos = new TableSchema.TableColumn(schema); colvarCantidadTurnos.ColumnName = "cantidadTurnos"; colvarCantidadTurnos.DataType = DbType.Int32; colvarCantidadTurnos.MaxLength = 0; colvarCantidadTurnos.AutoIncrement = false; colvarCantidadTurnos.IsNullable = true; colvarCantidadTurnos.IsPrimaryKey = false; colvarCantidadTurnos.IsForeignKey = false; colvarCantidadTurnos.IsReadOnly = false; schema.Columns.Add(colvarCantidadTurnos); TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema); colvarIdAgenda.ColumnName = "idAgenda"; colvarIdAgenda.DataType = DbType.Int32; colvarIdAgenda.MaxLength = 0; colvarIdAgenda.AutoIncrement = false; colvarIdAgenda.IsNullable = false; colvarIdAgenda.IsPrimaryKey = false; colvarIdAgenda.IsForeignKey = false; colvarIdAgenda.IsReadOnly = false; schema.Columns.Add(colvarIdAgenda); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_TurnosAnticipadosAusentes",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ConTurnosAnticipadosAusente() { SetSQLProps(); SetDefaults(); MarkNew(); } public ConTurnosAnticipadosAusente(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ConTurnosAnticipadosAusente(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ConTurnosAnticipadosAusente(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>("nombre"); } set { SetColumnValue("nombre", value); } } [XmlAttribute("CantidadTurnos")] [Bindable(true)] public int? CantidadTurnos { get { return GetColumnValue<int?>("cantidadTurnos"); } set { SetColumnValue("cantidadTurnos", value); } } [XmlAttribute("IdAgenda")] [Bindable(true)] public int IdAgenda { get { return GetColumnValue<int>("idAgenda"); } set { SetColumnValue("idAgenda", value); } } #endregion #region Columns Struct public struct Columns { public static string Nombre = @"nombre"; public static string CantidadTurnos = @"cantidadTurnos"; public static string IdAgenda = @"idAgenda"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Globalization; namespace NodaTime.Text { internal sealed class ValueCursor : TextCursor { /// <summary> /// Initializes a new instance of the <see cref="ValueCursor" /> class. /// </summary> /// <param name="value">The string to parse.</param> internal ValueCursor(string value) : base(value) { } /// <summary> /// Attempts to match the specified character with the current character of the string. If the /// character matches then the index is moved passed the character. /// </summary> /// <param name="character">The character to match.</param> /// <returns><c>true</c> if the character matches.</returns> internal bool Match(char character) { if (Current == character) { MoveNext(); return true; } return false; } /// <summary> /// Attempts to match the specified string with the current point in the string. If the /// character matches then the index is moved past the string. /// </summary> /// <param name="match">The string to match.</param> /// <returns><c>true</c> if the string matches.</returns> internal bool Match(string match) { unchecked { if (string.CompareOrdinal(Value, Index, match, 0, match.Length) == 0) { Move(Index + match.Length); return true; } return false; } } /// <summary> /// Attempts to match the specified string with the current point in the string in a case-insensitive /// manner, according to the given comparison info. The cursor is optionally updated to the end of the match. /// </summary> internal bool MatchCaseInsensitive(string match, CompareInfo compareInfo, bool moveOnSuccess) { unchecked { if (match.Length > Value.Length - Index) { return false; } // Note: This will fail if the length in the input string is different to the length in the // match string for culture-specific reasons. It's not clear how to handle that... // See issue 210 for details - we're not intending to fix this, but it's annoying. if (compareInfo.Compare(Value, Index, match.Length, match, 0, match.Length, CompareOptions.IgnoreCase) == 0) { if (moveOnSuccess) { Move(Index + match.Length); } return true; } return false; } } /// <summary> /// Compares the value from the current cursor position with the given match. If the /// given match string is longer than the remaining length, the comparison still goes /// ahead but the result is never 0: if the result of comparing to the end of the /// value returns 0, the result is -1 to indicate that the value is earlier than the given match. /// Conversely, if the remaining value is longer than the match string, the comparison only /// goes as far as the end of the match. So "xabcd" with the cursor at "a" will return 0 when /// matched with "abc". /// </summary> /// <returns>A negative number if the value (from the current cursor position) is lexicographically /// earlier than the given match string; 0 if they are equal (as far as the end of the match) and /// a positive number if the value is lexicographically later than the given match string.</returns> internal int CompareOrdinal(string match) { int remaining = Value.Length - Index; if (match.Length > remaining) { int ret = string.CompareOrdinal(Value, Index, match, 0, remaining); return ret == 0 ? -1 : ret; } return string.CompareOrdinal(Value, Index, match, 0, match.Length); } /// <summary> /// Parses digits at the current point in the string as a signed 64-bit integer value. /// Currently this method only supports cultures whose negative sign is "-" (and /// using ASCII digits). /// </summary> /// <param name="result">The result integer value. The value of this is not guaranteed /// to be anything specific if the return value is non-null.</param> /// <returns>null if the digits were parsed, or the appropriate parse failure</returns> internal ParseResult<T> ParseInt64<T>(out long result) { unchecked { result = 0L; int startIndex = Index; bool negative = Current == '-'; if (negative) { if (!MoveNext()) { Move(startIndex); return ParseResult<T>.EndOfString(this); } } int count = 0; int digit; while (result < 922337203685477580 && (digit = GetDigit()) != -1) { result = result * 10 + digit; count++; if (!MoveNext()) { break; } } if (count == 0) { Move(startIndex); return ParseResult<T>.MissingNumber(this); } if (result >= 922337203685477580 && (digit = GetDigit()) != -1) { if (result > 922337203685477580) { return BuildNumberOutOfRangeResult<T>(startIndex); } if (negative && digit == 8) { MoveNext(); result = long.MinValue; return null; } if (digit > 7) { return BuildNumberOutOfRangeResult<T>(startIndex); } // We know we can cope with this digit... result = result * 10 + digit; MoveNext(); if (GetDigit() != -1) { // Too many digits. Die. return BuildNumberOutOfRangeResult<T>(startIndex); } } if (negative) { result = -result; } return null; } } private ParseResult<T> BuildNumberOutOfRangeResult<T>(int startIndex) { Move(startIndex); if (Current == '-') { MoveNext(); } // End of string works like not finding a digit. while (GetDigit() != -1) { MoveNext(); } string badValue = Value.Substring(startIndex, Index - startIndex); Move(startIndex); return ParseResult<T>.ValueOutOfRange(this, badValue); } /// <summary> /// Parses digits at the current point in the string, as an <see cref="Int64"/> value. /// If the minimum required /// digits are not present then the index is unchanged. If there are more digits than /// the maximum allowed they are ignored. /// </summary> /// <param name="minimumDigits">The minimum allowed digits.</param> /// <param name="maximumDigits">The maximum allowed digits.</param> /// <param name="result">The result integer value. The value of this is not guaranteed /// to be anything specific if the return value is false.</param> /// <returns><c>true</c> if the digits were parsed.</returns> internal bool ParseInt64Digits(int minimumDigits, int maximumDigits, out long result) { unchecked { result = 0; int localIndex = Index; int maxIndex = localIndex + maximumDigits; if (maxIndex >= Length) { maxIndex = Length; } for (; localIndex < maxIndex; localIndex++) { // Optimized digit handling: rather than checking for the range, returning -1 // and then checking whether the result is -1, we can do both checks at once. int digit = Value[localIndex] - '0'; if (digit < 0 || digit > 9) { break; } result = result * 10 + digit; } int count = localIndex - Index; if (count < minimumDigits) { return false; } Move(localIndex); return true; } } /// <summary> /// Parses digits at the current point in the string. If the minimum required /// digits are not present then the index is unchanged. If there are more digits than /// the maximum allowed they are ignored. /// </summary> /// <param name="minimumDigits">The minimum allowed digits.</param> /// <param name="maximumDigits">The maximum allowed digits.</param> /// <param name="result">The result integer value. The value of this is not guaranteed /// to be anything specific if the return value is false.</param> /// <returns><c>true</c> if the digits were parsed.</returns> internal bool ParseDigits(int minimumDigits, int maximumDigits, out int result) { unchecked { result = 0; int localIndex = Index; int maxIndex = localIndex + maximumDigits; if (maxIndex >= Length) { maxIndex = Length; } for (; localIndex < maxIndex; localIndex++) { // Optimized digit handling: rather than checking for the range, returning -1 // and then checking whether the result is -1, we can do both checks at once. int digit = Value[localIndex] - '0'; if (digit < 0 || digit > 9) { break; } result = result * 10 + digit; } int count = localIndex - Index; if (count < minimumDigits) { return false; } Move(localIndex); return true; } } /// <summary> /// Parses digits at the current point in the string as a fractional value. /// </summary> /// <param name="maximumDigits">The maximum allowed digits.</param> /// <param name="scale">The scale of the fractional value.</param> /// <param name="result">The result value scaled by scale. The value of this is not guaranteed /// to be anything specific if the return value is false.</param> /// <param name="minimumDigits">The minimum number of digits that must be specified in the value.</param> /// <returns><c>true</c> if the digits were parsed.</returns> internal bool ParseFraction(int maximumDigits, int scale, out int result, int minimumDigits) { unchecked { if (scale < maximumDigits) { scale = maximumDigits; } result = 0; int localIndex = Index; int minIndex = localIndex + minimumDigits; if (minIndex > Length) { // If we don't have all the digits we're meant to have, we can't possibly succeed. return false; } int maxIndex = Math.Min(localIndex + maximumDigits, Length); for (; localIndex < maxIndex; localIndex++) { // Optimized digit handling: rather than checking for the range, returning -1 // and then checking whether the result is -1, we can do both checks at once. int digit = Value[localIndex] - '0'; if (digit < 0 || digit > 9) { break; } result = result * 10 + digit; } int count = localIndex - Index; // Couldn't parse the minimum number of digits required? if (count < minimumDigits) { return false; } result = (int) (result * Math.Pow(10.0, scale - count)); Move(localIndex); return true; } } /// <summary> /// Gets the integer value of the current digit character, or -1 for "not a digit". /// </summary> /// <remarks> /// This currently only handles ASCII digits, which is all we have to parse to stay in line with the BCL. /// </remarks> private int GetDigit() { unchecked { int c = Current; return c < '0' || c > '9' ? -1 : c - '0'; } } } }
namespace System.Workflow.ComponentModel.Compiler { using System; using System.Resources; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Design; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.Win32; using Microsoft.CSharp; using Microsoft.VisualBasic; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Serialization; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Runtime.InteropServices; using Microsoft.Build.Tasks; using System.Collections.Generic; using Microsoft.Workflow.Compiler; using System.Runtime.Versioning; using System.Security; [Guid("59B2D1D0-5DB0-4F9F-9609-13F0168516D6")] [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsHierarchy { } [Guid("6d5140c1-7436-11ce-8034-00aa006009fa")] [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IOleServiceProvider { [PreserveSig] int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject); } [ComImport(), Guid("8AA9644E-1F6A-4F4C-83E3-D0BAD4B2BB21"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IWorkflowBuildHostProperties { bool SkipWorkflowCompilation { get; set; } } internal class ServiceProvider : IServiceProvider { private static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); private IOleServiceProvider serviceProvider; public ServiceProvider(IOleServiceProvider sp) { this.serviceProvider = sp; } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); IntPtr pUnk = IntPtr.Zero; Guid guidService = serviceType.GUID; Guid guidUnk = IID_IUnknown; int hr = this.serviceProvider.QueryService(ref guidService, ref guidUnk, out pUnk); object service = null; if (hr >= 0) { try { service = Marshal.GetObjectForIUnknown(pUnk); } finally { Marshal.Release(pUnk); } } return service; } } #region CompileWorkflowTask /// <summary> /// This class extends the Task class of MSBuild framework. /// Methods of this class are invoked by the MSBuild framework to customize /// the build process when compiling WinOE flavors of CSharp and VB.net projects. /// It provides support for compiling .xoml files into intermediate /// code files (either CSharp or VB). It calls into the WorkflowCompiler to do the /// validations and code compile unit generation. /// This component is used during the build process of WinOE flavor projects /// both from within the Visual Studio IDE and the standalone MSBuild executable. /// As such this component's assembly should not have direct or indirect dependencies /// on the Visual Studio assemblies to work in the standalone scenario. /// </summary> [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class CompileWorkflowTask : Microsoft.Build.Utilities.Task, ITask { #region Members and Constructors private string projectExt = null; private string projectDirectory = null; private object hostObject = null; private string rootNamespace = null; private string imports = null; private string assemblyName = null; private ITaskItem[] xomlFiles = null; private ITaskItem[] referenceFiles = null; private ITaskItem[] sourceCodeFiles = null; private ITaskItem[] resourceFiles = null; private ITaskItem[] outputFiles = null; //new TaskItem[0]; // The outputs should be non-null if we bail out successfully or otherwise from the Execute method. private ITaskItem[] compilationOptions = null; private SupportedLanguages projectType; private StringCollection temporaryFiles = new StringCollection(); private bool delaySign = false; private string targetFramework = null; private string keyContainer = null; private string keyFile = null; public CompileWorkflowTask() : base(new ResourceManager("System.Workflow.ComponentModel.BuildTasksStrings", Assembly.GetExecutingAssembly())) { this.BuildingProject = true; } #endregion #region Input parameters and property overrides public string ProjectDirectory { get { return this.projectDirectory; } set { this.projectDirectory = value; } } public string ProjectExtension { get { return this.projectExt; } set { this.projectExt = value; if (String.Compare(this.projectExt, ".csproj", StringComparison.OrdinalIgnoreCase) == 0) { ProjectType = SupportedLanguages.CSharp; } else if (String.Compare(this.projectExt, ".vbproj", StringComparison.OrdinalIgnoreCase) == 0) { ProjectType = SupportedLanguages.VB; } } } public string RootNamespace { get { return this.rootNamespace; } set { this.rootNamespace = value; } } public string AssemblyName { get { return this.assemblyName; } set { this.assemblyName = value; } } public string Imports { get { return this.imports; } set { this.imports = value; } } public ITaskItem[] WorkflowMarkupFiles { get { return xomlFiles; } set { if (value != null) { ArrayList xomlFilesOnly = new ArrayList(); foreach (ITaskItem inputFile in value) { if (inputFile != null) { string fileSpec = inputFile.ItemSpec; if (fileSpec != null && fileSpec.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) { xomlFilesOnly.Add(inputFile); } } } if (xomlFilesOnly.Count > 0) { this.xomlFiles = xomlFilesOnly.ToArray(typeof(ITaskItem)) as ITaskItem[]; } } else { this.xomlFiles = value; } } } public ITaskItem[] ReferenceFiles { get { return this.referenceFiles; } set { this.referenceFiles = value; } } public ITaskItem[] ResourceFiles { get { return this.resourceFiles; } set { this.resourceFiles = value; } } public ITaskItem[] SourceCodeFiles { get { return this.sourceCodeFiles; } set { this.sourceCodeFiles = value; } } public ITaskItem[] CompilationOptions { get { return this.compilationOptions; } set { this.compilationOptions = value; } } public bool DelaySign { get { return this.delaySign; } set { this.delaySign = value; } } public string TargetFramework { get { return this.targetFramework; } set { this.targetFramework = value; } } public string KeyContainer { get { return this.keyContainer; } set { this.keyContainer = value; } } public string KeyFile { get { return this.keyFile; } set { this.keyFile = value; } } public new object HostObject { get { return this.hostObject; } } ITaskHost ITask.HostObject { get { return (ITaskHost)this.hostObject; } set { this.hostObject = value; } } public bool BuildingProject { get; set; } #endregion #region Output parameter properties [OutputAttribute] public ITaskItem[] OutputFiles { get { if (this.outputFiles == null) { if (this.ProjectType == SupportedLanguages.VB) this.outputFiles = new ITaskItem[0]; else { ArrayList oFiles = new ArrayList(); if (this.WorkflowMarkupFiles != null) oFiles.AddRange(this.WorkflowMarkupFiles); this.outputFiles = oFiles.ToArray(typeof(ITaskItem)) as ITaskItem[]; } } return this.outputFiles; } } [OutputAttribute] public string KeepTemporaryFiles { get { return ShouldKeepTempFiles().ToString(); } } [OutputAttribute] public string[] TemporaryFiles { get { string[] tempFiles = new string[this.temporaryFiles.Count]; this.temporaryFiles.CopyTo(tempFiles, 0); return tempFiles; } } #endregion #region Public method overrides public override bool Execute() { #if DEBUG DumpInputParameters(); #endif // Validate the input parameters for the task. if (!this.ValidateParameters()) return false; // If no .xoml files were specified, return success. if (this.WorkflowMarkupFiles == null) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles"); // Check if there are any referenced assemblies. if (this.ReferenceFiles == null || this.ReferenceFiles.Length == 0) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles"); // Check if there are any souce code files (cs/vb). if (this.SourceCodeFiles == null || this.SourceCodeFiles.Length == 0) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles"); // we return early if this is not invoked during the build phase of the project (eg project load) IWorkflowBuildHostProperties workflowBuildHostProperty = this.HostObject as IWorkflowBuildHostProperties; if (!this.BuildingProject || (workflowBuildHostProperty != null && workflowBuildHostProperty.SkipWorkflowCompilation)) { return true; } // Create an instance of WorkflowCompilerParameters. int errorCount = 0, warningCount = 0; WorkflowCompilerParameters compilerParameters = new WorkflowCompilerParameters(); // set the service provider IWorkflowCompilerErrorLogger workflowErrorLogger = null; IServiceProvider externalServiceProvider = null; if (this.HostObject is IOleServiceProvider) { externalServiceProvider = new ServiceProvider(this.HostObject as IOleServiceProvider); workflowErrorLogger = externalServiceProvider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger; } string[] userCodeFiles = GetFiles(this.SourceCodeFiles, this.ProjectDirectory); foreach (ITaskItem referenceFile in this.ReferenceFiles) compilerParameters.ReferencedAssemblies.Add(referenceFile.ItemSpec); if (string.IsNullOrEmpty(this.targetFramework)) { string defaultFrameworkName = null; const string NDPSetupRegistryBranch = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"; const string NetFrameworkIdentifier = ".NETFramework"; RegistryKey ndpSetupKey = null; try { ndpSetupKey = Registry.LocalMachine.OpenSubKey(NDPSetupRegistryBranch); if (ndpSetupKey != null) { string[] installedNetFxs = ndpSetupKey.GetSubKeyNames(); if (installedNetFxs != null) { char[] splitChars = new char[] { '.' }; for (int i = 0; i < installedNetFxs.Length; i++) { string framework = installedNetFxs[i]; if (framework.Length > 0) { string frameworkVersion = framework.TrimStart('v', 'V'); if (!string.IsNullOrEmpty(frameworkVersion)) { string[] parts = frameworkVersion.Split(splitChars); string normalizedVersion = null; if (parts.Length > 1) { normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.{1}", parts[0], parts[1]); } else { normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.0", parts[0]); } if (string.Compare(normalizedVersion, "v3.5", StringComparison.OrdinalIgnoreCase) == 0) { defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(3, 5)).ToString(); break; } } } } } } } catch (SecurityException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } finally { if (ndpSetupKey != null) { ndpSetupKey.Close(); } } if (defaultFrameworkName == null) { defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(2, 0)).ToString(); } compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(defaultFrameworkName); } else { compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework); } CompilerOptionsBuilder optionsBuilder; switch (this.ProjectType) { case SupportedLanguages.VB: switch (compilerParameters.CompilerVersion) { case MultiTargetingInfo.TargetFramework30CompilerVersion: optionsBuilder = new WhidbeyVBCompilerOptionsBuilder(); break; case MultiTargetingInfo.TargetFramework35CompilerVersion: optionsBuilder = new OrcasVBCompilerOptionsBuilder(); break; default: optionsBuilder = new CompilerOptionsBuilder(); break; } break; default: optionsBuilder = new CompilerOptionsBuilder(); break; } compilerParameters.CompilerOptions = this.PrepareCompilerOptions(optionsBuilder); compilerParameters.GenerateCodeCompileUnitOnly = true; compilerParameters.LanguageToUse = this.ProjectType.ToString(); compilerParameters.TempFiles.KeepFiles = ShouldKeepTempFiles(); compilerParameters.OutputAssembly = AssemblyName; if (!string.IsNullOrEmpty(assemblyName)) { // Normalizing the assembly name. // The codeDomProvider expects the proper extension to be set. string extension = (compilerParameters.GenerateExecutable) ? ".exe" : ".dll"; compilerParameters.OutputAssembly += extension; } CodeDomProvider codeProvider = null; if (this.ProjectType == SupportedLanguages.VB) codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), compilerParameters.CompilerVersion); else codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), compilerParameters.CompilerVersion); using (TempFileCollection tempFileCollection = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true)) { this.outputFiles = new TaskItem[1]; // Compile and generate a temporary code file for each xoml file. string[] xomlFilesPaths; if (this.WorkflowMarkupFiles != null) { xomlFilesPaths = new string[WorkflowMarkupFiles.GetLength(0) + userCodeFiles.Length]; int index = 0; for (; index < this.WorkflowMarkupFiles.GetLength(0); index++) xomlFilesPaths[index] = Path.Combine(ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec); userCodeFiles.CopyTo(xomlFilesPaths, index); } else { xomlFilesPaths = new string[userCodeFiles.Length]; userCodeFiles.CopyTo(xomlFilesPaths, 0); } WorkflowCompilerResults compilerResults = new CompilerWrapper().Compile(compilerParameters, xomlFilesPaths); foreach (WorkflowCompilerError error in compilerResults.Errors) { if (error.IsWarning) { warningCount++; if (workflowErrorLogger != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); workflowErrorLogger.LogError(error); workflowErrorLogger.LogMessage(error.ToString() + "\n"); } else this.Log.LogWarning(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column); } else { errorCount++; if (workflowErrorLogger != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); workflowErrorLogger.LogError(error); workflowErrorLogger.LogMessage(error.ToString() + "\n"); } else this.Log.LogError(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column); } } if (!compilerResults.Errors.HasErrors) { CodeCompileUnit ccu = compilerResults.CompiledUnit; if (ccu != null) { // Fix standard namespaces and root namespace. WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(ccu.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString())); //just add the standard namespaces string tempFile = tempFileCollection.AddExtension(codeProvider.FileExtension); using (StreamWriter fileStream = new StreamWriter(new FileStream(tempFile, FileMode.Create, FileAccess.Write), Encoding.UTF8)) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeProvider.GenerateCodeFromCompileUnit(ccu, fileStream, options); } this.outputFiles[0] = new TaskItem(tempFile); this.temporaryFiles.Add(tempFile); this.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", tempFile); } } } if ((errorCount > 0 || warningCount > 0) && workflowErrorLogger != null) workflowErrorLogger.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { errorCount, warningCount })); #if DEBUG DumpOutputParameters(); #endif this.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", errorCount, warningCount); return (errorCount == 0); } #endregion #region Private properties and methods private SupportedLanguages ProjectType { get { return this.projectType; } set { this.projectType = value; } } /// <summary> /// This method validates all the input parameters for the custom task. /// </summary> /// <returns>True if all parameters are valid, false otherwise</returns> private bool ValidateParameters() { // If the project directory is not supplied then bail out with an error. if (ProjectDirectory == null || ProjectDirectory.Trim().Length == 0) { this.Log.LogErrorFromResources("NoProjectType"); return false; } // If the project extension is not supplied then bail out with an error. if (ProjectExtension == null || ProjectExtension.Trim().Length == 0) { this.Log.LogErrorFromResources("NoProjectType"); return false; } // If the project extension is not .csproj or .vbproj bail out with an error. if (String.Compare(ProjectExtension, ".csproj", StringComparison.OrdinalIgnoreCase) != 0 && String.Compare(ProjectExtension, ".vbproj", StringComparison.OrdinalIgnoreCase) != 0) { this.Log.LogErrorFromResources("UnsupportedProjectType"); return false; } // All parameters are valid so return true. return true; } #if DEBUG void DumpInputParameters() { DumpParametersLine("CompileWorkflowTask - Input Parameters:"); DumpParametersLine(" projectExt={0}", this.projectExt); DumpParametersLine(" projectDirectory='{0}'", this.projectDirectory); DumpParametersLine(" rootNamespace={0}", this.rootNamespace); DumpParametersLine(" imports='{0}'", this.imports); DumpParametersLine(" assemblyName='{0}", this.assemblyName); DumpParametersTaskItems("xomlFiles", this.xomlFiles); DumpParametersTaskItems("sourceCodeFiles", this.sourceCodeFiles); DumpParametersTaskItems("resourceFiles", this.resourceFiles); DumpParametersTaskItems("referenceFiles", this.referenceFiles); DumpParametersTaskItems("compilationOptions", this.compilationOptions); DumpParametersLine(" delaySign={0},keyContainer='{1}',keyFile='{2}'", this.delaySign, this.keyContainer, this.keyFile); DumpParametersLine(" targetFramework='{0}'", this.targetFramework); } void DumpOutputParameters() { DumpParametersLine("CompileWorkflowTask - Output Parameters:"); DumpParametersTaskItems("outputFiles", this.outputFiles); DumpParametersLine(" KeepTemporaryFiles={0},temporaryFiles=[{1} items]", this.KeepTemporaryFiles, this.temporaryFiles.Count); for (int i = 0; i < this.temporaryFiles.Count; i++) { DumpParametersLine(" '{0}' [{1}]", this.temporaryFiles[i], i); } } void DumpParametersTaskItems(string name, ITaskItem[] items) { if (items == null) { DumpParametersLine(" {0}=<null>", name); } else { DumpParametersLine(" {0}=[{1} items]", name, items.Length); for (int i = 0; i < items.Length; i++) { ITaskItem item = items[i]; if (item == null) { DumpParametersLine(" <null> [{0}]", i); } else { DumpParametersLine(" {0} [{1}]", item.ItemSpec, i); foreach (string metadataName in item.MetadataNames) { DumpParametersLine(" {0}='{1}'", metadataName, item.GetMetadata(metadataName)); } } } } } void DumpParametersLine(string lineFormat, params object[] lineArguments) { if ((lineArguments != null) && (lineArguments.Length > 0)) { for (int i = 0; i < lineArguments.Length; i++) { if (lineArguments[i] == null) { lineArguments[i] = "<null>"; } } } this.Log.LogMessage(MessageImportance.Low, lineFormat, lineArguments); } #endif /// <summary> /// This method is used to get the absolute paths of the files /// in a project. /// </summary> /// <param name="taskItems"></param> /// <param name="projDir"></param> /// <returns></returns> private static string[] GetFiles(ITaskItem[] taskItems, string projDir) { if (taskItems == null) return new string[0]; string[] itemSpecs = new string[taskItems.Length]; for (int i = 0; i < taskItems.Length; i++) { if (projDir != null) { itemSpecs[i] = Path.Combine(projDir, taskItems[i].ItemSpec); } else { itemSpecs[i] = taskItems[i].ItemSpec; } } return itemSpecs; } private static bool HasManifestResourceName(ITaskItem resourceFile, out string manifestResourceName) { IEnumerator metadataNames = resourceFile.MetadataNames.GetEnumerator(); manifestResourceName = null; bool hasName = false; while (!hasName && metadataNames.MoveNext()) { string metadataName = (string)metadataNames.Current; if (metadataName == "ManifestResourceName") { hasName = true; manifestResourceName = resourceFile.GetMetadata(metadataName); } } return hasName; } //Note: Remember to prefix each option with a space. We don't want compiler options glued together. private string PrepareCompilerOptions(CompilerOptionsBuilder optionsBuilder) { StringBuilder compilerOptions = new StringBuilder(); if (this.DelaySign == true) compilerOptions.Append(" /delaysign+"); if (this.KeyContainer != null && this.KeyContainer.Trim().Length > 0) compilerOptions.AppendFormat(" /keycontainer:{0}", this.KeyContainer); if (this.KeyFile != null && this.KeyFile.Trim().Length > 0) compilerOptions.AppendFormat(" /keyfile:\"{0}\"", Path.Combine(this.ProjectDirectory, this.KeyFile)); if (this.compilationOptions != null && this.compilationOptions.Length > 0) { foreach (ITaskItem option in this.compilationOptions) { optionsBuilder.AddCustomOption(compilerOptions, option); } } if (this.resourceFiles != null && this.resourceFiles.Length > 0) { foreach (ITaskItem resourceFile in this.resourceFiles) { string manifestResourceName; if (HasManifestResourceName(resourceFile, out manifestResourceName)) { compilerOptions.AppendFormat(" /resource:\"{0}\",{1}", Path.Combine(this.ProjectDirectory, resourceFile.ItemSpec), manifestResourceName); } else { compilerOptions.AppendFormat(" /resource:\"{0}\"", Path.Combine(this.ProjectDirectory, resourceFile.ItemSpec)); } } } if (this.ProjectType == SupportedLanguages.VB) { if (!string.IsNullOrEmpty(this.RootNamespace)) compilerOptions.AppendFormat(" /rootnamespace:{0}", this.RootNamespace); compilerOptions.AppendFormat(" /imports:{0}", this.Imports.Replace(';', ',')); } if (compilerOptions.Length > 0) { if (char.IsWhiteSpace(compilerOptions[0])) { compilerOptions.Remove(0, 0); } } return compilerOptions.ToString(); } private bool ShouldKeepTempFiles() { bool retVal = false; // See comments for the CompileWorkflowCleanupTask class for reasons why we must keep the temp file for VB. if (this.ProjectType == SupportedLanguages.VB) retVal = true; else { try { RegistryKey winoeKey = Registry.LocalMachine.OpenSubKey(Helpers.ProductRootRegKey); if (winoeKey != null) { object obj = winoeKey.GetValue("KeepTempFiles"); retVal = (Convert.ToInt32(obj, CultureInfo.InvariantCulture) != 0); } } catch { } } return retVal; } #endregion class CompilerOptionsBuilder { public CompilerOptionsBuilder() { } public void AddCustomOption(StringBuilder options, ITaskItem option) { string optionName; string optionValue; string optionDelimiter; GetOptionInfo(option, out optionName, out optionValue, out optionDelimiter); if (!string.IsNullOrWhiteSpace(optionName)) { if (string.IsNullOrEmpty(optionValue)) { options.AppendFormat(" /{0}", optionName); } else if (string.IsNullOrEmpty(optionDelimiter)) { options.AppendFormat(" /{0}{1}", optionName, optionValue); } else { options.AppendFormat(" /{0}{1}{2}", optionName, optionDelimiter, optionValue); } } } protected virtual void GetOptionInfo(ITaskItem option, out string optionName, out string optionValue, out string optionDelimiter) { optionName = option.ItemSpec; optionValue = option.GetMetadata("value"); optionDelimiter = option.GetMetadata("delimiter"); } } abstract class VBCompilerOptionsBuilder : CompilerOptionsBuilder { const string SuppressWarningOption = "nowarn"; protected VBCompilerOptionsBuilder() : base() { } sealed protected override void GetOptionInfo(ITaskItem option, out string optionName, out string optionValue, out string optionDelimiter) { base.GetOptionInfo(option, out optionName, out optionValue, out optionDelimiter); if ((string.Compare(optionName, SuppressWarningOption, StringComparison.OrdinalIgnoreCase) == 0) && !string.IsNullOrWhiteSpace(optionValue)) { string[] warnings = optionValue.Split(','); StringBuilder validWarnings = new StringBuilder(); for (int i = 0; i < warnings.Length; i++) { string warning = warnings[i].Trim(); if (IsValidWarning(warning)) { if (validWarnings.Length == 0) { validWarnings.Append(warning); } else { validWarnings.AppendFormat(",{0}", warning); } } } optionValue = validWarnings.ToString(); if (string.IsNullOrWhiteSpace(optionValue)) { optionName = string.Empty; } } } protected abstract bool IsValidWarning(string warning); } class WhidbeyVBCompilerOptionsBuilder : VBCompilerOptionsBuilder { static HashSet<string> validWarnings = new HashSet<string>(StringComparer.Ordinal) { "40000", "40003", "40004", "40005", "40007", "40008", "40009", "40010", "40011", "40012", "40014", "40018", "40019", "40020", "40021", "40022", "40023", "40024", "40025", "40026", "40027", "40028", "40029", "40030", "40031", "40032", "40033", "40034", "40035", "40038", "40039", "40040", "40041", "40042", "40043", "40046", "40047", "40048", "40049", "40050", "40051", "40052", "40053", "40054", "40055", "40056", "40057", "41000", "41001", "41002", "41003", "41004", "41005", "41006", "41998", "41999", "42000", "42001", "42002", "42003", "42004", "42014", "42015", "42016", "42017", "42018", "42019", "42020", "42021", "42022", "42024", "42025", "42026", "42028", "42029", "42030", "42031", "42032", "42033", "42034", "42035", "42036", "42101", "42102", "42104", "42105", "42106", "42107", "42108", "42109", "42200", "42203", "42204", "42205", "42206", "42300", "42301", "42302", "42303", "42304", "42305", "42306", "42307", "42308", "42309", "42310", "42311", "42312", "42313", "42314", "42315", "42316", "42317", "42318", "42319", "42320", "42321" }; public WhidbeyVBCompilerOptionsBuilder() : base() { } protected override bool IsValidWarning(string warning) { return validWarnings.Contains(warning); } } class OrcasVBCompilerOptionsBuilder : VBCompilerOptionsBuilder { static HashSet<string> validWarnings = new HashSet<string>(StringComparer.Ordinal) { "40000", "40003", "40004", "40005", "40007", "40008", "40009", "40010", "40011", "40012", "40014", "40018", "40019", "40020", "40021", "40022", "40023", "40024", "40025", "40026", "40027", "40028", "40029", "40030", "40031", "40032", "40033", "40034", "40035", "40038", "40039", "40040", "40041", "40042", "40043", "40046", "40047", "40048", "40049", "40050", "40051", "40052", "40053", "40054", "40055", "40056", "40057", "41000", "41001", "41002", "41003", "41004", "41005", "41006", "41007", "41008", "41998", "41999", "42000", "42001", "42002", "42004", "42014", "42015", "42016", "42017", "42018", "42019", "42020", "42021", "42022", "42024", "42025", "42026", "42028", "42029", "42030", "42031", "42032", "42033", "42034", "42035", "42036", "42099", "42101", "42102", "42104", "42105", "42106", "42107", "42108", "42109", "42110", "42111", "42200", "42203", "42204", "42205", "42206", "42207", "42300", "42301", "42302", "42303", "42304", "42305", "42306", "42307", "42308", "42309", "42310", "42311", "42312", "42313", "42314", "42315", "42316", "42317", "42318", "42319", "42320", "42321", "42322", "42324", "42326", "42327", "42328" }; public OrcasVBCompilerOptionsBuilder() : base() { } protected override bool IsValidWarning(string warning) { return validWarnings.Contains(warning); } } } #endregion internal sealed class CreateWorkflowManifestResourceNameForCSharp : CreateCSharpManifestResourceName { private bool lastAskedFileWasXoml = false; [Output] public new ITaskItem[] ResourceFilesWithManifestResourceNames { get { for (int i = 0; i < base.ResourceFilesWithManifestResourceNames.Length; i++) { ITaskItem item = base.ResourceFilesWithManifestResourceNames[i]; item.SetMetadata("LogicalName", item.GetMetadata("ManifestResourceName")); } return base.ResourceFilesWithManifestResourceNames; } set { base.ResourceFilesWithManifestResourceNames = value; } } override protected string CreateManifestName(string fileName, string linkFileName, string rootNamespace, string dependentUponFileName, Stream binaryStream) { string manifestName = string.Empty; if (!this.lastAskedFileWasXoml) { manifestName = base.CreateManifestName(fileName, linkFileName, rootNamespace, dependentUponFileName, binaryStream); } else { manifestName = TasksHelper.GetXomlManifestName(fileName, linkFileName, rootNamespace, binaryStream); } string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".rules", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(extension, WorkflowDesignerLoader.DesignerLayoutFileExtension, StringComparison.OrdinalIgnoreCase) == 0) manifestName += extension; this.lastAskedFileWasXoml = false; return manifestName; } override protected bool IsSourceFile(string fileName) { string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".xoml", StringComparison.OrdinalIgnoreCase) == 0) { this.lastAskedFileWasXoml = true; return true; } return base.IsSourceFile(fileName); } } internal sealed class CreateWorkflowManifestResourceNameForVB : CreateVisualBasicManifestResourceName { private bool lastAskedFileWasXoml = false; override protected string CreateManifestName(string fileName, string linkFileName, string rootNamespace, string dependentUponFileName, Stream binaryStream) { string manifestName = string.Empty; if (!this.lastAskedFileWasXoml) { manifestName = base.CreateManifestName(fileName, linkFileName, rootNamespace, dependentUponFileName, binaryStream); } else { manifestName = TasksHelper.GetXomlManifestName(fileName, linkFileName, rootNamespace, binaryStream); } string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".rules", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(extension, WorkflowDesignerLoader.DesignerLayoutFileExtension, StringComparison.OrdinalIgnoreCase) == 0) manifestName += extension; this.lastAskedFileWasXoml = false; return manifestName; } override protected bool IsSourceFile(string fileName) { string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".xoml", StringComparison.OrdinalIgnoreCase) == 0) { this.lastAskedFileWasXoml = true; return true; } return base.IsSourceFile(fileName); } } internal static class TasksHelper { internal static string GetXomlManifestName(string fileName, string linkFileName, string rootNamespace, Stream binaryStream) { string manifestName = string.Empty; // Use the link file name if there is one, otherwise, fall back to file name. string embeddedFileName = linkFileName; if (embeddedFileName == null || embeddedFileName.Length == 0) embeddedFileName = fileName; Culture.ItemCultureInfo info = Culture.GetItemCultureInfo(embeddedFileName); if (binaryStream != null) { // Resource depends on a form. Now, get the form's class name fully // qualified with a namespace. string name = null; try { Xml.XmlTextReader reader = new Xml.XmlTextReader(binaryStream); if (reader.MoveToContent() == System.Xml.XmlNodeType.Element) { if (reader.MoveToAttribute("Class", StandardXomlKeys.Definitions_XmlNs)) name = reader.Value; } } catch { // ignore it for now } if (name != null && name.Length > 0) { manifestName = name; // Append the culture if there is one. if (info.culture != null && info.culture.Length > 0) { manifestName = manifestName + "." + info.culture; } } } // If there's no manifest name at this point, then fall back to using the // RootNamespace+Filename_with_slashes_converted_to_dots if (manifestName.Length == 0) { // If Rootnamespace was null, then it wasn't set from the project resourceFile. // Empty namespaces are allowed. if (!string.IsNullOrEmpty(rootNamespace)) manifestName = rootNamespace + "."; // Replace spaces in the directory name with underscores. Needed for compatibility with Everett. // Note that spaces in the file name itself are preserved. string everettCompatibleDirectoryName = CreateManifestResourceName.MakeValidEverettIdentifier(Path.GetDirectoryName(info.cultureNeutralFilename)); // only strip extension for .resx files if (0 == String.Compare(Path.GetExtension(info.cultureNeutralFilename), ".resx", StringComparison.OrdinalIgnoreCase)) { manifestName += Path.Combine(everettCompatibleDirectoryName, Path.GetFileNameWithoutExtension(info.cultureNeutralFilename)); // Replace all '\' with '.' manifestName = manifestName.Replace(Path.DirectorySeparatorChar, '.'); manifestName = manifestName.Replace(Path.AltDirectorySeparatorChar, '.'); // Append the culture if there is one. if (info.culture != null && info.culture.Length > 0) { manifestName = manifestName + "." + info.culture; } } else { manifestName += Path.Combine(everettCompatibleDirectoryName, Path.GetFileName(info.cultureNeutralFilename)); // Replace all '\' with '.' manifestName = manifestName.Replace(Path.DirectorySeparatorChar, '.'); manifestName = manifestName.Replace(Path.AltDirectorySeparatorChar, '.'); // Prepend the culture as a subdirectory if there is one. if (info.culture != null && info.culture.Length > 0) { manifestName = info.culture + Path.DirectorySeparatorChar + manifestName; } } } return manifestName; } } internal static class Culture { static private string[] cultureInfoStrings; internal struct ItemCultureInfo { internal string culture; internal string cultureNeutralFilename; }; internal static ItemCultureInfo GetItemCultureInfo(string name) { ItemCultureInfo info; info.culture = null; // If the item is defined as "Strings.en-US.resx", then ... // ... base file name will be "Strings.en-US" ... string baseFileNameWithCulture = Path.GetFileNameWithoutExtension(name); // ... and cultureName will be ".en-US". string cultureName = Path.GetExtension(baseFileNameWithCulture); // See if this is a valid culture name. bool validCulture = false; if ((cultureName != null) && (cultureName.Length > 1)) { // ... strip the "." to make "en-US" cultureName = cultureName.Substring(1); validCulture = IsValidCultureString(cultureName); } if (validCulture) { // A valid culture was found. if (info.culture == null || info.culture.Length == 0) { info.culture = cultureName; } // Copy the assigned file and make it culture-neutral string extension = Path.GetExtension(name); string baseFileName = Path.GetFileNameWithoutExtension(baseFileNameWithCulture); string baseFolder = Path.GetDirectoryName(name); string fileName = baseFileName + extension; info.cultureNeutralFilename = Path.Combine(baseFolder, fileName); } else { // No valid culture was found. In this case, the culture-neutral // name is the just the original file name. info.cultureNeutralFilename = name; } return info; } private static bool IsValidCultureString(string cultureString) { if (cultureInfoStrings == null) { CultureInfo[] cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures); cultureInfoStrings = new string[cultureInfos.Length]; for (int i = 0; i < cultureInfos.Length; i++) { cultureInfoStrings[i] = cultureInfos[i].ToString().ToLowerInvariant(); } Array.Sort(cultureInfoStrings); } bool valid = true; if (Array.BinarySearch(cultureInfoStrings, cultureString.ToLowerInvariant()) < 0) { valid = false; } return valid; } } #region Class CompileWorkflowCleanupTask // This cleanup task is a work-around for VB compilation only. // Due to a limitation for VB.Net, we can not delete the temp file. VB does back-ground compilation for // supporting intellisense. It re-compiles when there is a file change event that happens to each source // file. The temp file must be added to the OutputFiles collection in order for the compiler to pick it up. // This adds the temp file to the VB compiler project who would report an error if the file is deleted // when re-compilation happens in the back-ground. // However, if we don't delete the temp file, we have another problem. When we're in code-seperation mode, // we compile our xoml files on the fly and add the buffer that contains // the code generated based on the xoml to the project. This code conflicts with the code in the temp file, // thus causing all sorts of type conflicting errors. // Because the two reasons above, we wrote this cleanup task to keep the temp file but clear out the content // of the file, thus make it work for both cases. [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class CompileWorkflowCleanupTask : Microsoft.Build.Utilities.Task, ITask { #region Members and Constructors private ITaskItem[] temporaryFiles = null; public CompileWorkflowCleanupTask() : base(new ResourceManager("System.Workflow.ComponentModel.BuildTasksStrings", Assembly.GetExecutingAssembly())) { } #endregion #region Input parameters public ITaskItem[] TemporaryFiles { get { return this.temporaryFiles; } set { this.temporaryFiles = value; } } #endregion #region Public method overrides public override bool Execute() { if (this.temporaryFiles != null) { foreach (ITaskItem tempFileTask in this.temporaryFiles) { string tempFile = tempFileTask.ItemSpec; if (File.Exists(tempFile)) { FileStream fileStream = File.Open(tempFile, FileMode.Truncate); fileStream.Close(); } } } return true; } #endregion } #endregion }
using System; using System.Net.Sockets; using LavaLeak.Diplomata.Dictionaries; using LavaLeak.Diplomata.Helpers; using LavaLeak.Diplomata.Persistence; using LavaLeak.Diplomata.Persistence.Models; using UnityEngine; namespace LavaLeak.Diplomata.Models.Collections { /// <summary> /// The inventory class with all items and items categories. /// </summary> [Serializable] public class Inventory : Data { public Item[] items = new Item[0]; private int equipped = -1; [SerializeField] private string[] categories = new string[0]; /// <summary> /// All used categories in the items. /// </summary> /// <value>A array of categories.</value> public string[] Categories { get { return categories; } } /// <summary> /// Add a category to the categories array. /// </summary> /// <param name="category">The category to add.</param> public void AddCategory(string category) { if (category != "" && category != null) { if (categories == null) { categories = new string[0]; } if (!ArrayHelper.Contains(categories, category)) categories = ArrayHelper.Add(categories, category); RemoveNotUsedCategory(); } } /// <summary> /// Clean the categories array removing unused categories. /// </summary> public void RemoveNotUsedCategory() { foreach (var category in categories) { var itemsWithCategory = Find.In(items).Where("category", category).Results; if (itemsWithCategory.Length == 0) { categories = ArrayHelper.Remove(categories, category); } } } /// <summary> /// Return if the player has a equipped item. /// </summary> /// <returns>True if the player is equipped with something.</returns> public bool IsEquipped() { if (equipped == -1) { return false; } else { return true; } } /// <summary> /// Return if the player has a specific equipped item. /// </summary> /// <param name="id">The item id.</param> /// <returns>True if the player is equipped with this id.</returns> public bool IsEquipped(int id) { if (id == equipped) { return true; } else { return false; } } /// <summary> /// Get the equipped id. /// </summary> /// <returns>The item id.</returns> public int GetEquipped() { return equipped; } /// <summary> /// Equip a specific item. /// </summary> /// <param name="id">The item id.</param> public void Equip(int id) { for (int i = 0; i < items.Length; i++) { if (items[i].id == id) { equipped = id; break; } else if (i == items.Length - 1) { equipped = -1; } } } /// <summary> /// Equip a item by the name in a specific language. /// </summary> /// <param name="name">The item name.</param> /// <param name="language">The item name language.</param> public void Equip(string name, string language = "English") { foreach (Item item in items) { LanguageDictionary itemName = DictionariesHelper.ContainsKey(item.name, language); if (itemName.value == name && itemName != null) { Equip(item.id); break; } } if (equipped == -1) { Debug.LogError("Cannot find the item \"" + name + "\" in " + language + " in the inventory."); } } /// <summary> /// Unequip the player. /// </summary> public void UnEquip() { equipped = -1; } /// <summary> /// Set the items images and sprites. /// </summary> public void SetImagesAndSprites() { foreach (Item item in items) { item.SetImageAndSprite(); } } /// <summary> /// Generate a id for a new item without repeat the used ids. /// </summary> /// <returns>the new int id.</returns> public int GenerateId() { var usedIds = new int[0]; foreach (var item in items) usedIds = ArrayHelper.Add(usedIds, item.id); var id = items.Length; while (ArrayHelper.Contains(usedIds, id)) id++; return id; } /// <summary> /// Return the data of the object to save in a persistent object. /// </summary> /// <returns>A persistent object.</returns> public override Persistent GetData() { var inventory = new InventoryPersistent(); inventory.items = Data.GetArrayData<ItemPersistent>(items); return inventory; } /// <summary> /// Store in a object data from persistent object. /// </summary> /// <param name="persistentData">The persistent data object.</param> public override void SetData(Persistent persistentData) { var inventoryPersistent = (InventoryPersistent) persistentData; items = Data.SetArrayData<Item>(items, inventoryPersistent.items); } } }