context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Column.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using Gtk; using Hyena; using Hyena.Data; namespace Hyena.Data.Gui { public class Column : ColumnDescription, IEnumerable<ColumnCell> { private ColumnCell header_cell; private List<ColumnCell> cells = new List<ColumnCell> (); private int min_width = 0; private int max_width = Int32.MaxValue; public Column (ColumnDescription description) : this (description, new ColumnCellText (description.Property, true)) { } public Column (ColumnDescription description, ColumnCell cell) : this (description.Title, cell, description.Width, description.Visible) { } public Column (string title, ColumnCell cell, double width) : this (title, cell, width, true) { } public Column (string title, ColumnCell cell, double width, bool visible) : this (null, title, cell, width, visible) { } public Column (ColumnCell headerCell, string title, ColumnCell cell, double width) : this (headerCell, title, cell, width, true) { } public Column (ColumnCell headerCell, string title, ColumnCell cell, double width, bool visible) : this (headerCell, title, cell, width, visible, 0, Int32.MaxValue) { } public Column (ColumnCell headerCell, string title, ColumnCell cell, double width, bool visible, int minWidth, int maxWidth) : base (cell.ObjectBinder.Property, title, width, visible) { min_width = minWidth; max_width = maxWidth; header_cell = headerCell ?? new ColumnHeaderCellText (HeaderCellDataHandler); ColumnCellText header_text = header_cell as ColumnCellText; ColumnCellText cell_text = cell as ColumnCellText; if (header_text != null && cell_text != null) { header_text.Alignment = cell_text.Alignment; } PackStart (cell); } private Column HeaderCellDataHandler () { return this; } public void PackStart (ColumnCell cell) { cells.Insert (0, cell); } public void PackEnd (ColumnCell cell) { cells.Add (cell); } public ColumnCell GetCell (int index) { return cells[index]; } public void RemoveCell (int index) { cells.RemoveAt (index); } public void ClearCells () { cells.Clear (); } IEnumerator IEnumerable.GetEnumerator () { return cells.GetEnumerator (); } IEnumerator<ColumnCell> IEnumerable<ColumnCell>.GetEnumerator () { return cells.GetEnumerator (); } public ColumnCell HeaderCell { get { return header_cell; } set { header_cell = value; } } public void CalculateWidths (Pango.Layout layout, bool headerVisible, int headerHeight) { bool min_was_zero = MinWidth == 0; bool was_size_req = false; ISizeRequestCell sr_cell = cells[0] as ISizeRequestCell; if (sr_cell != null && sr_cell.RestrictSize) { int min_w, max_w; sr_cell.GetWidthRange (layout, out min_w, out max_w); MinWidth = min_w == -1 ? MinWidth : min_w; MaxWidth = max_w == -1 ? MaxWidth : max_w; was_size_req = true; } if (headerVisible && (min_was_zero || was_size_req) && !String.IsNullOrEmpty (Title)) { int w, h; layout.SetText (Title); //column_layout.SetText ("\u2026"); // ellipsis char layout.GetPixelSize (out w, out h); // Pretty sure the 3* is needed here only b/c of the " - 8" in ColumnCellText; // See TODO there w += 3 * (int)header_cell.Padding.Left; if (this is ISortableColumn) { w += ColumnHeaderCellText.GetArrowWidth (headerHeight); } MinWidth = Math.Max (MinWidth, w); // If the min/max are sufficiently close (arbitrarily choosen as < 8px) then // make them equal, so that the column doesn't appear resizable but in reality is on barely. if (MaxWidth - MinWidth < 8) { MinWidth = MaxWidth; } } } public int MinWidth { get { return min_width; } set { min_width = value; if (value > max_width) { max_width = value; } } } public int MaxWidth { get { return max_width; } set { max_width = value; if (value < min_width) { min_width = value; } } } private string id; public string Id { get { if (id == null) { id = GetCell (0).ObjectBinder.SubProperty ?? GetCell (0).ObjectBinder.Property; id = StringUtil.CamelCaseToUnderCase (id); } return id; } set { id = value; } } } }
// NameFilter.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 2010-03-03 Z-1654 Fixed bug where escape characters were excluded in SplitQuoted() using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace ICSharpCode.SharpZipLib.Core { /// <summary> /// NameFilter is a string matching class which allows for both positive and negative /// matching. /// A filter is a sequence of independant <see cref="Regex">regular expressions</see> separated by semi-colons ';'. /// To include a semi-colon it may be quoted as in \;. Each expression can be prefixed by a plus '+' sign or /// a minus '-' sign to denote the expression is intended to include or exclude names. /// If neither a plus or minus sign is found include is the default. /// A given name is tested for inclusion before checking exclusions. Only names matching an include spec /// and not matching an exclude spec are deemed to match the filter. /// An empty filter matches any name. /// </summary> /// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat' /// "+\.dat$;-^dummy\.dat$" /// </example> public class NameFilter : IScanFilter { #region Constructors /// <summary> /// Construct an instance based on the filter expression passed /// </summary> /// <param name="filter">The filter expression.</param> public NameFilter(string filter) { filter_ = filter; inclusions_ = new ArrayList(); exclusions_ = new ArrayList(); Compile(); } #endregion /// <summary> /// Test a string to see if it is a valid regular expression. /// </summary> /// <param name="expression">The expression to test.</param> /// <returns>True if expression is a valid <see cref="System.Text.RegularExpressions.Regex"/> false otherwise.</returns> public static bool IsValidExpression(string expression) { bool result = true; try { Regex exp = new Regex(expression, RegexOptions.IgnoreCase | RegexOptions.Singleline); result = exp != null; } catch (ArgumentException) { result = false; } return result; } /// <summary> /// Test an expression to see if it is valid as a filter. /// </summary> /// <param name="toTest">The filter expression to test.</param> /// <returns>True if the expression is valid, false otherwise.</returns> public static bool IsValidFilterExpression(string toTest) { bool result = true; try { if (toTest != null) { string[] items = SplitQuoted(toTest); for (int i = 0; i < items.Length; ++i) { if ((items[i] != null) && (items[i].Length > 0)) { string toCompile; if (items[i][0] == '+') { toCompile = items[i].Substring(1, items[i].Length - 1); } else if (items[i][0] == '-') { toCompile = items[i].Substring(1, items[i].Length - 1); } else { toCompile = items[i]; } Regex testRegex = new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Singleline); result = testRegex != null; } } } } catch (ArgumentException) { result = false; } return result; } /// <summary> /// Split a string into its component pieces /// </summary> /// <param name="original">The original string</param> /// <returns>Returns an array of <see cref="T:System.String"/> values containing the individual filter elements.</returns> public static string[] SplitQuoted(string original) { char escape = '\\'; char[] separators = { ';' }; ArrayList result = new ArrayList(); if ((original != null) && (original.Length > 0)) { int endIndex = -1; StringBuilder b = new StringBuilder(); while (endIndex < original.Length) { endIndex += 1; if (endIndex >= original.Length) { result.Add(b.ToString()); } else if (original[endIndex] == escape) { endIndex += 1; if (endIndex >= original.Length) { #if NETCF_1_0 || UNITY_WINRT throw new ArgumentException("Missing terminating escape character"); #else throw new ArgumentException("Missing terminating escape character", "original"); #endif } // include escape if this is not an escaped separator if (Array.IndexOf(separators, original[endIndex]) < 0) b.Append(escape); b.Append(original[endIndex]); } else { if (Array.IndexOf(separators, original[endIndex]) >= 0) { result.Add(b.ToString()); b.Length = 0; } else { b.Append(original[endIndex]); } } } } return (string[])result.ToArray(typeof(string)); } /// <summary> /// Convert this filter to its string equivalent. /// </summary> /// <returns>The string equivalent for this filter.</returns> public override string ToString() { return filter_; } /// <summary> /// Test a value to see if it is included by the filter. /// </summary> /// <param name="name">The value to test.</param> /// <returns>True if the value is included, false otherwise.</returns> public bool IsIncluded(string name) { bool result = false; if ( inclusions_.Count == 0 ) { result = true; } else { foreach ( Regex r in inclusions_ ) { if ( r.IsMatch(name) ) { result = true; break; } } } return result; } /// <summary> /// Test a value to see if it is excluded by the filter. /// </summary> /// <param name="name">The value to test.</param> /// <returns>True if the value is excluded, false otherwise.</returns> public bool IsExcluded(string name) { bool result = false; foreach ( Regex r in exclusions_ ) { if ( r.IsMatch(name) ) { result = true; break; } } return result; } #region IScanFilter Members /// <summary> /// Test a value to see if it matches the filter. /// </summary> /// <param name="name">The value to test.</param> /// <returns>True if the value matches, false otherwise.</returns> public bool IsMatch(string name) { return (IsIncluded(name) && !IsExcluded(name)); } #endregion /// <summary> /// Compile this filter. /// </summary> void Compile() { // TODO: Check to see if combining RE's makes it faster/smaller. // simple scheme would be to have one RE for inclusion and one for exclusion. if ( filter_ == null ) { return; } string[] items = SplitQuoted(filter_); for ( int i = 0; i < items.Length; ++i ) { if ( (items[i] != null) && (items[i].Length > 0) ) { bool include = (items[i][0] != '-'); string toCompile; if ( items[i][0] == '+' ) { toCompile = items[i].Substring(1, items[i].Length - 1); } else if ( items[i][0] == '-' ) { toCompile = items[i].Substring(1, items[i].Length - 1); } else { toCompile = items[i]; } // NOTE: Regular expressions can fail to compile here for a number of reasons that cause an exception // these are left unhandled here as the caller is responsible for ensuring all is valid. // several functions IsValidFilterExpression and IsValidExpression are provided for such checking if ( include ) { inclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | (RegexOptions)8 | RegexOptions.Singleline));//RegexOptions.Compiled = 8 } else { exclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | (RegexOptions)8 | RegexOptions.Singleline)); } } } } #region Instance Fields string filter_; ArrayList inclusions_; ArrayList exclusions_; #endregion } }
// // Misc.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Text; using Couchbase.Lite; using Couchbase.Lite.Util; using System.Collections; using System.Threading; using System.Threading.Tasks; namespace Couchbase.Lite { /// <summary> /// An event handler that sends a typed sender instead of object /// </summary> public delegate void TypedEventHandler<TSenderType, TArgType>(TSenderType sender, TArgType args); internal static class Misc { internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime OffsetFromEpoch(TimeSpan timeSinceEpoch) { return Epoch.Add(timeSinceEpoch); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, string tag, string message) { return CreateExceptionAndLog(domain, StatusCode.Exception, tag, message); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, StatusCode code, string tag, string message) { domain.E(tag, "{0}, throwing CouchbaseLiteException ({1})", message, code); return new CouchbaseLiteException(message, code); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, StatusCode code, string tag, string format, params object[] args) { var message = String.Format(format, args); return CreateExceptionAndLog(domain, code, tag, message); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, Exception inner, string tag, string message) { return CreateExceptionAndLog(domain, inner, StatusCode.Exception, tag, message); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, Exception inner, StatusCode code, string tag, string message) { domain.E(tag, String.Format("{0}, throwing CouchbaseLiteException", message), inner); return new CouchbaseLiteException(message, inner) { Code = code }; } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, Exception inner, string tag, string format, params object[] args) { var message = String.Format(format, args); return CreateExceptionAndLog(domain, inner, tag, message); } public static CouchbaseLiteException CreateExceptionAndLog(DomainLogger domain, Exception inner, StatusCode code, string tag, string format, params object[] args) { var message = String.Format(format, args); return CreateExceptionAndLog(domain, inner, code, tag, message); } public static IEnumerable<Exception> Flatten(Exception inE) { if (inE == null) { return new Exception[0]; } return new ExceptionEnumerable(inE); } public static Exception UnwrapAggregate(Exception inE) { if (inE == null) { return null; } var ae = inE as AggregateException; if (ae == null) { return inE; } return ae.Flatten().InnerException; } public static object KeyForPrefixMatch(object key, int depth) { if(depth < 1) { return key; } var keyStr = key as string; if (keyStr != null) { // Kludge: prefix match a string by appending max possible character value to it return keyStr + "\U0010FFFD"; } var keyList = key as IList; if (keyList != null) { var nuKey = new List<object>(); foreach (var entry in keyList) { nuKey.Add(entry); } if (depth == 1) { nuKey.Add(new Dictionary<string, object>()); } else { var lastObject = KeyForPrefixMatch(nuKey.Last(), depth - 1); nuKey[keyList.Count - 1] = lastObject; } return nuKey; } return key; } public static void SafeNull<T>(ref T obj, Action<T> action) where T : class { #if !__UNITY__ var copy = Interlocked.Exchange<T>(ref obj, null); #else var copy = obj; obj = null; #endif if (copy != null && action != null) { action(copy); } } public static void SafeDispose<T>(ref T obj, Action<T> action = null) where T : class, IDisposable { #if !__UNITY__ var tmp = Interlocked.Exchange<T>(ref obj, null); #else var tmp = obj; obj = null; #endif if (action != null) { action(tmp); } if (tmp != null) { tmp.Dispose(); } } public static string CreateGUID() { var sb = new StringBuilder(Convert.ToBase64String(Guid.NewGuid().ToByteArray()).TrimEnd('=')); // URL-safe character set per RFC 4648 sec. 5: sb.Replace('/', '_'); sb.Replace('+', '-'); // prefix a '-' to make it more clear where this string came from and prevent having a leading // '_' character: sb.Insert(0, '-'); return sb.ToString(); } public static string HexSHA1Digest(IEnumerable<Byte> input) { MessageDigest md; try { md = MessageDigest.GetInstance("SHA-1"); } catch (NotSupportedException) { Log.To.NoDomain.E("Misc", "SHA-1 digest is unavailable."); return null; } byte[] sha1hash; var inputArray = input.ToArray(); md.Update(inputArray, 0, inputArray.Count()); sha1hash = md.Digest(); return ConvertToHex(sha1hash); } public static string ConvertToHex(byte[] data, int numBytes = -1) { StringBuilder buf = new StringBuilder(); if (numBytes == -1) { numBytes = data.Length; } for (int i = 0; i < numBytes; i++) { int halfbyte = (data[i] >> 4) & unchecked((0x0F)); int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) { buf.Append((char)('0' + halfbyte)); } else { buf.Append((char)('a' + (halfbyte - 10))); } halfbyte = data[i] & unchecked((0x0F)); } while (two_halfs++ < 1); } return buf.ToString(); } public static int TDSequenceCompare(long a, long b, bool ascending = true) { long diff = ascending ? a - b : b - a; return diff > 0 ? 1 : (diff < 0 ? -1 : 0); } public static string UnquoteString(string param) { return param.Replace("\"", string.Empty); } public static bool IsUnauthorizedError(Exception e) { var ex = e as HttpResponseException; if(ex == null) { return false; } return ex.StatusCode == HttpStatusCode.Unauthorized || ex.StatusCode == HttpStatusCode.ProxyAuthenticationRequired; } /// <summary>Like equals, but works even if either/both are null</summary> /// <param name="obj1">object1 being compared</param> /// <param name="obj2">object2 being compared</param> /// <returns> /// true if both are non-null and obj1.equals(obj2), or true if both are null. /// otherwise return false. /// </returns> public static bool IsEqual(object obj1, object obj2) { if (obj1 != null) { return (obj2 != null) && obj1.Equals(obj2); } else { return obj2 == null; } } public static bool PropertiesEqual(IDictionary<string, object> prop1, IDictionary<string, object> prop2) { if (prop1 == null || prop2 == null) { return prop1 == prop2; } if (prop1.Count != prop2.Count) { return false; } foreach(var key in prop1.Keys) { if (!prop2.ContainsKey(key)) { return false; } object obj1 = prop1[key]; object obj2 = prop2[key]; bool isValueEqual; if (obj1 is IDictionary<string, object> && obj2 is IDictionary<string, object>) { isValueEqual = PropertiesEqual((IDictionary<string, object>)obj1, (IDictionary<string, object>)obj2); } else { isValueEqual = obj1.Equals(obj2); } if (!isValueEqual) { return false; } } return true; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Timers; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")] public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}"; private Scene m_scene = null; private int m_savetime = 5; // seconds to wait before saving changed appearance private int m_sendtime = 2; // seconds to wait before sending changed appearance private bool m_reusetextures = false; private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates private System.Timers.Timer m_updateTimer = new System.Timers.Timer(); private ThreadedClasses.RwLockedDictionary<UUID, long> m_savequeue = new ThreadedClasses.RwLockedDictionary<UUID, long>(); private ThreadedClasses.RwLockedDictionary<UUID, long> m_sendqueue = new ThreadedClasses.RwLockedDictionary<UUID, long>(); private object m_setAppearanceLock = new object(); #region Region Module interface public void Initialise(IConfigSource config) { IConfig appearanceConfig = config.Configs["Appearance"]; if (appearanceConfig != null) { m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime))); m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime))); m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures); // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime); } } public void AddRegion(Scene scene) { if (m_scene == null) m_scene = scene; scene.RegisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient += SubscribeToClientEvents; } public void RemoveRegion(Scene scene) { if (scene == m_scene) { scene.UnregisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient -= SubscribeToClientEvents; } m_scene = null; } public void RegionLoaded(Scene scene) { m_updateTimer.Enabled = false; m_updateTimer.AutoReset = true; m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer); } public void Close() { } public string Name { get { return "Default Avatar Factory"; } } public bool IsSharedModule { get { return false; } } public Type ReplaceableInterface { get { return null; } } private void SubscribeToClientEvents(IClientAPI client) { client.OnRequestWearables += Client_OnRequestWearables; client.OnSetAppearance += Client_OnSetAppearance; client.OnAvatarNowWearing += Client_OnAvatarNowWearing; client.OnCachedTextureRequest += Client_OnCachedTextureRequest; } #endregion #region IAvatarFactoryModule /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems) { SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems); } public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { float oldoff = sp.Appearance.AvatarFeetOffset; Vector3 oldbox = sp.Appearance.AvatarBoxSize; SetAppearance(sp, textureEntry, visualParams, cacheItems); sp.Appearance.SetSize(avSize); float off = sp.Appearance.AvatarFeetOffset; Vector3 box = sp.Appearance.AvatarBoxSize; if (oldoff != off || oldbox != box) ((ScenePresence)sp).SetSize(box, off); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems) { // m_log.DebugFormat( // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}", // sp.Name, textureEntry, visualParams); // TODO: This is probably not necessary any longer, just assume the // textureEntry set implies that the appearance transaction is complete bool changed = false; // Process the texture entry transactionally, this doesn't guarantee that Appearance is // going to be handled correctly but it does serialize the updates to the appearance lock (m_setAppearanceLock) { // Process the visual params, this may change height as well if (visualParams != null) { // string[] visualParamsStrings = new string[visualParams.Length]; // for (int i = 0; i < visualParams.Length; i++) // visualParamsStrings[i] = visualParams[i].ToString(); // m_log.DebugFormat( // "[AVFACTORY]: Setting visual params for {0} to {1}", // client.Name, string.Join(", ", visualParamsStrings)); /* float oldHeight = sp.Appearance.AvatarHeight; changed = sp.Appearance.SetVisualParams(visualParams); if (sp.Appearance.AvatarHeight != oldHeight && sp.Appearance.AvatarHeight > 0) ((ScenePresence)sp).SetHeight(sp.Appearance.AvatarHeight); */ // float oldoff = sp.Appearance.AvatarFeetOffset; // Vector3 oldbox = sp.Appearance.AvatarBoxSize; changed = sp.Appearance.SetVisualParams(visualParams); // float off = sp.Appearance.AvatarFeetOffset; // Vector3 box = sp.Appearance.AvatarBoxSize; // if(oldoff != off || oldbox != box) // ((ScenePresence)sp).SetSize(box,off); } // Process the baked texture array if (textureEntry != null) { m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID); // WriteBakedTexturesReport(sp, m_log.DebugFormat); changed = sp.Appearance.SetTextureEntries(textureEntry) || changed; // WriteBakedTexturesReport(sp, m_log.DebugFormat); // If bake textures are missing and this is not an NPC, request a rebake from client if (!ValidateBakedTextureCache(sp) && (((ScenePresence)sp).PresenceType != PresenceType.Npc)) RequestRebake(sp, true); // This appears to be set only in the final stage of the appearance // update transaction. In theory, we should be able to do an immediate // appearance send and save here. } // NPC should send to clients immediately and skip saving appearance if (((ScenePresence)sp).PresenceType == PresenceType.Npc) { SendAppearance((ScenePresence)sp); return; } // save only if there were changes, send no matter what (doesn't hurt to send twice) if (changed) QueueAppearanceSave(sp.ControllingClient.AgentId); QueueAppearanceSend(sp.ControllingClient.AgentId); } // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString()); } private void SendAppearance(ScenePresence sp) { // Send the appearance to everyone in the scene sp.SendAppearanceToAllOtherAgents(); // Send animations back to the avatar as well sp.Animator.SendAnimPack(); } public bool SendAppearance(UUID agentId) { // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId); ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId); return false; } SendAppearance(sp); return true; } public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); return GetBakedTextureFaces(sp); } public WearableCacheItem[] GetCachedItems(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); WearableCacheItem[] items = sp.Appearance.WearableCacheItems; //foreach (WearableCacheItem item in items) //{ //} return items; } public bool SaveBakedTextures(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return false; m_log.DebugFormat( "[AV FACTORY]: Permanently saving baked textures for {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp); if (bakedTextures.Count == 0) return false; foreach (BakeType bakeType in bakedTextures.Keys) { Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType]; if (bakedTextureFace == null) { // This can happen legitimately, since some baked textures might not exist //m_log.WarnFormat( // "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently", // bakeType, sp.Name, m_scene.RegionInfo.RegionName); continue; } AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString()); if (asset != null) { // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars asset.ID = asset.FullID.ToString(); asset.Temporary = false; asset.Local = false; m_scene.AssetService.Store(asset); } else { m_log.WarnFormat( "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently", bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName); } } return true; } /// <summary> /// Queue up a request to send appearance. /// </summary> /// <remarks> /// Makes it possible to accumulate changes without sending out each one separately. /// </remarks> /// <param name="agentId"></param> public void QueueAppearanceSend(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000); m_sendqueue[agentid] = timestamp; lock (m_updateTimer) { if ((m_sendqueue.Count != 0 || m_savequeue.Count != 0) && !m_updateTimer.Enabled) { m_updateTimer.Start(); } } } public void QueueAppearanceSave(UUID agentid) { //m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000); m_savequeue[agentid] = timestamp; lock (m_updateTimer) { if ((m_sendqueue.Count != 0 || m_savequeue.Count != 0) && !m_updateTimer.Enabled) { m_updateTimer.Start(); } } } public bool ValidateBakedTextureCache(IScenePresence sp) { bool defonly = true; // are we only using default textures IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); WearableCacheItem[] wearableCache = null; // Cache wearable data for teleport. // Only makes sense if there's a bake module and a cache module if (bakedModule != null && cache != null) { try { wearableCache = bakedModule.Get(sp.UUID); } catch (Exception) { } if (wearableCache != null) { for (int i = 0; i < wearableCache.Length; i++) { cache.Cache(wearableCache[i].TextureAsset); } } } /* IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); if (invService.GetRootFolder(userID) != null) { WearableCacheItem[] wearableCache = null; if (bakedModule != null) { try { wearableCache = bakedModule.Get(userID); appearance.WearableCacheItems = wearableCache; appearance.WearableCacheItemsDirty = false; foreach (WearableCacheItem item in wearableCache) { appearance.Texture.FaceTextures[item.TextureIndex].TextureID = item.TextureID; } } catch (Exception) { } } */ // Process the texture entry for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // No face, so lets check our baked service cache, teleport or login. if (face == null) { if (wearableCache != null) { // If we find the an appearance item, set it as the textureentry and the face WearableCacheItem searchitem = WearableCacheItem.SearchTextureIndex((uint) idx, wearableCache); if (searchitem != null) { sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx); sp.Appearance.Texture.FaceTextures[idx].TextureID = searchitem.TextureID; face = sp.Appearance.Texture.FaceTextures[idx]; } else { // if there is no texture entry and no baked cache, skip it continue; } } else { //No texture entry face and no cache. Skip this face. continue; } } // m_log.DebugFormat( // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}", // face.TextureID, idx, client.Name, client.AgentId); // if the texture is one of the "defaults" then skip it // this should probably be more intelligent (skirt texture doesnt matter // if the avatar isnt wearing a skirt) but if any of the main baked // textures is default then the rest should be as well if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; defonly = false; // found a non-default texture reference if (m_scene.AssetService.Get(face.TextureID.ToString()) == null) { m_log.WarnFormat("[AVFACTORY]: Missing baked texture {1} for appearance of {0}", sp.Name, face.TextureID); return false; } } // m_log.DebugFormat("[AVFACTORY]: Completed texture check for {0} {1}", sp.Name, sp.UUID); // If we only found default textures, then the appearance is not cached return (defonly ? false : true); } public int RequestRebake(IScenePresence sp, bool missingTexturesOnly) { int texturesRebaked = 0; // IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // if there is no texture entry, skip it if (face == null) continue; // m_log.DebugFormat( // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}", // face.TextureID, idx, client.Name, client.AgentId); // if the texture is one of the "defaults" then skip it // this should probably be more intelligent (skirt texture doesnt matter // if the avatar isnt wearing a skirt) but if any of the main baked // textures is default then the rest should be as well if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; if (missingTexturesOnly) { if (m_scene.AssetService.Get(face.TextureID.ToString()) != null) { continue; } else { // On inter-simulator teleports, this occurs if baked textures are not being stored by the // grid asset service (which means that they are not available to the new region and so have // to be re-requested from the client). // // The only available core OpenSimulator behaviour right now // is not to store these textures, temporarily or otherwise. m_log.DebugFormat( "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.", face.TextureID, idx, sp.Name); } } else { m_log.DebugFormat( "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.", face.TextureID, idx, sp.Name); } texturesRebaked++; sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } return texturesRebaked; } #endregion #region AvatarFactoryModule private methods private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp) { if (sp.IsChildAgent) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = new Dictionary<BakeType, Primitive.TextureEntryFace>(); AvatarAppearance appearance = sp.Appearance; Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures; foreach (int i in Enum.GetValues(typeof(BakeType))) { BakeType bakeType = (BakeType)i; if (bakeType == BakeType.Unknown) continue; // m_log.DebugFormat( // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}", // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType); Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture bakedTextures[bakeType] = texture; } return bakedTextures; } private void HandleAppearanceUpdateTimer(object sender, EventArgs ea) { long now = DateTime.Now.Ticks; KeyValuePair<UUID, long> removalKVP; while (m_sendqueue.FindRemoveIf(delegate(UUID avatarID, long sendTime) { return sendTime < now; }, out removalKVP)) { SendAppearance(removalKVP.Key); } while(m_savequeue.FindRemoveIf(delegate(UUID avatarID, long sendTime) { return sendTime < now; }, out removalKVP)) { SaveAppearance(removalKVP.Key); } // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread. lock (m_updateTimer) { if (m_savequeue.Count == 0 && m_sendqueue.Count == 0) m_updateTimer.Stop(); } } private void SaveAppearance(UUID agentid) { // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved // in a culture where decimal points are commas and then reloaded in a culture which just treats them as // number seperators. Culture.SetCurrentCulture(); ScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { // This is expected if the user has gone away. //m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid); return; } //m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid); // This could take awhile since it needs to pull inventory // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape // assets and item asset id changes to complete. // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids // multiple save requests. SetAppearanceAssets(sp.UUID, sp.Appearance); // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); // foreach (AvatarAttachment att in attachments) // { // m_log.DebugFormat( // "[AVFACTORY]: For {0} saving attachment {1} at point {2}", // sp.Name, att.ItemID, att.AttachPoint); // } m_scene.AvatarService.SetAppearance(agentid, sp.Appearance); // Trigger this here because it's the final step in the set/queue/save process for appearance setting. // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes). m_scene.EventManager.TriggerAvatarAppearanceChanged(sp); } /// <summary> /// For a given set of appearance items, check whether the items are valid and add their asset IDs to /// appearance data. /// </summary> /// <param name='userID'></param> /// <param name='appearance'></param> private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; if (invService.GetRootFolder(userID) != null) { for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { for (int j = 0; j < appearance.Wearables[i].Count; j++) { if (appearance.Wearables[i][j].ItemID == UUID.Zero) { m_log.WarnFormat( "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.", i, j, userID); continue; } // Ignore ruth's assets if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) continue; InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); baseItem = invService.GetItem(baseItem); if (baseItem != null) { appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); } else { m_log.WarnFormat( "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", appearance.Wearables[i][j].ItemID, (WearableType)i); appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID); } } } } else { m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); } // IInventoryService invService = m_scene.InventoryService; // bool resetwearable = false; // if (invService.GetRootFolder(userID) != null) // { // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) // { // for (int j = 0; j < appearance.Wearables[i].Count; j++) // { // // Check if the default wearables are not set // if (appearance.Wearables[i][j].ItemID == UUID.Zero) // { // switch ((WearableType) i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values."); // resetwearable = true; // break; // // } // continue; // } // // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1 // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) // { // switch ((WearableType)i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i); // resetwearable = true; // break; // // } // continue; // } // // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); // baseItem = invService.GetItem(baseItem); // // if (baseItem != null) // { // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); // int unmodifiedWearableIndexForClosure = i; // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this, // delegate(string x, object y, AssetBase z) // { // if (z == null) // { // TryAndRepairBrokenWearable( // (WearableType)unmodifiedWearableIndexForClosure, invService, // userID, appearance); // } // }); // } // else // { // m_log.ErrorFormat( // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", // appearance.Wearables[i][j].ItemID, (WearableType)i); // // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // // } // } // } // // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int) WearableType.Eyes] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes)); // // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}", // appearance.Wearables[(int) WearableType.Eyes][0].ItemID, // appearance.Wearables[(int) WearableType.Eyes][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Shape] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape)); // // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Shape][0].ItemID, // appearance.Wearables[(int)WearableType.Shape][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Hair] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair)); // // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Hair][0].ItemID, // appearance.Wearables[(int)WearableType.Hair][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Skin] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin)); // // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Skin][0].ItemID, // appearance.Wearables[(int)WearableType.Skin][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // // } // // } // if (resetwearable) // { // ScenePresence presence = null; // if (m_scene.TryGetScenePresence(userID, out presence)) // { // presence.ControllingClient.SendWearables(presence.Appearance.Wearables, // presence.Appearance.Serial++); // } // } // // } // else // { // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); // } } private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance) { UUID defaultwearable = GetDefaultItem(type); if (defaultwearable != UUID.Zero) { UUID newInvItem = UUID.Random(); InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID) { AssetID = defaultwearable, AssetType = (int) AssetType .Bodypart, CreatorId = userID .ToString (), //InvType = (int)InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService .GetFolderForType (userID, AssetType .Bodypart) .ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); UUID LinkInvItem = UUID.Random(); itembase = new InventoryItemBase(LinkInvItem, userID) { AssetID = newInvItem, AssetType = (int) AssetType .Link, CreatorId = userID .ToString (), InvType = (int) InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService .GetFolderForType (userID, AssetType .CurrentOutfitFolder) .ID, Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type), BasePermissions = (uint) PermissionMask.Copy, CurrentPermissions = (uint) PermissionMask.Copy, EveryOnePermissions = (uint) PermissionMask.Copy, GroupPermissions = (uint) PermissionMask.Copy, NextPermissions = (uint) PermissionMask.Copy }; invService.AddItem(itembase); appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type)); ScenePresence presence = null; if (m_scene.TryGetScenePresence(userID, out presence)) { m_scene.SendInventoryUpdate(presence.ControllingClient, invService.GetFolderForType(userID, AssetType .CurrentOutfitFolder), false, true); } } } private UUID GetDefaultItem(WearableType wearable) { // These are ruth UUID ret = UUID.Zero; switch (wearable) { case WearableType.Eyes: ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); break; case WearableType.Hair: ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); break; case WearableType.Pants: ret = new UUID("00000000-38f9-1111-024e-222222111120"); break; case WearableType.Shape: ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); break; case WearableType.Shirt: ret = new UUID("00000000-38f9-1111-024e-222222111110"); break; case WearableType.Skin: ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); break; case WearableType.Undershirt: ret = new UUID("16499ebb-3208-ec27-2def-481881728f47"); break; case WearableType.Underpants: ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d"); break; } return ret; } #endregion #region Client Event Handlers /// <summary> /// Tell the client for this scene presence what items it should be wearing now /// </summary> /// <param name="client"></param> private void Client_OnRequestWearables(IClientAPI client) { //m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId); Util.FireAndForget(delegate(object x) { Thread.Sleep(4000); // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++); else m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId); }); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) received from a client /// </summary> /// <param name="client"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { //m_log.DebugFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems); else m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId); } /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="client"></param> /// <param name="e"></param> private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e) { //m_log.DebugFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId); return; } // we need to clean out the existing textures sp.Appearance.ResetAppearance(); // operate on a copy of the appearance so we don't have to lock anything yet AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false); foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { if (wear.Type < AvatarWearable.MAX_WEARABLES) avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom(sp.Appearance); lock (m_setAppearanceLock) { // Update only those fields that we have changed. This is important because the viewer // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing // shouldn't overwrite the changes made in SetAppearance. sp.Appearance.Wearables = avatAppearance.Wearables; sp.Appearance.Texture = avatAppearance.Texture; } // We don't need to send the appearance here since the "iswearing" will trigger a new set // of visual param and baked texture changes. When those complete, the new appearance will be sent QueueAppearanceSave(client.AgentId); } /// <summary> /// Respond to the cached textures request from the client /// </summary> /// <param name="client"></param> /// <param name="serial"></param> /// <param name="cachedTextureRequest"></param> private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest) { //m_log.DebugFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>(); foreach (CachedTextureRequestArg request in cachedTextureRequest) { UUID texture = UUID.Zero; int index = request.BakedTextureIndex; if (m_reusetextures) { // this is the most insanely dumb way to do this... however it seems to // actually work. if the appearance has been reset because wearables have // changed then the texture entries are zero'd out until the bakes are // uploaded. on login, if the textures exist in the cache (eg if you logged // into the simulator recently, then the appearance will pull those and send // them back in the packet and you won't have to rebake. if the textures aren't // in the cache then the intial makeroot() call in scenepresence will zero // them out. // // a better solution (though how much better is an open question) is to // store the hashes in the appearance and compare them. Thats's coming. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index]; if (face != null) texture = face.TextureID; // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index); } CachedTextureResponseArg response = new CachedTextureResponseArg(); response.BakedTextureIndex = index; response.BakedTextureID = texture; response.HostName = null; cachedTextureResponse.Add(response); } // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial); // The serial number appears to be used to match requests and responses // in the texture transaction. We just send back the serial number // that was provided in the request. The viewer bumps this for us. client.SendCachedTextureResponse(sp, serial, cachedTextureResponse); } #endregion public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction) { outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID"); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID); foreach (BakeType bt in bakedTextures.Keys) { string rawTextureID; if (bakedTextures[bt] == null) { rawTextureID = "not set"; } else { rawTextureID = bakedTextures[bt].TextureID.ToString(); if (m_scene.AssetService.Get(rawTextureID) == null) rawTextureID += " (not found)"; else rawTextureID += " (uploaded)"; } outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID); } bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp); outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Commencement.Core.Domain; using Commencement.Tests.Core; using Commencement.Tests.Core.Extensions; using Commencement.Tests.Core.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentNHibernate.Testing; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using UCDArch.Testing.Extensions; namespace Commencement.Tests.Repositories { /// <summary> /// Entity Name: RegistrationPetition /// LookupFieldName: ExceptionReason /// </summary> [TestClass] public class RegistrationPetitionRepositoryTests : AbstractRepositoryTests<RegistrationPetition, int, RegistrationPetitionMap> { /// <summary> /// Gets or sets the RegistrationPetition repository. /// </summary> /// <value>The RegistrationPetition repository.</value> public IRepository<RegistrationPetition> RegistrationPetitionRepository { get; set; } public IRepositoryWithTypedId<State, string> StateRepository { get; set; } public IRepositoryWithTypedId<MajorCode, string> MajorCodeRepository { get; set; } #region Init and Overrides /// <summary> /// Initializes a new instance of the <see cref="RegistrationPetitionRepositoryTests"/> class. /// </summary> public RegistrationPetitionRepositoryTests() { RegistrationPetitionRepository = new Repository<RegistrationPetition>(); StateRepository = new RepositoryWithTypedId<State, string>(); MajorCodeRepository = new RepositoryWithTypedId<MajorCode, string>(); } /// <summary> /// Gets the valid entity of type T /// </summary> /// <param name="counter">The counter.</param> /// <returns>A valid entity of type T</returns> protected override RegistrationPetition GetValid(int? counter) { var rtValue = CreateValidEntities.RegistrationPetition(counter); rtValue.Registration = Repository.OfType<Registration>().Queryable.First(); rtValue.MajorCode = Repository.OfType<MajorCode>().Queryable.First(); return rtValue; } /// <summary> /// A Query which will return a single record /// </summary> /// <param name="numberAtEnd"></param> /// <returns></returns> protected override IQueryable<RegistrationPetition> GetQuery(int numberAtEnd) { return RegistrationPetitionRepository.Queryable.Where(a => a.ExceptionReason.EndsWith(numberAtEnd.ToString())); } /// <summary> /// A way to compare the entities that were read. /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment); /// </summary> /// <param name="entity"></param> /// <param name="counter"></param> protected override void FoundEntityComparison(RegistrationPetition entity, int counter) { Assert.AreEqual("ExceptionReason" + counter, entity.ExceptionReason); } /// <summary> /// Updates , compares, restores. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> protected override void UpdateUtility(RegistrationPetition entity, ARTAction action) { const string updateValue = "Updated"; switch (action) { case ARTAction.Compare: Assert.AreEqual(updateValue, entity.ExceptionReason); break; case ARTAction.Restore: entity.ExceptionReason = RestoreValue; break; case ARTAction.Update: RestoreValue = entity.ExceptionReason; entity.ExceptionReason = updateValue; break; } } /// <summary> /// Loads the data. /// </summary> protected override void LoadData() { Repository.OfType<Registration>().DbContext.BeginTransaction(); LoadMajorCode(3); LoadTermCode(1); LoadState(1); LoadCeremony(3); LoadStudent(1); LoadRegistrations(3); Repository.OfType<Registration>().DbContext.CommitTransaction(); RegistrationPetitionRepository.DbContext.BeginTransaction(); LoadRecords(5); RegistrationPetitionRepository.DbContext.CommitTransaction(); } #endregion Init and Overrides #region Registration Tests #region Invalid Tests /// <summary> /// Tests the Registration with A value of null does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestRegistrationWithAValueOfNullDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.Registration = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); Assert.AreEqual(registrationPetition.Registration, null); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("Registration: may not be null"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } [TestMethod] [ExpectedException(typeof(NHibernate.TransientObjectException))] public void TestRegistrationWithANewValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.Registration = CreateValidEntities.Registration(9); registrationPetition.Registration.State = StateRepository.Queryable.First(); registrationPetition.Registration.Student = Repository.OfType<Student>().Queryable.First(); registrationPetition.Registration.TermCode = Repository.OfType<TermCode>().Queryable.First(); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(registrationPetition); Assert.IsNotNull(ex); Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Registration, Entity: Commencement.Core.Domain.Registration", ex.Message); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestRegistrationWithExistingValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.Registration = Repository.OfType<Registration>().GetNullableById(2); Assert.IsNotNull(registrationPetition.Registration); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsNotNull(registrationPetition.Registration); Assert.AreEqual("Address12", registrationPetition.Registration.Address1); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion Valid Tests #region Cascade Tests [TestMethod] public void TestDeleteregistrationParticipationsDoesNotCascadeToRegistration() { #region Arrange var registration = Repository.OfType<Registration>().GetNullableById(2); Assert.IsNotNull(registration); var registrationPetition = GetValid(9); registrationPetition.Registration = registration; RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); var saveId = registrationPetition.Id; NHibernateSessionManager.Instance.GetSession().Evict(registration); NHibernateSessionManager.Instance.GetSession().Evict(registrationPetition); #endregion Arrange #region Act registrationPetition = RegistrationPetitionRepository.GetNullableById(saveId); Assert.IsNotNull(registrationPetition); RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.Remove(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); NHibernateSessionManager.Instance.GetSession().Evict(registration); #endregion Act #region Assert Assert.IsNull(RegistrationPetitionRepository.GetNullableById(saveId)); Assert.IsNotNull(Repository.OfType<Registration>().GetNullableById(2)); #endregion Assert } #endregion Cascade Tests #endregion Registration Tests #region Major Tests #region Invalid Tests /// <summary> /// Tests the Major with A value of null does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestMajorWithAValueOfNullDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.MajorCode = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); Assert.AreEqual(registrationPetition.MajorCode, null); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("MajorCode: may not be null"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } [TestMethod] [ExpectedException(typeof(NHibernate.TransientObjectException))] public void TestMajorWithANewValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.MajorCode = CreateValidEntities.MajorCode(9); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(registrationPetition); Assert.IsNotNull(ex); Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.MajorCode, Entity: Commencement.Core.Domain.MajorCode", ex.Message); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestMajorWithExistingMajorCodeSaves() { #region Arrange var major = MajorCodeRepository.GetNullableById("2"); Assert.IsNotNull(major); var registrationPetition = GetValid(9); registrationPetition.MajorCode = major; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsNotNull(registrationPetition.MajorCode); Assert.AreEqual("Name2", registrationPetition.MajorCode.Name); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion Valid Tests #region Cascade Tests [TestMethod] public void TestDeleteRegistrationParticipationsDoesNotCascadeToMajorCode() { #region Arrange var major = MajorCodeRepository.GetNullableById("2"); Assert.IsNotNull(major); var registrationPetition = GetValid(9); registrationPetition.MajorCode = major; RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); var saveId = registrationPetition.Id; NHibernateSessionManager.Instance.GetSession().Evict(major); NHibernateSessionManager.Instance.GetSession().Evict(registrationPetition); #endregion Arrange #region Act registrationPetition = RegistrationPetitionRepository.GetNullableById(saveId); Assert.IsNotNull(registrationPetition); RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.Remove(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); NHibernateSessionManager.Instance.GetSession().Evict(major); #endregion Act #region Assert Assert.IsNull(RegistrationPetitionRepository.GetNullableById(saveId)); Assert.IsNotNull(MajorCodeRepository.GetNullableById("2")); #endregion Assert } #endregion Cascade Tests #endregion Major Tests #region ExceptionReason Tests #region Invalid Tests /// <summary> /// Tests the ExceptionReason with null value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestExceptionReasonWithNullValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.ExceptionReason = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("ExceptionReason: may not be null or empty"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } /// <summary> /// Tests the ExceptionReason with empty string does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestExceptionReasonWithEmptyStringDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.ExceptionReason = string.Empty; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("ExceptionReason: may not be null or empty"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } /// <summary> /// Tests the ExceptionReason with spaces only does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestExceptionReasonWithSpacesOnlyDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.ExceptionReason = " "; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("ExceptionReason: may not be null or empty"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } /// <summary> /// Tests the ExceptionReason with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestExceptionReasonWithTooLongValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.ExceptionReason = "x".RepeatTimes((1000 + 1)); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); Assert.AreEqual(1000 + 1, registrationPetition.ExceptionReason.Length); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("ExceptionReason: length must be between 0 and 1000"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the ExceptionReason with one character saves. /// </summary> [TestMethod] public void TestExceptionReasonWithOneCharacterSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.ExceptionReason = "x"; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the ExceptionReason with long value saves. /// </summary> [TestMethod] public void TestExceptionReasonWithLongValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.ExceptionReason = "x".RepeatTimes(1000); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(1000, registrationPetition.ExceptionReason.Length); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion Valid Tests #endregion ExceptionReason Tests #region TermCodeComplete Tests #region Invalid Tests /// <summary> /// Tests the TermCodeComplete with A value of xxx does not save. /// </summary> [TestMethod] [ExpectedException(typeof(NHibernate.TransientObjectException))] public void TestTermCodeCompleteWithANewValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.TermCodeComplete = CreateValidEntities.vTermCode(3); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(registrationPetition); Assert.IsNotNull(ex); Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.vTermCode, Entity: Commencement.Core.Domain.vTermCode", ex.Message); throw; } } /// <summary> /// Tests the TermCodeComplete with A value of xxx does not save. /// </summary> [TestMethod] [ExpectedException(typeof(NHibernate.ADOException))] public void TestTermCodeCompleteWithASpecialTestValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange Repository.OfType<vTermCode>().DbContext.BeginTransaction(); LoadvTermCode(3); Repository.OfType<vTermCode>().DbContext.CommitTransaction(); registrationPetition = GetValid(9); registrationPetition.TermCodeComplete = Repository.OfType<vTermCode>().Queryable.First(); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(registrationPetition); Assert.IsNotNull(ex); Assert.IsTrue(ex.Message.Contains("FROM vTermCodes this_ WHERE ( this_.TypeCode='Q' and (this_.id like '%10' or this_.id like '%03')) limit 1]")); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestTermCodeCompleteWithNullValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TermCodeComplete = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsNull(registrationPetition.TermCodeComplete); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } //[TestMethod] //Can't test because there is a where clause on a database only field. //public void TestTermCodeCompleteWithExistingValueSaves() //{ // #region Arrange // Repository.OfType<vTermCode>().DbContext.BeginTransaction(); // LoadvTermCode(3); // Repository.OfType<vTermCode>().DbContext.CommitTransaction(); // var registrationPetition = GetValid(9); // registrationPetition.TermCodeComplete = Repository.OfType<vTermCode>().Queryable.First(); // #endregion Arrange // #region Act // RegistrationPetitionRepository.DbContext.BeginTransaction(); // RegistrationPetitionRepository.EnsurePersistent(registrationPetition); // RegistrationPetitionRepository.DbContext.CommitTransaction(); // #endregion Act // #region Assert // Assert.IsNotNull(registrationPetition.TermCodeComplete); // Assert.AreEqual("Description1", registrationPetition.TermCodeComplete.Description); // Assert.IsFalse(registrationPetition.IsTransient()); // Assert.IsTrue(registrationPetition.IsValid()); // #endregion Assert //} #endregion Valid Tests #region Cascade Tests //Can't test because there is a where clause on a database only field. #endregion Cascade Tests #endregion TermCodeComplete Tests #region TransferUnitsFrom Tests #region Invalid Tests /// <summary> /// Tests the TransferUnitsFrom with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestTransferUnitsFromWithTooLongValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = "x".RepeatTimes((100 + 1)); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); Assert.AreEqual(100 + 1, registrationPetition.TransferUnitsFrom.Length); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("TransferUnitsFrom: length must be between 0 and 100"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the TransferUnitsFrom with null value saves. /// </summary> [TestMethod] public void TestTransferUnitsFromWithNullValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnitsFrom with empty string saves. /// </summary> [TestMethod] public void TestTransferUnitsFromWithEmptyStringSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = string.Empty; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnitsFrom with one space saves. /// </summary> [TestMethod] public void TestTransferUnitsFromWithOneSpaceSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = " "; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnitsFrom with one character saves. /// </summary> [TestMethod] public void TestTransferUnitsFromWithOneCharacterSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = "x"; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnitsFrom with long value saves. /// </summary> [TestMethod] public void TestTransferUnitsFromWithLongValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnitsFrom = "x".RepeatTimes(100); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(100, registrationPetition.TransferUnitsFrom.Length); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion Valid Tests #endregion TransferUnitsFrom Tests #region TransferUnits Tests #region Invalid Tests /// <summary> /// Tests the TransferUnits with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestTransferUnitsWithTooLongValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.TransferUnits = "x".RepeatTimes((5 + 1)); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(registrationPetition); Assert.AreEqual(5 + 1, registrationPetition.TransferUnits.Length); var results = registrationPetition.ValidationResults().AsMessageList(); results.AssertErrorsAre("TransferUnits: length must be between 0 and 5"); Assert.IsTrue(registrationPetition.IsTransient()); Assert.IsFalse(registrationPetition.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the TransferUnits with null value saves. /// </summary> [TestMethod] public void TestTransferUnitsWithNullValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnits = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnits with empty string saves. /// </summary> [TestMethod] public void TestTransferUnitsWithEmptyStringSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnits = string.Empty; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnits with one space saves. /// </summary> [TestMethod] public void TestTransferUnitsWithOneSpaceSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnits = " "; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnits with one character saves. /// </summary> [TestMethod] public void TestTransferUnitsWithOneCharacterSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnits = "x"; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the TransferUnits with long value saves. /// </summary> [TestMethod] public void TestTransferUnitsWithLongValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.TransferUnits = "x".RepeatTimes(5); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(5, registrationPetition.TransferUnits.Length); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion Valid Tests #endregion TransferUnits Tests #region IsPending Tests /// <summary> /// Tests the IsPending is false saves. /// </summary> [TestMethod] public void TestIsPendingIsFalseSaves() { #region Arrange RegistrationPetition registrationPetition = GetValid(9); registrationPetition.IsPending = false; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsPending); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the IsPending is true saves. /// </summary> [TestMethod] public void TestIsPendingIsTrueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.IsPending = true; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsTrue(registrationPetition.IsPending); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion IsPending Tests #region IsApproved Tests /// <summary> /// Tests the IsApproved is false saves. /// </summary> [TestMethod] public void TestIsApprovedIsFalseSaves() { #region Arrange RegistrationPetition registrationPetition = GetValid(9); registrationPetition.IsApproved = false; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsApproved); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } /// <summary> /// Tests the IsApproved is true saves. /// </summary> [TestMethod] public void TestIsApprovedIsTrueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.IsApproved = true; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsTrue(registrationPetition.IsApproved); Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); #endregion Assert } #endregion IsApproved Tests #region DateSubmitted Tests /// <summary> /// Tests the DateSubmitted with past date will save. /// </summary> [TestMethod] public void TestDateSubmittedWithPastDateWillSave() { #region Arrange var compareDate = DateTime.Now.AddDays(-10); RegistrationPetition record = GetValid(99); record.DateSubmitted = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateSubmitted); #endregion Assert } /// <summary> /// Tests the DateSubmitted with current date date will save. /// </summary> [TestMethod] public void TestDateSubmittedWithCurrentDateDateWillSave() { #region Arrange var compareDate = DateTime.Now; var record = GetValid(99); record.DateSubmitted = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateSubmitted); #endregion Assert } /// <summary> /// Tests the DateSubmitted with future date date will save. /// </summary> [TestMethod] public void TestDateSubmittedWithFutureDateDateWillSave() { #region Arrange var compareDate = DateTime.Now.AddDays(15); var record = GetValid(99); record.DateSubmitted = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateSubmitted); #endregion Assert } #endregion DateSubmitted Tests #region DateDecision Tests [TestMethod] public void TestDateDecisionWithNullValueWillSave() { #region Arrange RegistrationPetition record = GetValid(99); record.DateDecision = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(null, record.DateDecision); #endregion Assert } /// <summary> /// Tests the DateDecision with past date will save. /// </summary> [TestMethod] public void TestDateDecisionWithPastDateWillSave() { #region Arrange var compareDate = DateTime.Now.AddDays(-10); RegistrationPetition record = GetValid(99); record.DateDecision = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateDecision); #endregion Assert } /// <summary> /// Tests the DateDecision with current date date will save. /// </summary> [TestMethod] public void TestDateDecisionWithCurrentDateDateWillSave() { #region Arrange var compareDate = DateTime.Now; var record = GetValid(99); record.DateDecision = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateDecision); #endregion Assert } /// <summary> /// Tests the DateDecision with future date date will save. /// </summary> [TestMethod] public void TestDateDecisionWithFutureDateDateWillSave() { #region Arrange var compareDate = DateTime.Now.AddDays(15); var record = GetValid(99); record.DateDecision = compareDate; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); Assert.AreEqual(compareDate, record.DateDecision); #endregion Assert } #endregion DateDecision Tests #region Ceremony Tests #region Invalid Tests /// <summary> /// Tests the Ceremony with A value of xxx does not save. /// </summary> [TestMethod] [ExpectedException(typeof(NHibernate.TransientObjectException))] public void TestCeremonyWithANewValueDoesNotSave() { RegistrationPetition registrationPetition = null; try { #region Arrange registrationPetition = GetValid(9); registrationPetition.Ceremony = CreateValidEntities.Ceremony(9); registrationPetition.Ceremony.TermCode = Repository.OfType<TermCode>().Queryable.First(); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(registrationPetition); Assert.IsNotNull(ex); Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Ceremony, Entity: Commencement.Core.Domain.Ceremony", ex.Message); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestCeremonyWithNullValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.Ceremony = null; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); Assert.IsNull(registrationPetition.Ceremony); #endregion Assert } [TestMethod] public void TestCeremonyWithExistingValueSaves() { #region Arrange var registrationPetition = GetValid(9); registrationPetition.Ceremony = Repository.OfType<Ceremony>().GetNullableById(2); Assert.IsNotNull(registrationPetition.Ceremony); #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert Assert.IsFalse(registrationPetition.IsTransient()); Assert.IsTrue(registrationPetition.IsValid()); Assert.IsNotNull(registrationPetition.Ceremony); #endregion Assert } #endregion Valid Tests #region Cascade Tests [TestMethod] public void TestDeleteRegistrationPetitionDoesNotCascadeToCeremony() { #region Arrange var registrationPetition = GetValid(9); var ceremony = Repository.OfType<Ceremony>().GetNullableById(2); registrationPetition.Ceremony = ceremony; Assert.IsNotNull(registrationPetition.Ceremony); RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(registrationPetition); RegistrationPetitionRepository.DbContext.CommitChanges(); var saveId = registrationPetition.Id; NHibernateSessionManager.Instance.GetSession().Evict(ceremony); NHibernateSessionManager.Instance.GetSession().Evict(registrationPetition); #endregion Arrange #region Act registrationPetition = RegistrationPetitionRepository.GetNullableById(saveId); RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.Remove(registrationPetition); RegistrationPetitionRepository.DbContext.CommitChanges(); #endregion Act #region Assert NHibernateSessionManager.Instance.GetSession().Evict(ceremony); Assert.IsNull(RegistrationPetitionRepository.GetNullableById(saveId)); Assert.IsNotNull(Repository.OfType<Ceremony>().GetNullableById(2)); #endregion Assert } #endregion Cascade Tests #endregion Ceremony Tests #region NumberTickets Tests /// <summary> /// Tests the NumberTickets with max int value saves. /// </summary> [TestMethod] public void TestNumberTicketsWithMaxIntValueSaves() { #region Arrange var record = GetValid(9); record.NumberTickets = int.MaxValue; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(int.MaxValue, record.NumberTickets); Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); #endregion Assert } /// <summary> /// Tests the NumberTickets with min int value saves. /// </summary> [TestMethod] public void TestNumberTicketsWithMinIntValueSaves() { #region Arrange var record = GetValid(9); record.NumberTickets = int.MinValue; #endregion Arrange #region Act RegistrationPetitionRepository.DbContext.BeginTransaction(); RegistrationPetitionRepository.EnsurePersistent(record); RegistrationPetitionRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(int.MinValue, record.NumberTickets); Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); #endregion Assert } #endregion NumberTickets Tests #region Status Tests [TestMethod] public void TestStatusReturnsExpectedResult1() { #region Arrange var record = CreateValidEntities.RegistrationPetition(9); record.IsPending = true; record.IsApproved = false; #endregion Arrange #region Act var result = record.Status; #endregion Act #region Assert Assert.AreEqual("Pending", result); #endregion Assert } [TestMethod] public void TestStatusReturnsExpectedResult2() { #region Arrange var record = CreateValidEntities.RegistrationPetition(9); record.IsPending = true; record.IsApproved = true; #endregion Arrange #region Act var result = record.Status; #endregion Act #region Assert Assert.AreEqual("Pending", result); #endregion Assert } [TestMethod] public void TestStatusReturnsExpectedResult3() { #region Arrange var record = CreateValidEntities.RegistrationPetition(9); record.IsPending = false; record.IsApproved = false; #endregion Arrange #region Act var result = record.Status; #endregion Act #region Assert Assert.AreEqual("Denied", result); #endregion Assert } [TestMethod] public void TestStatusReturnsExpectedResult4() { #region Arrange var record = CreateValidEntities.RegistrationPetition(9); record.IsPending = false; record.IsApproved = true; #endregion Arrange #region Act var result = record.Status; #endregion Act #region Assert Assert.AreEqual("Approved", result); #endregion Assert } #endregion Status Tests #region Constructor Tests [TestMethod] public void TestConstructorWithNoParametersSetsExpectedValues() { #region Arrange var record = new RegistrationPetition(); #endregion Arrange #region Assert Assert.AreEqual(DateTime.Now.Date, record.DateSubmitted.Date); Assert.IsTrue(record.IsPending); Assert.IsFalse(record.IsApproved); Assert.IsNull(record.DateDecision); #endregion Assert } [TestMethod] public void TestConstructorWithParametersSetsExpectedValues() { #region Arrange var record = new RegistrationPetition(CreateValidEntities.Registration(9), CreateValidEntities.MajorCode(8), CreateValidEntities.Ceremony(7), "Because I said So!", CreateValidEntities.vTermCode(6), 5); #endregion Arrange #region Assert Assert.AreEqual(DateTime.Now.Date, record.DateSubmitted.Date); Assert.IsTrue(record.IsPending); Assert.IsFalse(record.IsApproved); Assert.IsNull(record.DateDecision); Assert.AreEqual("Address19", record.Registration.Address1); Assert.AreEqual("Name8", record.MajorCode.Name); Assert.AreEqual("Location7", record.Ceremony.Location); Assert.AreEqual("Because I said So!", record.ExceptionReason); Assert.AreEqual("Description6", record.TermCodeComplete.Description); Assert.AreEqual(5, record.NumberTickets); #endregion Assert } #endregion Constructor Tests #region Fluent Mapping Tests [TestMethod] public void TestCanCorrectlyMapRegistrationPetition1() { #region Arrange var id = RegistrationPetitionRepository.Queryable.Max(a => a.Id) + 1; var session = NHibernateSessionManager.Instance.GetSession(); var dateToCheck1 = new DateTime(2010, 01, 01); var dateToCheck2 = new DateTime(2010, 01, 02); #endregion Arrange #region Act/Assert new PersistenceSpecification<RegistrationPetition>(session) .CheckProperty(c => c.Id, id) .CheckProperty(c => c.ExceptionReason, "Some Reason") .CheckProperty(c => c.TransferUnitsFrom, "FUnit") .CheckProperty(c => c.TransferUnits, "Units") .CheckProperty(c => c.IsPending, true) .CheckProperty(c => c.IsApproved, true) .CheckProperty(c => c.DateSubmitted, dateToCheck1) .CheckProperty(c => c.DateDecision, dateToCheck2) .CheckProperty(c => c.NumberTickets, 5) .VerifyTheMappings(); #endregion Act/Assert } [TestMethod] public void TestCanCorrectlyMapRegistrationPetition2() { #region Arrange var id = RegistrationPetitionRepository.Queryable.Max(a => a.Id) + 1; var session = NHibernateSessionManager.Instance.GetSession(); var dateToCheck1 = new DateTime(2010, 01, 01); #endregion Arrange #region Act/Assert new PersistenceSpecification<RegistrationPetition>(session) .CheckProperty(c => c.Id, id) .CheckProperty(c => c.ExceptionReason, "Some Reason") .CheckProperty(c => c.TransferUnitsFrom, "FUnit") .CheckProperty(c => c.TransferUnits, "Units") .CheckProperty(c => c.IsPending, false) .CheckProperty(c => c.IsApproved, false) .CheckProperty(c => c.DateSubmitted, dateToCheck1) .CheckProperty(c => c.DateDecision, null) .CheckProperty(c => c.NumberTickets, 5) .VerifyTheMappings(); #endregion Act/Assert } [TestMethod] public void TestCanCorrectlyMapRegistrationPetition3() { #region Arrange var id = RegistrationPetitionRepository.Queryable.Max(a => a.Id) + 1; var session = NHibernateSessionManager.Instance.GetSession(); var registration = Repository.OfType<Registration>().Queryable.First(); var major = Repository.OfType<MajorCode>().Queryable.First(); var ceremony = Repository.OfType<Ceremony>().Queryable.First(); #endregion Arrange #region Act/Assert new PersistenceSpecification<RegistrationPetition>(session) .CheckProperty(c => c.Id, id) .CheckReference(c => c.Registration, registration) .CheckReference(c => c.MajorCode, major) .CheckReference(c => c.Ceremony, ceremony) .VerifyTheMappings(); #endregion Act/Assert } #endregion Fluent Mapping Tests #region Reflection of Database. /// <summary> /// Tests all fields in the database have been tested. /// If this fails and no other tests, it means that a field has been added which has not been tested above. /// </summary> [TestMethod] public void TestAllFieldsInTheDatabaseHaveBeenTested() { #region Arrange var expectedFields = new List<NameAndType>(); expectedFields.Add(new NameAndType("Ceremony", "Commencement.Core.Domain.Ceremony", new List<string>())); expectedFields.Add(new NameAndType("DateDecision", "System.Nullable`1[System.DateTime]", new List<string>())); expectedFields.Add(new NameAndType("DateSubmitted", "System.DateTime", new List<string>())); expectedFields.Add(new NameAndType("ExceptionReason", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)1000)]", "[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]" })); expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string> { "[Newtonsoft.Json.JsonPropertyAttribute()]", "[System.Xml.Serialization.XmlIgnoreAttribute()]" })); expectedFields.Add(new NameAndType("IsApproved", "System.Boolean", new List<string>())); expectedFields.Add(new NameAndType("IsPending", "System.Boolean", new List<string>())); expectedFields.Add(new NameAndType("MajorCode", "Commencement.Core.Domain.MajorCode", new List<string> { "[NHibernate.Validator.Constraints.NotNullAttribute()]" })); expectedFields.Add(new NameAndType("NumberTickets", "System.Int32", new List<string>())); expectedFields.Add(new NameAndType("Registration", "Commencement.Core.Domain.Registration", new List<string> { "[NHibernate.Validator.Constraints.NotNullAttribute()]" })); expectedFields.Add(new NameAndType("Status", "System.String", new List<string>())); expectedFields.Add(new NameAndType("TermCodeComplete", "Commencement.Core.Domain.vTermCode", new List<string>())); expectedFields.Add(new NameAndType("TransferUnits", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)5)]" })); expectedFields.Add(new NameAndType("TransferUnitsFrom", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)100)]" })); #endregion Arrange AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(RegistrationPetition)); } #endregion Reflection of Database. } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Win32; namespace TestUtilities { public class PythonPaths { private static readonly List<PythonInterpreterInformation> _foundInRegistry = PythonRegistrySearch .PerformDefaultSearch() .Where(pii => pii.Configuration.Id.Contains("PythonCore|")) .ToList(); public static readonly PythonVersion Python25 = GetCPythonVersion(PythonLanguageVersion.V25, InterpreterArchitecture.x86); public static readonly PythonVersion Python26 = GetCPythonVersion(PythonLanguageVersion.V26, InterpreterArchitecture.x86); public static readonly PythonVersion Python27 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x86); public static readonly PythonVersion Python30 = GetCPythonVersion(PythonLanguageVersion.V30, InterpreterArchitecture.x86); public static readonly PythonVersion Python31 = GetCPythonVersion(PythonLanguageVersion.V31, InterpreterArchitecture.x86); public static readonly PythonVersion Python32 = GetCPythonVersion(PythonLanguageVersion.V32, InterpreterArchitecture.x86); public static readonly PythonVersion Python33 = GetCPythonVersion(PythonLanguageVersion.V33, InterpreterArchitecture.x86); public static readonly PythonVersion Python34 = GetCPythonVersion(PythonLanguageVersion.V34, InterpreterArchitecture.x86); public static readonly PythonVersion Python35 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x86); public static readonly PythonVersion Python36 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x86); public static readonly PythonVersion IronPython27 = GetIronPythonVersion(false); public static readonly PythonVersion Python25_x64 = GetCPythonVersion(PythonLanguageVersion.V25, InterpreterArchitecture.x64); public static readonly PythonVersion Python26_x64 = GetCPythonVersion(PythonLanguageVersion.V26, InterpreterArchitecture.x64); public static readonly PythonVersion Python27_x64 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x64); public static readonly PythonVersion Python30_x64 = GetCPythonVersion(PythonLanguageVersion.V30, InterpreterArchitecture.x64); public static readonly PythonVersion Python31_x64 = GetCPythonVersion(PythonLanguageVersion.V31, InterpreterArchitecture.x64); public static readonly PythonVersion Python32_x64 = GetCPythonVersion(PythonLanguageVersion.V32, InterpreterArchitecture.x64); public static readonly PythonVersion Python33_x64 = GetCPythonVersion(PythonLanguageVersion.V33, InterpreterArchitecture.x64); public static readonly PythonVersion Python34_x64 = GetCPythonVersion(PythonLanguageVersion.V34, InterpreterArchitecture.x64); public static readonly PythonVersion Python35_x64 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x64); public static readonly PythonVersion Python36_x64 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x64); public static readonly PythonVersion IronPython27_x64 = GetIronPythonVersion(true); public static readonly PythonVersion Jython27 = GetJythonVersion(PythonLanguageVersion.V27); private static PythonVersion GetIronPythonVersion(bool x64) { var exeName = x64 ? "ipy64.exe" : "ipy.exe"; using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) { if (ipy != null) { using (var twoSeven = ipy.OpenSubKey("2.7")) { if (twoSeven != null) { var installPath = twoSeven.OpenSubKey("InstallPath"); if (installPath != null) { var res = installPath.GetValue("") as string; if (res != null) { return new PythonVersion( new InterpreterConfiguration( x64 ? "IronPython|2.7-64" : "IronPython|2.7-32", string.Format("IronPython {0} 2.7", x64 ? "64-bit" : "32-bit"), res, Path.Combine(res, exeName), arch: x64 ? InterpreterArchitecture.x64 : InterpreterArchitecture.x86, version: new Version(2, 7), pathVar: "IRONPYTHONPATH" ), ironPython: true ); } } } } } } var ver = new PythonVersion(new InterpreterConfiguration( "IronPython|2.7-32", "IronPython 32-bit 2.7", "C:\\Program Files (x86)\\IronPython 2.7\\", "C:\\Program Files (x86)\\IronPython 2.7\\" + exeName, arch: InterpreterArchitecture.x86, version: new Version(2, 7), pathVar: "IRONPYTHONPATH" ), ironPython: true); if (File.Exists(ver.InterpreterPath)) { return ver; } return null; } private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, InterpreterArchitecture arch) { var res = _foundInRegistry.FirstOrDefault(ii => ii.Configuration.Id.StartsWith("Global|PythonCore|") && ii.Configuration.Architecture == arch && ii.Configuration.Version == version.ToVersion() ); if (res != null) { return new PythonVersion(res.Configuration, cPython: true); } var ver = version.ToVersion(); var tag = ver + (arch == InterpreterArchitecture.x86 ? "-32" : ""); foreach (var path in new[] { string.Format("Python{0}{1}", ver.Major, ver.Minor), string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("x")), string.Format("Python{0}{1}-{2}", ver.Major, ver.Minor, arch.ToString("#")), string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("#")), }) { var prefixPath = Path.Combine(Environment.GetEnvironmentVariable("SystemDrive"), "\\", path); var exePath = Path.Combine(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable); var procArch = (arch == InterpreterArchitecture.x86) ? ProcessorArchitecture.X86 : (arch == InterpreterArchitecture.x64) ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.None; if (procArch == Microsoft.PythonTools.Infrastructure.NativeMethods.GetBinaryType(path)) { return new PythonVersion(new InterpreterConfiguration( CPythonInterpreterFactoryConstants.GetInterpreterId("PythonCore", tag), "Python {0} {1}".FormatInvariant(arch, ver), prefixPath, exePath, pathVar: CPythonInterpreterFactoryConstants.PathEnvironmentVariableName, arch: arch, version: ver )); } } return null; } private static PythonVersion GetJythonVersion(PythonLanguageVersion version) { var candidates = new List<DirectoryInfo>(); var ver = version.ToVersion(); var path1 = string.Format("jython{0}{1}*", ver.Major, ver.Minor); var path2 = string.Format("jython{0}.{1}*", ver.Major, ver.Minor); foreach (var drive in DriveInfo.GetDrives()) { if (drive.DriveType != DriveType.Fixed) { continue; } try { candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path1)); candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path2)); } catch { } } foreach (var dir in candidates) { var interpreter = dir.EnumerateFiles("jython.bat").FirstOrDefault(); if (interpreter == null) { continue; } var libPath = dir.EnumerateDirectories("Lib").FirstOrDefault(); if (libPath == null || !libPath.EnumerateFiles("site.py").Any()) { continue; } return new PythonVersion(new InterpreterConfiguration( CPythonInterpreterFactoryConstants.GetInterpreterId( "Jython", version.ToVersion().ToString() ), string.Format("Jython {0}", version.ToVersion()), dir.FullName, interpreter.FullName, version: version.ToVersion() )); } return null; } public static IEnumerable<PythonVersion> Versions { get { if (Python25 != null) yield return Python25; if (Python26 != null) yield return Python26; if (Python27 != null) yield return Python27; if (Python30 != null) yield return Python30; if (Python31 != null) yield return Python31; if (Python32 != null) yield return Python32; if (Python33 != null) yield return Python33; if (Python34 != null) yield return Python34; if (Python35 != null) yield return Python35; if (Python36 != null) yield return Python36; if (IronPython27 != null) yield return IronPython27; if (Python25_x64 != null) yield return Python25_x64; if (Python26_x64 != null) yield return Python26_x64; if (Python27_x64 != null) yield return Python27_x64; if (Python30_x64 != null) yield return Python30_x64; if (Python31_x64 != null) yield return Python31_x64; if (Python32_x64 != null) yield return Python32_x64; if (Python33_x64 != null) yield return Python33_x64; if (Python34_x64 != null) yield return Python34_x64; if (Python35_x64 != null) yield return Python35_x64; if (Python36_x64 != null) yield return Python36_x64; if (IronPython27_x64 != null) yield return IronPython27_x64; if (Jython27 != null) yield return Jython27; } } } public class PythonVersion { public readonly InterpreterConfiguration Configuration; public readonly bool IsCPython; public readonly bool IsIronPython; public PythonVersion(InterpreterConfiguration config, bool ironPython = false, bool cPython = false) { Configuration = config; IsCPython = cPython; IsIronPython = ironPython; } public override string ToString() => Configuration.Description; public string PrefixPath => Configuration.PrefixPath; public string InterpreterPath => Configuration.InterpreterPath; public PythonLanguageVersion Version => Configuration.Version.ToLanguageVersion(); public string Id => Configuration.Id; public bool Isx64 => Configuration.Architecture == InterpreterArchitecture.x64; public InterpreterArchitecture Architecture => Configuration.Architecture; } public static class PythonVersionExtensions { public static void AssertInstalled(this PythonVersion self) { if(self == null || !File.Exists(self.InterpreterPath)) { Assert.Inconclusive("Python interpreter not installed"); } } } }
using J2N; using J2N.Text; using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Some of this code came from the excellent Unicode * conversion examples from: * * http://www.unicode.org/Public/PROGRAMS/CVTUTF * * Full Copyright for that code follows: */ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * this source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute this Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* * Additional code came from the IBM ICU library. * * http://www.icu-project.org * * Full Copyright for that code follows. */ /* * Copyright (C) 1999-2010, International Business Machines * Corporation and others. All Rights Reserved. * * 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, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * provided that the above copyright notice(s) and this permission notice appear * in all copies of the Software and that both the above copyright notice(s) and * this permission notice appear in supporting documentation. * * 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 OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN this NOTICE BE * LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF this SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization of the * copyright holder. */ /// <summary> /// Class to encode .NET's UTF16 <see cref="T:char[]"/> into UTF8 <see cref="T:byte[]"/> /// without always allocating a new <see cref="T:byte[]"/> as /// <see cref="Encoding.GetBytes(string)"/> of <see cref="Encoding.UTF8"/> does. /// <para/> /// @lucene.internal /// </summary> public static class UnicodeUtil { /// <summary> /// A binary term consisting of a number of 0xff bytes, likely to be bigger than other terms /// (e.g. collation keys) one would normally encounter, and definitely bigger than any UTF-8 terms. /// <para/> /// WARNING: this is not a valid UTF8 Term /// </summary> public static readonly BytesRef BIG_TERM = new BytesRef(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }); // TODO this is unrelated here find a better place for it public const int UNI_SUR_HIGH_START = 0xD800; public const int UNI_SUR_HIGH_END = 0xDBFF; public const int UNI_SUR_LOW_START = 0xDC00; public const int UNI_SUR_LOW_END = 0xDFFF; public const int UNI_REPLACEMENT_CHAR = 0xFFFD; private const long UNI_MAX_BMP = 0x0000FFFF; private const long HALF_SHIFT = 10; private const long HALF_MASK = 0x3FFL; private const int SURROGATE_OFFSET = Character.MinSupplementaryCodePoint - (UNI_SUR_HIGH_START << (int)HALF_SHIFT) - UNI_SUR_LOW_START; /// <summary> /// Encode characters from a <see cref="T:char[]"/> <paramref name="source"/>, starting at /// <paramref name="offset"/> for <paramref name="length"/> chars. After encoding, <c>result.Offset</c> will always be 0. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(char[] source, int offset, int length, BytesRef result) { int upto = 0; int i = offset; int end = offset + length; var @out = result.Bytes; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } result.Offset = 0; while (i < end) { int code = (int)source[i++]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && i < end) { var utf32 = (int)source[i]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(source, offset, length, out, upto); result.Length = upto; } /// <summary> /// Encode characters from this <see cref="ICharSequence"/>, starting at <paramref name="offset"/> /// for <paramref name="length"/> characters. After encoding, <c>result.Offset</c> will always be 0. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(ICharSequence s, int offset, int length, BytesRef result) { int end = offset + length; var @out = result.Bytes; result.Offset = 0; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } int upto = 0; for (int i = offset; i < end; i++) { var code = (int)s[i]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end - 1)) { int utf32 = (int)s[i + 1]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(s, offset, length, out, upto); result.Length = upto; } /// <summary> /// Encode characters from this <see cref="string"/>, starting at <paramref name="offset"/> /// for <paramref name="length"/> characters. After encoding, <c>result.Offset</c> will always be 0. /// <para/> /// LUCENENET specific. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(string s, int offset, int length, BytesRef result) { int end = offset + length; var @out = result.Bytes; result.Offset = 0; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } int upto = 0; for (int i = offset; i < end; i++) { var code = (int)s[i]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end - 1)) { int utf32 = (int)s[i + 1]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(s, offset, length, out, upto); result.Length = upto; } // Only called from assert /* private static boolean matches(char[] source, int offset, int length, byte[] result, int upto) { try { String s1 = new String(source, offset, length); String s2 = new String(result, 0, upto, StandardCharsets.UTF_8); if (!s1.equals(s2, StringComparison.Ordinal)) { //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println("s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2, StringComparison.Ordinal); } catch (UnsupportedEncodingException uee) { return false; } } // Only called from assert private static boolean matches(String source, int offset, int length, byte[] result, int upto) { try { String s1 = source.substring(offset, offset+length); String s2 = new String(result, 0, upto, StandardCharsets.UTF_8); if (!s1.equals(s2, StringComparison.Ordinal)) { // Allow a difference if s1 is not valid UTF-16 //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println(" s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2, StringComparison.Ordinal); } catch (UnsupportedEncodingException uee) { return false; } } */ public static bool ValidUTF16String(ICharSequence s) { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(string s) // LUCENENET specific overload because string doesn't implement ICharSequence { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(StringBuilder s) // LUCENENET specific overload because StringBuilder doesn't implement ICharSequence { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(char[] s, int size) { for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else { return false; } } else { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } // Borrowed from Python's 3.1.2 sources, // Objects/unicodeobject.c, and modified (see commented // out section, and the -1s) to disallow the reserved for // future (RFC 3629) 5/6 byte sequence characters, and // invalid 0xFE and 0xFF bytes. /* Map UTF-8 encoded prefix byte to sequence length. -1 (0xFF) * means illegal prefix. see RFC 2279 for details */ internal static readonly int[] utf8CodeLength = LoadUTF8CodeLength(); private static int[] LoadUTF8CodeLength() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { int v = int.MinValue; return new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 }; } /// <summary> /// Returns the number of code points in this UTF8 sequence. /// /// <para/>This method assumes valid UTF8 input. This method /// <b>does not perform</b> full UTF8 validation, it will check only the /// first byte of each codepoint (for multi-byte sequences any bytes after /// the head are skipped). /// </summary> /// <exception cref="ArgumentException"> If invalid codepoint header byte occurs or the /// content is prematurely truncated. </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CodePointCount(BytesRef utf8) { int pos = utf8.Offset; int limit = pos + utf8.Length; var bytes = utf8.Bytes; int codePointCount = 0; for (; pos < limit; codePointCount++) { int v = bytes[pos] & 0xFF; if (v < /* 0xxx xxxx */ 0x80) { pos += 1; continue; } if (v >= /* 110x xxxx */ 0xc0) { if (v < /* 111x xxxx */ 0xe0) { pos += 2; continue; } if (v < /* 1111 xxxx */ 0xf0) { pos += 3; continue; } if (v < /* 1111 1xxx */ 0xf8) { pos += 4; continue; } // fallthrough, consider 5 and 6 byte sequences invalid. } // Anything not covered above is invalid UTF8. throw new ArgumentException(); } // Check if we didn't go over the limit on the last character. if (pos > limit) throw new ArgumentException(); return codePointCount; } /// <summary> /// This method assumes valid UTF8 input. This method /// <b>does not perform</b> full UTF8 validation, it will check only the /// first byte of each codepoint (for multi-byte sequences any bytes after /// the head are skipped). /// </summary> /// <exception cref="ArgumentException"> If invalid codepoint header byte occurs or the /// content is prematurely truncated. </exception> public static void UTF8toUTF32(BytesRef utf8, Int32sRef utf32) { // TODO: broken if incoming result.offset != 0 // pre-alloc for worst case // TODO: ints cannot be null, should be an assert if (utf32.Int32s == null || utf32.Int32s.Length < utf8.Length) { utf32.Int32s = new int[utf8.Length]; } int utf32Count = 0; int utf8Upto = utf8.Offset; int[] ints = utf32.Int32s; var bytes = utf8.Bytes; int utf8Limit = utf8.Offset + utf8.Length; while (utf8Upto < utf8Limit) { int numBytes = utf8CodeLength[bytes[utf8Upto] & 0xFF]; int v = 0; switch (numBytes) { case 1: ints[utf32Count++] = bytes[utf8Upto++]; continue; case 2: // 5 useful bits v = bytes[utf8Upto++] & 31; break; case 3: // 4 useful bits v = bytes[utf8Upto++] & 15; break; case 4: // 3 useful bits v = bytes[utf8Upto++] & 7; break; default: throw new ArgumentException("invalid utf8"); } // TODO: this may read past utf8's limit. int limit = utf8Upto + numBytes - 1; while (utf8Upto < limit) { v = v << 6 | bytes[utf8Upto++] & 63; } ints[utf32Count++] = v; } utf32.Offset = 0; utf32.Length = utf32Count; } /// <summary> /// Shift value for lead surrogate to form a supplementary character. </summary> private const int LEAD_SURROGATE_SHIFT_ = 10; /// <summary> /// Mask to retrieve the significant value from a trail surrogate. </summary> private const int TRAIL_SURROGATE_MASK_ = 0x3FF; /// <summary> /// Trail surrogate minimum value. </summary> private const int TRAIL_SURROGATE_MIN_VALUE = 0xDC00; /// <summary> /// Lead surrogate minimum value. </summary> private const int LEAD_SURROGATE_MIN_VALUE = 0xD800; /// <summary> /// The minimum value for Supplementary code points. </summary> private const int SUPPLEMENTARY_MIN_VALUE = 0x10000; /// <summary> /// Value that all lead surrogate starts with. </summary> private static readonly int LEAD_SURROGATE_OFFSET_ = LEAD_SURROGATE_MIN_VALUE - (SUPPLEMENTARY_MIN_VALUE >> LEAD_SURROGATE_SHIFT_); /// <summary> /// Cover JDK 1.5 API. Create a String from an array of <paramref name="codePoints"/>. /// </summary> /// <param name="codePoints"> The code array. </param> /// <param name="offset"> The start of the text in the code point array. </param> /// <param name="count"> The number of code points. </param> /// <returns> a String representing the code points between offset and count. </returns> /// <exception cref="ArgumentException"> If an invalid code point is encountered. </exception> /// <exception cref="IndexOutOfRangeException"> If the offset or count are out of bounds. </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string NewString(int[] codePoints, int offset, int count) { char[] chars = ToCharArray(codePoints, offset, count); return new string(chars); } /// <summary> /// Generates char array that represents the provided input code points. /// <para/> /// LUCENENET specific. /// </summary> /// <param name="codePoints"> The code array. </param> /// <param name="offset"> The start of the text in the code point array. </param> /// <param name="count"> The number of code points. </param> /// <returns> a char array representing the code points between offset and count. </returns> // LUCENENET NOTE: This code was originally in the NewString() method (above). // It has been refactored from the original to remove the exception throw/catch and // instead proactively resizes the array instead of relying on excpetions + copy operations public static char[] ToCharArray(int[] codePoints, int offset, int count) { if (count < 0) { throw new ArgumentException(); } int countThreashold = 1024; // If the number of chars exceeds this, we count them instead of allocating count * 2 // LUCENENET: as a first approximation, assume each codepoint // is 2 characters (since it cannot be longer than this) int arrayLength = count * 2; // LUCENENET: if we go over the threashold, count the number of // chars we will need so we can allocate the precise amount of memory if (count > countThreashold) { arrayLength = 0; for (int r = offset, e = offset + count; r < e; ++r) { arrayLength += codePoints[r] < 0x010000 ? 1 : 2; } if (arrayLength < 1) { arrayLength = count * 2; } } // Initialize our array to our exact or oversized length. // It is now safe to assume we have enough space for all of the characters. char[] chars = new char[arrayLength]; int w = 0; for (int r = offset, e = offset + count; r < e; ++r) { int cp = codePoints[r]; if (cp < 0 || cp > 0x10ffff) { throw new ArgumentException(); } if (cp < 0x010000) { chars[w++] = (char)cp; } else { chars[w++] = (char)(LEAD_SURROGATE_OFFSET_ + (cp >> LEAD_SURROGATE_SHIFT_)); chars[w++] = (char)(TRAIL_SURROGATE_MIN_VALUE + (cp & TRAIL_SURROGATE_MASK_)); } } var result = new char[w]; Array.Copy(chars, result, w); return result; } // for debugging public static string ToHexString(string s) { var sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char ch = s[i]; if (i > 0) { sb.Append(' '); } if (ch < 128) { sb.Append(ch); } else { if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { sb.Append("H:"); } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { sb.Append("L:"); } else if (ch > UNI_SUR_LOW_END) { if (ch == 0xffff) { sb.Append("F:"); } else { sb.Append("E:"); } } sb.Append("0x" + ((short)ch).ToString("X")); } } return sb.ToString(); } /// <summary> /// Interprets the given byte array as UTF-8 and converts to UTF-16. The <see cref="CharsRef"/> will be extended if /// it doesn't provide enough space to hold the worst case of each byte becoming a UTF-16 codepoint. /// <para/> /// NOTE: Full characters are read, even if this reads past the length passed (and /// can result in an <see cref="IndexOutOfRangeException"/> if invalid UTF-8 is passed). /// Explicit checks for valid UTF-8 are not performed. /// </summary> // TODO: broken if chars.offset != 0 public static void UTF8toUTF16(byte[] utf8, int offset, int length, CharsRef chars) { int out_offset = chars.Offset = 0; char[] @out = chars.Chars = ArrayUtil.Grow(chars.Chars, length); int limit = offset + length; while (offset < limit) { int b = utf8[offset++] & 0xff; if (b < 0xc0) { Debug.Assert(b < 0x80); @out[out_offset++] = (char)b; } else if (b < 0xe0) { @out[out_offset++] = (char)(((b & 0x1f) << 6) + (utf8[offset++] & 0x3f)); } else if (b < 0xf0) { @out[out_offset++] = (char)(((b & 0xf) << 12) + ((utf8[offset] & 0x3f) << 6) + (utf8[offset + 1] & 0x3f)); offset += 2; } else { Debug.Assert(b < 0xf8, "b = 0x" + b.ToString("x")); int ch = ((b & 0x7) << 18) + ((utf8[offset] & 0x3f) << 12) + ((utf8[offset + 1] & 0x3f) << 6) + (utf8[offset + 2] & 0x3f); offset += 3; if (ch < UNI_MAX_BMP) { @out[out_offset++] = (char)ch; } else { int chHalf = ch - 0x0010000; @out[out_offset++] = (char)((chHalf >> 10) + 0xD800); @out[out_offset++] = (char)((chHalf & HALF_MASK) + 0xDC00); } } } chars.Length = out_offset - chars.Offset; } /// <summary> /// Utility method for <see cref="UTF8toUTF16(byte[], int, int, CharsRef)"/> </summary> /// <seealso cref="UTF8toUTF16(byte[], int, int, CharsRef)"/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void UTF8toUTF16(BytesRef bytesRef, CharsRef chars) { UTF8toUTF16(bytesRef.Bytes, bytesRef.Offset, bytesRef.Length, chars); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Cryptography; using System.Text; using Xunit; using Xunit.Abstractions; using Medo.Security.Cryptography; namespace Tests.Medo.Security.Cryptography { public class TwofishManagedTests { private readonly ITestOutputHelper Output; public TwofishManagedTests(ITestOutputHelper output) => Output = output; [Fact(DisplayName = "TwoFish: Known Answers (ECB)")] public void KnownAnswers_ECB() { var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.ECB_TBL.TXT")); foreach (var test in tests) { using var algorithm = new TwofishManaged() { KeySize = test.KeySize, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, test.Key, null, test.PlainText); Assert.Equal(BitConverter.ToString(test.CipherText), BitConverter.ToString(ct)); var pt = Decrypt(algorithm, test.Key, null, test.CipherText); Assert.Equal(BitConverter.ToString(test.PlainText), BitConverter.ToString(pt)); } } //[Fact(DisplayName = "TwoFish: Monte Carlo (ECB) Encrypt")] private void MonteCarlo_ECB_Encrypt() { //takes ages var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.ECB_E_M.TXT")); var sw = Stopwatch.StartNew(); foreach (var test in tests) { MonteCarlo_ECB_E(test); } sw.Stop(); Output.WriteLine("Duration: " + sw.ElapsedMilliseconds.ToString() + " ms"); } [Fact(DisplayName = "TwoFish: Monte Carlo (ECB) Encrypt single")] public void MonteCarlo_ECB_Encrypt_One() { var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.ECB_E_M.TXT")); var test = tests[Rnd.Next(tests.Count)]; MonteCarlo_ECB_E(test); } //[Fact(DisplayName = "TwoFish: Monte Carlo (ECB) Decrypt")] private void MonteCarlo_ECB_Decrypt() { //takes ages var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.ECB_D_M.TXT")); var sw = Stopwatch.StartNew(); foreach (var test in tests) { MonteCarlo_ECB_D(test); } sw.Stop(); Output.WriteLine("Duration: " + sw.ElapsedMilliseconds.ToString() + " ms"); } [Fact(DisplayName = "TwoFish: Monte Carlo (ECB) Decrypt single")] public void MonteCarlo_ECB_Decrypt_One() { var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.ECB_D_M.TXT")); var test = tests[Rnd.Next(tests.Count)]; MonteCarlo_ECB_D(test); } //[Fact(DisplayName = "TwoFish: Monte Carlo (CBC) Encrypt")] private void MonteCarlo_CBC_Encrypt() { //takes ages var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.CBC_E_M.TXT")); var sw = Stopwatch.StartNew(); foreach (var test in tests) { MonteCarlo_CBC_E(test); } sw.Stop(); Output.WriteLine("Duration: " + sw.ElapsedMilliseconds.ToString() + " ms"); } [Fact(DisplayName = "TwoFish: Monte Carlo (CBC) Encrypt single")] public void MonteCarlo_CBC_Encrypt_One() { var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.CBC_E_M.TXT")); var test = tests[Rnd.Next(tests.Count)]; MonteCarlo_CBC_E(test); } //[Fact(DisplayName = "TwoFish: Monte Carlo (CBC) Decrypt")] private void MonteCarlo_CBC_Decrypt() { //takes ages var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.CBC_D_M.TXT")); var sw = Stopwatch.StartNew(); foreach (var test in tests) { MonteCarlo_CBC_D(test); } sw.Stop(); Output.WriteLine("Duration: " + sw.ElapsedMilliseconds.ToString() + " ms"); } [Fact(DisplayName = "TwoFish: Monte Carlo (CBC) Decrypt single")] public void MonteCarlo_CBC_Decrypt_One() { var tests = GetTestBlocks(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Twofish.CBC_D_M.TXT")); var test = tests[Rnd.Next(tests.Count)]; MonteCarlo_CBC_D(test); } [Theory(DisplayName = "TwoFish: Padding full blocks")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void PaddingFull(PaddingMode padding) { var key = new byte[32]; RandomNumberGenerator.Fill(key); var iv = new byte[16]; RandomNumberGenerator.Fill(iv); var data = new byte[48]; RandomNumberGenerator.Fill(data); // full blocks var algorithm = new TwofishManaged() { Padding = padding, }; var ct = Encrypt(algorithm, key, iv, data); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } [Theory(DisplayName = "TwoFish: Padding partial blocks")] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void PaddingPartial(PaddingMode padding) { var key = new byte[32]; RandomNumberGenerator.Fill(key); var iv = new byte[16]; RandomNumberGenerator.Fill(iv); var data = new byte[42]; RandomNumberGenerator.Fill(data); var algorithm = new TwofishManaged() { Padding = padding }; var ct = Encrypt(algorithm, key, iv, data); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } [Theory(DisplayName = "TwoFish: Only CBC supported")] [InlineData(CipherMode.CFB)] [InlineData(CipherMode.CTS)] public void OnlyCbcAndEbcSupported(CipherMode mode) { Assert.Throws<CryptographicException>(() => { var _ = new TwofishManaged() { Mode = mode }; }); } [Theory(DisplayName = "TwoFish: Large Final Block")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void LargeFinalBlock(PaddingMode padding) { var crypto = new TwofishManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var text = "This is a final block wider than block size."; // more than 128 bits of data if (padding is PaddingMode.None) { text += "1234"; } // must have a full block if no padding var bytes = Encoding.ASCII.GetBytes(text); using var encryptor = crypto.CreateEncryptor(); var ct = encryptor.TransformFinalBlock(bytes, 0, bytes.Length); Assert.Equal(padding == PaddingMode.None ? bytes.Length : 48, ct.Length); using var decryptor = crypto.CreateDecryptor(); var pt = decryptor.TransformFinalBlock(ct, 0, ct.Length); Assert.Equal(bytes.Length, pt.Length); Assert.Equal(text, Encoding.ASCII.GetString(pt)); } [Theory(DisplayName = "TwoFish: BlockSizeRounding")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void BlockSizeRounding(PaddingMode padding) { var key = new byte[32]; RandomNumberGenerator.Fill(key); var iv = new byte[16]; RandomNumberGenerator.Fill(iv); for (int n = 0; n < 50; n++) { if ((n % 16 != 0) && (padding is PaddingMode.None)) { continue; } // padding None works only on full blocks var data = new byte[n]; RandomNumberGenerator.Fill(data); if ((padding == PaddingMode.Zeros) && (data.Length > 0)) { data[^1] = 1; } // zero padding needs to have the last number non-zero var algorithm = new TwofishManaged() { Padding = padding, }; var expectedCryptLength = padding switch { PaddingMode.None => data.Length, PaddingMode.PKCS7 => ((data.Length / 16) + 1) * 16, PaddingMode.Zeros => (data.Length / 16 + (data.Length % 16 > 0 ? 1 : 0)) * 16, PaddingMode.ANSIX923 => ((data.Length / 16) + 1) * 16, PaddingMode.ISO10126 => ((data.Length / 16) + 1) * 16, _ => -1 }; var ct = Encrypt(algorithm, key, iv, data); Assert.Equal(expectedCryptLength, ct.Length); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } } [Theory(DisplayName = "TwoFish: Random Testing")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void Randomised(PaddingMode padding) { for (var n = 0; n < 1000; n++) { var crypto = new TwofishManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var data = new byte[Random.Shared.Next(100)]; if (padding is PaddingMode.None) { data = new byte[data.Length / 16 * 16]; } // make it rounded number if no padding RandomNumberGenerator.Fill(data); if ((padding == PaddingMode.Zeros) && (data.Length > 0)) { data[^1] = 1; } // zero padding needs to have the last number non-zero var ct = Encrypt(crypto, crypto.Key, crypto.IV, data); if (padding is PaddingMode.None or PaddingMode.Zeros) { Assert.True(data.Length <= ct.Length); } else { Assert.True(data.Length < ct.Length); } var pt = Decrypt(crypto, crypto.Key, crypto.IV, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } } [Theory(DisplayName = "TwoFish: Encrypt/Decrypt")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void EncryptDecrypt(PaddingMode padding) { var crypto = new TwofishManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var bytes = RandomNumberGenerator.GetBytes(1024); var bytesEnc = new byte[bytes.Length]; var bytesDec = new byte[bytes.Length]; var sw = Stopwatch.StartNew(); using var encryptor = crypto.CreateEncryptor(); using var decryptor = crypto.CreateDecryptor(); for (var n = 0; n < 1024; n++) { encryptor.TransformBlock(bytes, 0, bytes.Length, bytesEnc, 0); decryptor.TransformBlock(bytesEnc, 0, bytesEnc.Length, bytesDec, 0); } if (padding is PaddingMode.None) { // has to be a full block if no padding var lastBytesEnc = encryptor.TransformFinalBlock(new byte[16], 0, 16); var lastBytesDec = decryptor.TransformFinalBlock(lastBytesEnc, 0, lastBytesEnc.Length); } else { var lastBytesEnc = encryptor.TransformFinalBlock(new byte[10], 0, 10); var lastBytesDec = decryptor.TransformFinalBlock(lastBytesEnc, 0, lastBytesEnc.Length); } sw.Stop(); Output.WriteLine($"Duration: {sw.ElapsedMilliseconds} ms"); } #region Private helper private static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] key, byte[] iv, byte[] pt) { using var ms = new MemoryStream(); using (var transform = algorithm.CreateEncryptor(key, iv)) { using var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write); cs.Write(pt, 0, pt.Length); } return ms.ToArray(); } private static byte[] Decrypt(SymmetricAlgorithm algorithm, byte[] key, byte[] iv, byte[] ct) { using var ctStream = new MemoryStream(ct); using var transform = algorithm.CreateDecryptor(key, iv); using var cs = new CryptoStream(ctStream, transform, CryptoStreamMode.Read); using var ms = new MemoryStream(); cs.CopyTo(ms); return ms.ToArray(); } #endregion #region Private: Monte carlo // http://www.ntua.gr/cryptix/old/cryptix/aes/docs/katmct.html private static void MonteCarlo_ECB_E(TestBlock test) { using var algorithm = new TwofishManaged() { KeySize = test.KeySize, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var key = test.Key; var pt = test.PlainText; byte[] ct = null; for (var j = 0; j < 10000; j++) { ct = Encrypt(algorithm, key, null, pt); pt = ct; } Assert.Equal(BitConverter.ToString(test.CipherText), BitConverter.ToString(ct)); } private static void MonteCarlo_ECB_D(TestBlock test) { using var algorithm = new TwofishManaged() { KeySize = test.KeySize, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var key = test.Key; var ct = test.CipherText; byte[] pt = null; for (var j = 0; j < 10000; j++) { pt = Decrypt(algorithm, key, null, ct); ct = pt; } Assert.Equal(BitConverter.ToString(test.PlainText), BitConverter.ToString(pt)); } private static void MonteCarlo_CBC_E(TestBlock test) { using var algorithm = new TwofishManaged() { KeySize = test.KeySize, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var key = test.Key; var cv = test.IV; var pt = test.PlainText; byte[] ct = null; for (var j = 0; j < 10000; j++) { var ob = Encrypt(algorithm, key, cv, pt); pt = (j == 0) ? cv : ct; ct = ob; cv = ct; } Assert.Equal(BitConverter.ToString(test.CipherText), BitConverter.ToString(ct)); } private static void MonteCarlo_CBC_D(TestBlock test) { using var algorithm = new TwofishManaged() { KeySize = test.KeySize, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var key = test.Key; var cv = test.IV; var ct = test.CipherText; byte[] pt = null; for (var j = 0; j < 10000; j++) { pt = Decrypt(algorithm, key, cv, ct); cv = ct; ct = pt; } Assert.Equal(BitConverter.ToString(test.PlainText), BitConverter.ToString(pt)); } #endregion #region Multiblock [Fact(DisplayName = "TwoFish: Multiblock (ECB/128) Encrypt")] public void MultiBlock_ECB_128_Encrypt() { var key = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (ECB/128) Decrypt")] public void MultiBlock_ECB_128_Decrypt() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/128) Encrypt")] public void MultiBlock_CBC_128_Encrypt() { var key = ParseBytes("00000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, iv, pt); Assert.Equal("9F589F5CF6122C32B6BFEC2F2AE8C35AD491DB16E7B1C39E86CB086B789F541905EF8C61A811582634BA5CB7106AA641", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/128) Decrypt")] public void MultiBlock_CBC_128_Decrypt() { var key = ParseBytes("00000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("9F589F5CF6122C32B6BFEC2F2AE8C35AD491DB16E7B1C39E86CB086B789F541905EF8C61A811582634BA5CB7106AA641"); var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (ECB/192) Encrypt")] public void MultiBlock_ECB_192_Encrypt() { var key = ParseBytes("000000000000000000000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); var algorithm = new TwofishManaged() { KeySize = 192, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("EFA71F788965BD4453F860178FC19101EFA71F788965BD4453F860178FC19101EFA71F788965BD4453F860178FC19101", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (ECB/192) Decrypt")] public void MultiBlock_ECB_192_Decrypt() { var key = ParseBytes("000000000000000000000000000000000000000000000000"); var ct = ParseBytes("EFA71F788965BD4453F860178FC19101EFA71F788965BD4453F860178FC19101EFA71F788965BD4453F860178FC19101"); var algorithm = new TwofishManaged() { KeySize = 192, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/192) Encrypt")] public void MultiBlock_CBC_192_Encrypt() { var key = ParseBytes("000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); var algorithm = new TwofishManaged() { KeySize = 192, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, iv, pt); Assert.Equal("EFA71F788965BD4453F860178FC1910188B2B2706B105E36B446BB6D731A1E88F2DD994D2C4E64517CC9DB9AED2D5909", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/192) Decrypt")] public void MultiBlock_CBC_192_Decrypt() { var key = ParseBytes("000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("EFA71F788965BD4453F860178FC1910188B2B2706B105E36B446BB6D731A1E88F2DD994D2C4E64517CC9DB9AED2D5909"); var algorithm = new TwofishManaged() { KeySize = 192, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (ECB/256) Encrypt")] public void MultiBlock_ECB_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (ECB/256) Decrypt")] public void MultiBlock_ECB_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var ct = ParseBytes("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F"); var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/256) Encrypt")] public void MultiBlock_CBC_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, iv, pt); Assert.Equal("57FF739D4DC92C1BD7FC01700CC8216FD43BB7556EA32E46F2A282B7D45B4E0D2804E32925D62BAE74487A06B3CD2D46", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock (CBC/256) Decrypt")] public void MultiBlock_CBC_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("57FF739D4DC92C1BD7FC01700CC8216FD43BB7556EA32E46F2A282B7D45B4E0D2804E32925D62BAE74487A06B3CD2D46"); var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 2 (ECB/256) Encrypt")] public void MultiBlockNonFinal_ECB_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; algorithm.Key = key; var ct = new byte[pt.Length]; using (var transform = algorithm.CreateEncryptor()) { transform.TransformBlock(pt, 0, pt.Length, ct, 0); transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0); } Assert.Equal("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 2 (ECB/256) Decrypt")] public void MultiBlockNotFinal_ECB_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var ct = ParseBytes("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; algorithm.Key = key; var pt = new byte[ct.Length]; using (var transform = algorithm.CreateDecryptor()) { transform.TransformBlock(ct, 0, ct.Length, pt, 0); transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0); } Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 3 (ECB/256) Encrypt")] public void MultiBlockFinal_ECB_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var pt = ParseBytes("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; algorithm.Key = key; var ct = algorithm.CreateEncryptor().TransformFinalBlock(pt, 0, pt.Length); Assert.Equal("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 3 (ECB/256) Decrypt")] public void MultiBlockFinal_ECB_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var ct = ParseBytes("57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F57FF739D4DC92C1BD7FC01700CC8216F"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.ECB, Padding = PaddingMode.None }; algorithm.Key = key; var pt = algorithm.CreateDecryptor().TransformFinalBlock(ct, 0, ct.Length); Assert.Equal("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 2 (CBC/256) Encrypt")] public void MultiBlockNonFinal_CBC_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; algorithm.Key = key; algorithm.IV = iv; var ct = new byte[pt.Length]; using (var transform = algorithm.CreateEncryptor()) { transform.TransformBlock(pt, 0, pt.Length, ct, 0); transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0); } Assert.Equal("61B5BC459C4E9491DD9E6ACB7478813047BE7250D34F792C17F0C23583C0B040B95C9FAE11107EE9BAC3D79BBFE019EE", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 2 (CBC/256) Decrypt")] public void MultiBlockNonFinal_CBC_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("61B5BC459C4E9491DD9E6ACB7478813047BE7250D34F792C17F0C23583C0B040B95C9FAE11107EE9BAC3D79BBFE019EE"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; algorithm.Key = key; algorithm.IV = iv; var pt = new byte[ct.Length]; pt[ct.Length - 1] = 0xFF; using (var transform = algorithm.CreateDecryptor()) { transform.TransformBlock(ct, 0, ct.Length, pt, 0); transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0); } Assert.Equal("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A", BitConverter.ToString(pt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 3 (CBC/256) Encrypt")] public void MultiBlockFinal_CBC_256_Encrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var pt = ParseBytes("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; algorithm.Key = key; algorithm.IV = iv; var ct = algorithm.CreateEncryptor().TransformFinalBlock(pt, 0, pt.Length); Assert.Equal("61B5BC459C4E9491DD9E6ACB7478813047BE7250D34F792C17F0C23583C0B040B95C9FAE11107EE9BAC3D79BBFE019EE", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Multiblock 3 (CBC/256) Decrypt")] public void MultiBlockFinal_CBC_256_Decrypt() { var key = ParseBytes("0000000000000000000000000000000000000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("61B5BC459C4E9491DD9E6ACB7478813047BE7250D34F792C17F0C23583C0B040B95C9FAE11107EE9BAC3D79BBFE019EE"); using var algorithm = new TwofishManaged() { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.None }; algorithm.Key = key; algorithm.IV = iv; var pt = algorithm.CreateDecryptor().TransformFinalBlock(ct, 0, ct.Length); Assert.Equal("9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A9F589F5CF6122C32B6BFEC2F2AE8C35A", BitConverter.ToString(pt).Replace("-", "")); } #endregion #region Padding [Fact(DisplayName = "TwoFish: Padding Zeros (ECB/128) Encrypt")] public void Padding_Zeros_ECB_128_Encrypt() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.Zeros }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB33C25C273BF09B94A31DE3C27C28DFB5C", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding Zeros (ECB/128) Decrypt")] public void Padding_Zeros_ECB_128_Decrypt() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB33C25C273BF09B94A31DE3C27C28DFB5C"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.Zeros }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding None at boundary (ECB/128) Encrypt")] public void Padding_None_ECB_128_Encrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding None at boundary (ECB/128) Decrypt")] public void Padding_None_ECB_128_Decrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.None }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog once", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding Zeros at boundary (ECB/128) Encrypt")] public void Padding_Zeros_ECB_128_Encrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.Zeros }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding Zeros at boundary (ECB/128) Decrypt")] public void Padding_Zeros_ECB_128_Decrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.Zeros }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog once", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding PKCS#7 (ECB/128) Encrypt")] public void Padding_Pkcs7_ECB_128_Encrypt() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB3235D2E6063F32DE35B8A62A384FC587E", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding PKCS#7 (ECB/128) Decrypt")] public void Padding_Pkcs7_ECB_128_Decrypt() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB3235D2E6063F32DE35B8A62A384FC587E"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding PKCS#7 at boundary (ECB/128) Encrypt")] public void Padding_Pkcs7_ECB_128_Encrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59771D591428AF301D69FA1E227D083527", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding PKCS#7 at boundary (ECB/128) Decrypt")] public void Padding_Pkcs7_ECB_128_Decrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB59771D591428AF301D69FA1E227D083527"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog once", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding ANSI X923 (ECB/128) Encrypt")] public void Padding_AnsiX923_ECB_128_Encrypt() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ANSIX923 }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB3B696D40A5E12225D3E05E8A466F078C2", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding ANSI X923 (ECB/128) Decrypt")] public void Padding_AnsiX923_ECB_128_Decrypt() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB3B696D40A5E12225D3E05E8A466F078C2"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ANSIX923 }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding ANSI X923 at boundary (ECB/128) Encrypt")] public void Padding_AnsiX923_ECB_128_Encrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var pt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ANSIX923 }; var ct = Encrypt(algorithm, key, null, pt); Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB5958A06DC5AD2D7C0550771D6E9D59D58B", BitConverter.ToString(ct).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Padding ANSI X923 at boundary (ECB/128) Decrypt")] public void Padding_AnsiX923_ECB_128_Decrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var ct = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB5958A06DC5AD2D7C0550771D6E9D59D58B"); using var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ANSIX923 }; var pt = Decrypt(algorithm, key, null, ct); Assert.Equal("The quick brown fox jumps over the lazy dog once", Encoding.UTF8.GetString(pt)); } [Fact(DisplayName = "TwoFish: Padding ISO 10126 (ECB/128) Encrypt/Decrypt")] public void Padding_Iso10126_ECB_128_DecryptAndEncrypt() { var key = ParseBytes("00000000000000000000000000000000"); var pt = "The quick brown fox jumps over the lazy dog"; var ctA = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB3B696D40A5E12225D3E05E8A466F078C2"); using (var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ISO10126 }) { var ptA = Decrypt(algorithm, key, null, ctA); Assert.Equal(pt, Encoding.UTF8.GetString(ptA)); } var ptB = Encoding.UTF8.GetBytes(pt); using (var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ISO10126 }) { var ctB = Encrypt(algorithm, key, null, ptB); var ptC = Decrypt(algorithm, key, null, ctB); Assert.Equal(pt, Encoding.UTF8.GetString(ptC)); Assert.NotEqual(BitConverter.ToString(ctA).Replace("-", ""), BitConverter.ToString(ctB).Replace("-", "")); //chances are good padding will be different (due to randomness involved) } } [Fact(DisplayName = "TwoFish: Padding ISO 10126 at boundary (ECB/128) Encrypt/Decrypt")] public void Padding_Iso10126_ECB_128_DecryptAndEncrypt_16() { var key = ParseBytes("00000000000000000000000000000000"); var pt = "The quick brown fox jumps over the lazy dog once"; var ctA = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF1194B36D8E0BDD5AC10842B549230BB36D66FC3AFE1F40216590079AF862AB5958A06DC5AD2D7C0550771D6E9D59D58B"); using (var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ISO10126 }) { var ptA = Decrypt(algorithm, key, null, ctA); Assert.Equal(pt, Encoding.UTF8.GetString(ptA)); } var ptB = Encoding.UTF8.GetBytes(pt); using (var algorithm = new TwofishManaged() { KeySize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.ISO10126 }) { var ctB = Encrypt(algorithm, key, null, ptB); var ptC = Decrypt(algorithm, key, null, ctB); Assert.Equal(pt, Encoding.UTF8.GetString(ptC)); Assert.NotEqual(BitConverter.ToString(ctA).Replace("-", ""), BitConverter.ToString(ctB).Replace("-", "")); //chances are good padding will be different (due to randomness involved) } } #endregion #region Other [Fact(DisplayName = "TwoFish: Transform block (same array) Encrypt")] public void TransformBlock_Encrypt_UseSameArray() { var key = ParseBytes("00000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ctpt = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog once"); using (var twofish = new TwofishManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None, KeySize = 128, Key = key, IV = iv }) { using var transform = twofish.CreateEncryptor(); transform.TransformBlock(ctpt, 0, 48, ctpt, 0); } Assert.Equal("B0DD30E9AB1F1329C1BEE154DDBE88AF8C47A4FE24D56DC027ED503652C9D164CE26E0C6E32BCA8756482B99988E8C79", BitConverter.ToString(ctpt).Replace("-", "")); } [Fact(DisplayName = "TwoFish: Transform block (same array) Decrypt")] public void TransformBlock_Decrypt_UseSameArray() { var key = ParseBytes("00000000000000000000000000000000"); var iv = ParseBytes("00000000000000000000000000000000"); var ctpt = ParseBytes("B0DD30E9AB1F1329C1BEE154DDBE88AF8C47A4FE24D56DC027ED503652C9D164CE26E0C6E32BCA8756482B99988E8C79"); using (var twofish = new TwofishManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None, KeySize = 128, Key = key, IV = iv }) { using var transform = twofish.CreateDecryptor(); transform.TransformBlock(ctpt, 0, 48, ctpt, 0); //no caching last block if Padding is none } Assert.Equal("The quick brown fox jumps over the lazy dog once", Encoding.UTF8.GetString(ctpt)); } #endregion #region Private setup private static readonly Random Rnd = new(); private static List<TestBlock> GetTestBlocks(Stream fileStream) { var result = new List<TestBlock>(); using (var s = new StreamReader(fileStream)) { int? keySize = null, i = null; byte[] key = null, iv = null, ct = null, pt = null; while (!s.EndOfStream) { var line = s.ReadLine(); if (line.StartsWith("KEYSIZE=", StringComparison.Ordinal)) { keySize = int.Parse(line[8..], CultureInfo.InvariantCulture); i = null; } else if (line.StartsWith("I=", StringComparison.Ordinal)) { if (keySize == null) { continue; } i = int.Parse(line[2..], CultureInfo.InvariantCulture); } else if (line.StartsWith("KEY=", StringComparison.Ordinal)) { key = ParseBytes(line[4..]); } else if (line.StartsWith("IV=", StringComparison.Ordinal)) { iv = ParseBytes(line[3..]); } else if (line.StartsWith("PT=", StringComparison.Ordinal)) { pt = ParseBytes(line[3..]); } else if (line.StartsWith("CT=", StringComparison.Ordinal)) { ct = ParseBytes(line[3..]); } else if (line.Equals("", StringComparison.Ordinal)) { if (i == null) { continue; } result.Add(new TestBlock(keySize.Value, i.Value, key, iv, pt, ct)); i = null; key = null; iv = null; ct = null; pt = null; } } } return result; } private static byte[] ParseBytes(string hex) { Trace.Assert((hex.Length % 2) == 0); var result = new byte[hex.Length / 2]; for (var i = 0; i < hex.Length; i += 2) { result[i / 2] = byte.Parse(hex.AsSpan(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return result; } [DebuggerDisplay("{KeySize}:{Index}")] private struct TestBlock { internal TestBlock(int keySize, int index, byte[] key, byte[] iv, byte[] plainText, byte[] cipherText) { KeySize = keySize; Index = index; Key = key; IV = iv; PlainText = plainText; CipherText = cipherText; } internal int KeySize { get; } internal int Index { get; } internal byte[] Key { get; } internal byte[] IV { get; } internal byte[] PlainText { get; } internal byte[] CipherText { get; } } #endregion } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A VM crashdump /// First published in XenServer 4.0. /// </summary> public partial class Crashdump : XenObject<Crashdump> { #region Constructors public Crashdump() { } public Crashdump(string uuid, XenRef<VM> VM, XenRef<VDI> VDI, Dictionary<string, string> other_config) { this.uuid = uuid; this.VM = VM; this.VDI = VDI; this.other_config = other_config; } /// <summary> /// Creates a new Crashdump from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Crashdump(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Crashdump from a Proxy_Crashdump. /// </summary> /// <param name="proxy"></param> public Crashdump(Proxy_Crashdump proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Crashdump. /// </summary> public override void UpdateFrom(Crashdump update) { uuid = update.uuid; VM = update.VM; VDI = update.VDI; other_config = update.other_config; } internal void UpdateFrom(Proxy_Crashdump proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Crashdump ToProxy() { Proxy_Crashdump result_ = new Proxy_Crashdump(); result_.uuid = uuid ?? ""; result_.VM = VM ?? ""; result_.VDI = VDI ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Crashdump /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("VDI")) VDI = Marshalling.ParseRef<VDI>(table, "VDI"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Crashdump other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._VDI, other._VDI) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<Crashdump> ProxyArrayToObjectList(Proxy_Crashdump[] input) { var result = new List<Crashdump>(); foreach (var item in input) result.Add(new Crashdump(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Crashdump server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Crashdump.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given crashdump. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> [Deprecated("XenServer 7.3")] public static Crashdump get_record(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_record(session.opaque_ref, _crashdump); else return new Crashdump(session.proxy.crashdump_get_record(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get a reference to the crashdump instance with the specified UUID. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> [Deprecated("XenServer 7.3")] public static XenRef<Crashdump> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Crashdump>.Create(session.proxy.crashdump_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static string get_uuid(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_uuid(session.opaque_ref, _crashdump); else return session.proxy.crashdump_get_uuid(session.opaque_ref, _crashdump ?? "").parse(); } /// <summary> /// Get the VM field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<VM> get_VM(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_vm(session.opaque_ref, _crashdump); else return XenRef<VM>.Create(session.proxy.crashdump_get_vm(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get the VDI field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<VDI> get_VDI(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_vdi(session.opaque_ref, _crashdump); else return XenRef<VDI>.Create(session.proxy.crashdump_get_vdi(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static Dictionary<string, string> get_other_config(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_other_config(session.opaque_ref, _crashdump); else return Maps.convert_from_proxy_string_string(session.proxy.crashdump_get_other_config(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Set the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _crashdump, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_set_other_config(session.opaque_ref, _crashdump, _other_config); else session.proxy.crashdump_set_other_config(session.opaque_ref, _crashdump ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _crashdump, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_add_to_other_config(session.opaque_ref, _crashdump, _key, _value); else session.proxy.crashdump_add_to_other_config(session.opaque_ref, _crashdump ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given crashdump. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _crashdump, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_remove_from_other_config(session.opaque_ref, _crashdump, _key); else session.proxy.crashdump_remove_from_other_config(session.opaque_ref, _crashdump ?? "", _key ?? "").parse(); } /// <summary> /// Destroy the specified crashdump /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static void destroy(Session session, string _crashdump) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_destroy(session.opaque_ref, _crashdump); else session.proxy.crashdump_destroy(session.opaque_ref, _crashdump ?? "").parse(); } /// <summary> /// Destroy the specified crashdump /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<Task> async_destroy(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_crashdump_destroy(session.opaque_ref, _crashdump); else return XenRef<Task>.Create(session.proxy.async_crashdump_destroy(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Return a list of all the crashdumps known to the system. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> [Deprecated("XenServer 7.3")] public static List<XenRef<Crashdump>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_all(session.opaque_ref); else return XenRef<Crashdump>.Create(session.proxy.crashdump_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the crashdump Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Crashdump>, Crashdump> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_all_records(session.opaque_ref); else return XenRef<Crashdump>.Create<Proxy_Crashdump>(session.proxy.crashdump_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the virtual machine /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; Changed = true; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// the virtual disk /// </summary> [JsonConverter(typeof(XenRefConverter<VDI>))] public virtual XenRef<VDI> VDI { get { return _VDI; } set { if (!Helper.AreEqual(value, _VDI)) { _VDI = value; Changed = true; NotifyPropertyChanged("VDI"); } } } private XenRef<VDI> _VDI = new XenRef<VDI>(Helper.NullOpaqueRef); /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// 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; /// <summary> /// System.Collections.Generic.IEnumerable<T>.GetEnumerator() /// </summary> public class IEnumerableGetEnumerator { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 20; public static int Main() { IEnumerableGetEnumerator testObj = new IEnumerableGetEnumerator(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.IEnumerable<T>.GetEnumerator()"); if (testObj.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; return retVal; } #region Positive Tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the GetEnumerator method in IEnumerable<T> and Type is string..."; const string c_TEST_ID = "P001"; List<String> list = new List<String>(); String x = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String y = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); list.Add(x); list.Add(y); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IEnumerator<String> enumerator = ((IEnumerable<String>)list).GetEnumerator(); enumerator.MoveNext(); if (enumerator.Current != x) { string errorDesc = "Value is not " + x + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } enumerator.MoveNext(); if (enumerator.Current != y) { string errorDesc = "Value is not " + y + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the GetEnumerator method in IEnumerable<T> and Type is int..."; const string c_TEST_ID = "P002"; List<int> list = new List<int>(); int x = TestLibrary.Generator.GetInt32(-55); int y = TestLibrary.Generator.GetInt32(-55); list.Add(x); list.Add(y); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IEnumerator<int> enumerator = ((IEnumerable<int>)list).GetEnumerator(); enumerator.MoveNext(); if (enumerator.Current != x) { string errorDesc = "Value is not " + x + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } enumerator.MoveNext(); if (enumerator.Current != y) { string errorDesc = "Value is not " + y + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Useing customer class which implemented the GetEnumerator method in IEnumerable<T>... "; const string c_TEST_ID = "P003"; int[] pArray = new int[2]; pArray[0] = TestLibrary.Generator.GetInt32(-55); pArray[1] = TestLibrary.Generator.GetInt32(-55); MyEnumerable<int> myEnumerable = new MyEnumerable<int>(pArray); MyEnumerator<int> myEnumerator = new MyEnumerator<int>(pArray); ((IEnumerator<int>)myEnumerator).MoveNext(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IEnumerator<int> enumerator = ((IEnumerable<int>)myEnumerable).GetEnumerator(); enumerator.MoveNext(); if (enumerator.Current != ((IEnumerator<int>)myEnumerator).Current) { string errorDesc = "Value is not " + myEnumerator.Current + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } enumerator.MoveNext(); ((IEnumerator<int>)myEnumerator).MoveNext(); if (enumerator.Current != ((IEnumerator<int>)myEnumerator).Current) { string errorDesc = "Value is not " + myEnumerator.Current + " as expected: Actual(" + enumerator.Current + ")"; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyEnumerable<T> : IEnumerable<T> { public T[] _item; public MyEnumerable(T[] pArray) { _item = new T[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _item[i] = pArray[i]; } } #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new MyEnumerator<T>(_item); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new MyEnumerator<T>(_item); } #endregion } public class MyEnumerator<T> : IEnumerator<T> { public T[] _item; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public MyEnumerator(T[] list) { _item = list; } public bool MoveNext() { position++; return (position < _item.Length); } public void Reset() { position = -1; } public object Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } #region IEnumerator<T> Members T IEnumerator<T>.Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } #endregion #region IDisposable Members public void Dispose() { throw new Exception("The method or operation is not implemented."); } #endregion #region IDisposable Members void IDisposable.Dispose() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } bool System.Collections.IEnumerator.MoveNext() { position++; return (position < _item.Length); } void System.Collections.IEnumerator.Reset() { position = -1; } #endregion } #endregion }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Apis.Download; using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Xunit; using Object = Google.Apis.Storage.v1.Data.Object; namespace Google.Cloud.Storage.V1.IntegrationTests { [Collection(nameof(StorageFixture))] public class DownloadObjectTest { private readonly StorageFixture _fixture; public DownloadObjectTest(StorageFixture fixture) { _fixture = fixture; } [Fact] public async Task SimpleDownload() { using (var stream = new MemoryStream()) { await _fixture.Client.DownloadObjectAsync(_fixture.ReadBucket, _fixture.SmallObject, stream); Assert.Equal(_fixture.SmallContent, stream.ToArray()); } } [Fact] public void WrongObjectName() { using (var stream = new MemoryStream()) { Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(_fixture.ReadBucket, "doesntexist", stream)); } } [Fact] public async Task WrongObjectName_Async() { using (var stream = new MemoryStream()) { await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.DownloadObjectAsync(_fixture.ReadBucket, "doesntexist", stream)); } } [Fact] public void WrongBucketName() { using (var stream = new MemoryStream()) { Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(_fixture.BucketPrefix + "doesntexist", "doesntexist", stream)); } } [Fact] public async Task WrongBucketName_Async() { using (var stream = new MemoryStream()) { await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.DownloadObjectAsync(_fixture.BucketPrefix + "doesntexist", "doesntexist", stream)); } } [Fact] public async Task ChunkSize() { int chunks = 0; var progress = new Progress<IDownloadProgress> (p => chunks++); using (var stream = new MemoryStream()) { await _fixture.Client.DownloadObjectAsync( _fixture.ReadBucket, _fixture.LargeObject, stream, new DownloadObjectOptions { ChunkSize = 2 * 1024 }, CancellationToken.None, progress); Assert.Equal(_fixture.LargeContent, stream.ToArray()); Assert.True(chunks >= 5); } } [Fact] public async Task Cancellation() { var cts = new CancellationTokenSource(); var progress = new Progress<IDownloadProgress>(p => { if (p.BytesDownloaded > 5000) { cts.Cancel(); } }); using (var stream = new MemoryStream()) { await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _fixture.Client.DownloadObjectAsync( _fixture.ReadBucket, _fixture.LargeObject, stream, new DownloadObjectOptions { ChunkSize = 2 * 1024 }, cts.Token, progress)); } } [Fact] public void DownloadObjectFromInvalidBucket() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject("!!!", _fixture.LargeObject, new MemoryStream())); } [Fact] public void DownloadObjectWrongGeneration() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { Generation = existing.Generation + 1 }, null)); Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadDifferentGenerations() { var bucket = _fixture.ReadBucket; var name = _fixture.SmallThenLargeObject; var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true }).ToList(); Assert.Equal(2, objects.Count); // Fetch them by generation and check size matches foreach (var obj in objects) { var stream = new MemoryStream(); _fixture.Client.DownloadObject(bucket, name, stream, new DownloadObjectOptions { Generation = obj.Generation }, null); Assert.Equal((long) obj.Size, stream.Length); } } [Fact] public void SpecifyingObjectSourceIgnoredGeneration() { var bucket = _fixture.ReadBucket; var name = _fixture.SmallThenLargeObject; var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true }) .OrderBy(x => x.Generation) .ToList(); Assert.Equal(2, objects.Count); Assert.NotEqual(objects[0].Size, objects[1].Size); var stream = new MemoryStream(); _fixture.Client.DownloadObject(objects[0], stream); Assert.Equal((long) objects[1].Size, stream.Length); } [Fact] public void DownloadObjectIfGenerationMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationMatch = existing.Generation}, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationMatch = existing.Generation + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationNotMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationNotMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation + 1 }, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObject_IfGenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject( _fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(), new DownloadObjectOptions { IfGenerationMatch = 1, IfGenerationNotMatch = 2 }, null)); } [Fact] public void DownloadObjectIfMetagenerationMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration}, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationNotMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationNotMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration + 1 }, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObject_IfMetagenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject( _fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(), new DownloadObjectOptions { IfMetagenerationMatch = 1, IfMetagenerationNotMatch = 2 }, null)); } [Fact] public void DownloadObject_Range() { var stream = new MemoryStream(); _fixture.Client.DownloadObject(_fixture.ReadBucket, _fixture.LargeObject, stream, new DownloadObjectOptions { Range = new RangeHeaderValue(2000, 2999) }); var expected = _fixture.LargeContent.Skip(2000).Take(1000).ToArray(); var actual = stream.ToArray(); Assert.Equal(expected, actual); } private Object GetLatestVersionOfMultiversionObject() { var service = _fixture.Client.Service; return service.Objects.Get(_fixture.ReadBucket, _fixture.SmallThenLargeObject).Execute(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene40 { using ArrayUtil = Lucene.Net.Util.ArrayUtil; /* * 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 AtomicReader = Lucene.Net.Index.AtomicReader; using Bits = Lucene.Net.Util.Bits; using BytesRef = Lucene.Net.Util.BytesRef; using DataInput = Lucene.Net.Store.DataInput; using Directory = Lucene.Net.Store.Directory; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using Fields = Lucene.Net.Index.Fields; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using MergeState = Lucene.Net.Index.MergeState; using SegmentReader = Lucene.Net.Index.SegmentReader; using StringHelper = Lucene.Net.Util.StringHelper; // TODO: make a new 4.0 TV format that encodes better // - use startOffset (not endOffset) as base for delta on // next startOffset because today for syns or ngrams or // WDF or shingles etc. we are encoding negative vints // (= slow, 5 bytes per) // - if doc has no term vectors, write 0 into the tvx // file; saves a seek to tvd only to read a 0 vint (and // saves a byte in tvd) /// <summary> /// Lucene 4.0 Term Vectors writer. /// <p> /// It writes .tvd, .tvf, and .tvx files. /// </summary> /// <seealso cref= Lucene40TermVectorsFormat </seealso> public sealed class Lucene40TermVectorsWriter : TermVectorsWriter { private readonly Directory Directory; private readonly string Segment; private IndexOutput Tvx = null, Tvd = null, Tvf = null; /// <summary> /// Sole constructor. </summary> public Lucene40TermVectorsWriter(Directory directory, string segment, IOContext context) { this.Directory = directory; this.Segment = segment; bool success = false; try { // Open files for TermVector storage Tvx = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_INDEX_EXTENSION), context); CodecUtil.WriteHeader(Tvx, Lucene40TermVectorsReader.CODEC_NAME_INDEX, Lucene40TermVectorsReader.VERSION_CURRENT); Tvd = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_DOCUMENTS_EXTENSION), context); CodecUtil.WriteHeader(Tvd, Lucene40TermVectorsReader.CODEC_NAME_DOCS, Lucene40TermVectorsReader.VERSION_CURRENT); Tvf = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene40TermVectorsReader.VECTORS_FIELDS_EXTENSION), context); CodecUtil.WriteHeader(Tvf, Lucene40TermVectorsReader.CODEC_NAME_FIELDS, Lucene40TermVectorsReader.VERSION_CURRENT); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_INDEX == Tvx.FilePointer); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_DOCS == Tvd.FilePointer); Debug.Assert(Lucene40TermVectorsReader.HEADER_LENGTH_FIELDS == Tvf.FilePointer); success = true; } finally { if (!success) { Abort(); } } } public override void StartDocument(int numVectorFields) { LastFieldName = null; this.NumVectorFields = numVectorFields; Tvx.WriteLong(Tvd.FilePointer); Tvx.WriteLong(Tvf.FilePointer); Tvd.WriteVInt(numVectorFields); FieldCount = 0; Fps = ArrayUtil.Grow(Fps, numVectorFields); } private long[] Fps = new long[10]; // pointers to the tvf before writing each field private int FieldCount = 0; // number of fields we have written so far for this document private int NumVectorFields = 0; // total number of fields we will write for this document private string LastFieldName; public override void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads) { Debug.Assert(LastFieldName == null || info.Name.CompareTo(LastFieldName) > 0, "fieldName=" + info.Name + " lastFieldName=" + LastFieldName); LastFieldName = info.Name; this.Positions = positions; this.Offsets = offsets; this.Payloads = payloads; LastTerm.Length = 0; LastPayloadLength = -1; // force first payload to write its length Fps[FieldCount++] = Tvf.FilePointer; Tvd.WriteVInt(info.Number); Tvf.WriteVInt(numTerms); sbyte bits = 0x0; if (positions) { bits |= Lucene40TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR; } if (offsets) { bits |= Lucene40TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR; } if (payloads) { bits |= Lucene40TermVectorsReader.STORE_PAYLOAD_WITH_TERMVECTOR; } Tvf.WriteByte((byte)bits); } public override void FinishDocument() { Debug.Assert(FieldCount == NumVectorFields); for (int i = 1; i < FieldCount; i++) { Tvd.WriteVLong(Fps[i] - Fps[i - 1]); } } private readonly BytesRef LastTerm = new BytesRef(10); // NOTE: we override addProx, so we don't need to buffer when indexing. // we also don't buffer during bulk merges. private int[] OffsetStartBuffer = new int[10]; private int[] OffsetEndBuffer = new int[10]; private BytesRef PayloadData = new BytesRef(10); private int BufferedIndex = 0; private int BufferedFreq = 0; private bool Positions = false; private bool Offsets = false; private bool Payloads = false; public override void StartTerm(BytesRef term, int freq) { int prefix = StringHelper.BytesDifference(LastTerm, term); int suffix = term.Length - prefix; Tvf.WriteVInt(prefix); Tvf.WriteVInt(suffix); Tvf.WriteBytes(term.Bytes, term.Offset + prefix, suffix); Tvf.WriteVInt(freq); LastTerm.CopyBytes(term); LastPosition = LastOffset = 0; if (Offsets && Positions) { // we might need to buffer if its a non-bulk merge OffsetStartBuffer = ArrayUtil.Grow(OffsetStartBuffer, freq); OffsetEndBuffer = ArrayUtil.Grow(OffsetEndBuffer, freq); } BufferedIndex = 0; BufferedFreq = freq; PayloadData.Length = 0; } internal int LastPosition = 0; internal int LastOffset = 0; internal int LastPayloadLength = -1; // force first payload to write its length internal BytesRef Scratch = new BytesRef(); // used only by this optimized flush below public override void AddProx(int numProx, DataInput positions, DataInput offsets) { if (Payloads) { // TODO, maybe overkill and just call super.addProx() in this case? // we do avoid buffering the offsets in RAM though. for (int i = 0; i < numProx; i++) { int code = positions.ReadVInt(); if ((code & 1) == 1) { int length = positions.ReadVInt(); Scratch.Grow(length); Scratch.Length = length; positions.ReadBytes(Scratch.Bytes, Scratch.Offset, Scratch.Length); WritePosition((int)((uint)code >> 1), Scratch); } else { WritePosition((int)((uint)code >> 1), null); } } Tvf.WriteBytes(PayloadData.Bytes, PayloadData.Offset, PayloadData.Length); } else if (positions != null) { // pure positions, no payloads for (int i = 0; i < numProx; i++) { Tvf.WriteVInt((int)((uint)positions.ReadVInt() >> 1)); } } if (offsets != null) { for (int i = 0; i < numProx; i++) { Tvf.WriteVInt(offsets.ReadVInt()); Tvf.WriteVInt(offsets.ReadVInt()); } } } public override void AddPosition(int position, int startOffset, int endOffset, BytesRef payload) { if (Positions && (Offsets || Payloads)) { // write position delta WritePosition(position - LastPosition, payload); LastPosition = position; // buffer offsets if (Offsets) { OffsetStartBuffer[BufferedIndex] = startOffset; OffsetEndBuffer[BufferedIndex] = endOffset; } BufferedIndex++; } else if (Positions) { // write position delta WritePosition(position - LastPosition, payload); LastPosition = position; } else if (Offsets) { // write offset deltas Tvf.WriteVInt(startOffset - LastOffset); Tvf.WriteVInt(endOffset - startOffset); LastOffset = endOffset; } } public override void FinishTerm() { if (BufferedIndex > 0) { // dump buffer Debug.Assert(Positions && (Offsets || Payloads)); Debug.Assert(BufferedIndex == BufferedFreq); if (Payloads) { Tvf.WriteBytes(PayloadData.Bytes, PayloadData.Offset, PayloadData.Length); } if (Offsets) { for (int i = 0; i < BufferedIndex; i++) { Tvf.WriteVInt(OffsetStartBuffer[i] - LastOffset); Tvf.WriteVInt(OffsetEndBuffer[i] - OffsetStartBuffer[i]); LastOffset = OffsetEndBuffer[i]; } } } } private void WritePosition(int delta, BytesRef payload) { if (Payloads) { int payloadLength = payload == null ? 0 : payload.Length; if (payloadLength != LastPayloadLength) { LastPayloadLength = payloadLength; Tvf.WriteVInt((delta << 1) | 1); Tvf.WriteVInt(payloadLength); } else { Tvf.WriteVInt(delta << 1); } if (payloadLength > 0) { if (payloadLength + PayloadData.Length < 0) { // we overflowed the payload buffer, just throw UOE // having > Integer.MAX_VALUE bytes of payload for a single term in a single doc is nuts. throw new System.NotSupportedException("A term cannot have more than Integer.MAX_VALUE bytes of payload data in a single document"); } PayloadData.Append(payload); } } else { Tvf.WriteVInt(delta); } } public override void Abort() { try { Dispose(); } catch (Exception ignored) { } IOUtils.DeleteFilesIgnoringExceptions(Directory, IndexFileNames.SegmentFileName(Segment, "", Lucene40TermVectorsReader.VECTORS_INDEX_EXTENSION), IndexFileNames.SegmentFileName(Segment, "", Lucene40TermVectorsReader.VECTORS_DOCUMENTS_EXTENSION), IndexFileNames.SegmentFileName(Segment, "", Lucene40TermVectorsReader.VECTORS_FIELDS_EXTENSION)); } /// <summary> /// Do a bulk copy of numDocs documents from reader to our /// streams. this is used to expedite merging, if the /// field numbers are congruent. /// </summary> private void AddRawDocuments(Lucene40TermVectorsReader reader, int[] tvdLengths, int[] tvfLengths, int numDocs) { long tvdPosition = Tvd.FilePointer; long tvfPosition = Tvf.FilePointer; long tvdStart = tvdPosition; long tvfStart = tvfPosition; for (int i = 0; i < numDocs; i++) { Tvx.WriteLong(tvdPosition); tvdPosition += tvdLengths[i]; Tvx.WriteLong(tvfPosition); tvfPosition += tvfLengths[i]; } Tvd.CopyBytes(reader.TvdStream, tvdPosition - tvdStart); Tvf.CopyBytes(reader.TvfStream, tvfPosition - tvfStart); Debug.Assert(Tvd.FilePointer == tvdPosition); Debug.Assert(Tvf.FilePointer == tvfPosition); } public override int Merge(MergeState mergeState) { // Used for bulk-reading raw bytes for term vectors int[] rawDocLengths = new int[MAX_RAW_MERGE_DOCS]; int[] rawDocLengths2 = new int[MAX_RAW_MERGE_DOCS]; int idx = 0; int numDocs = 0; for (int i = 0; i < mergeState.Readers.Count; i++) { AtomicReader reader = mergeState.Readers[i]; SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++]; Lucene40TermVectorsReader matchingVectorsReader = null; if (matchingSegmentReader != null) { TermVectorsReader vectorsReader = matchingSegmentReader.TermVectorsReader; if (vectorsReader != null && vectorsReader is Lucene40TermVectorsReader) { matchingVectorsReader = (Lucene40TermVectorsReader)vectorsReader; } } if (reader.LiveDocs != null) { numDocs += CopyVectorsWithDeletions(mergeState, matchingVectorsReader, reader, rawDocLengths, rawDocLengths2); } else { numDocs += CopyVectorsNoDeletions(mergeState, matchingVectorsReader, reader, rawDocLengths, rawDocLengths2); } } Finish(mergeState.FieldInfos, numDocs); return numDocs; } /// <summary> /// Maximum number of contiguous documents to bulk-copy /// when merging term vectors /// </summary> private const int MAX_RAW_MERGE_DOCS = 4192; private int CopyVectorsWithDeletions(MergeState mergeState, Lucene40TermVectorsReader matchingVectorsReader, AtomicReader reader, int[] rawDocLengths, int[] rawDocLengths2) { int maxDoc = reader.MaxDoc; Bits liveDocs = reader.LiveDocs; int totalNumDocs = 0; if (matchingVectorsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" for (int docNum = 0; docNum < maxDoc; ) { if (!liveDocs.Get(docNum)) { // skip deleted docs ++docNum; continue; } // We can optimize this case (doing a bulk byte copy) since the field // numbers are identical int start = docNum, numDocs = 0; do { docNum++; numDocs++; if (docNum >= maxDoc) { break; } if (!liveDocs.Get(docNum)) { docNum++; break; } } while (numDocs < MAX_RAW_MERGE_DOCS); matchingVectorsReader.RawDocs(rawDocLengths, rawDocLengths2, start, numDocs); AddRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, numDocs); totalNumDocs += numDocs; mergeState.checkAbort.Work(300 * numDocs); } } else { for (int docNum = 0; docNum < maxDoc; docNum++) { if (!liveDocs.Get(docNum)) { // skip deleted docs continue; } // NOTE: it's very important to first assign to vectors then pass it to // termVectorsWriter.addAllDocVectors; see LUCENE-1282 Fields vectors = reader.GetTermVectors(docNum); AddAllDocVectors(vectors, mergeState); totalNumDocs++; mergeState.checkAbort.Work(300); } } return totalNumDocs; } private int CopyVectorsNoDeletions(MergeState mergeState, Lucene40TermVectorsReader matchingVectorsReader, AtomicReader reader, int[] rawDocLengths, int[] rawDocLengths2) { int maxDoc = reader.MaxDoc; if (matchingVectorsReader != null) { // We can bulk-copy because the fieldInfos are "congruent" int docCount = 0; while (docCount < maxDoc) { int len = Math.Min(MAX_RAW_MERGE_DOCS, maxDoc - docCount); matchingVectorsReader.RawDocs(rawDocLengths, rawDocLengths2, docCount, len); AddRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, len); docCount += len; mergeState.checkAbort.Work(300 * len); } } else { for (int docNum = 0; docNum < maxDoc; docNum++) { // NOTE: it's very important to first assign to vectors then pass it to // termVectorsWriter.addAllDocVectors; see LUCENE-1282 Fields vectors = reader.GetTermVectors(docNum); AddAllDocVectors(vectors, mergeState); mergeState.checkAbort.Work(300); } } return maxDoc; } public override void Finish(FieldInfos fis, int numDocs) { if (Lucene40TermVectorsReader.HEADER_LENGTH_INDEX + ((long)numDocs) * 16 != Tvx.FilePointer) // this is most likely a bug in Sun JRE 1.6.0_04/_05; // we detect that the bug has struck, here, and // throw an exception to prevent the corruption from // entering the index. See LUCENE-1282 for // details. { throw new Exception("tvx size mismatch: mergedDocs is " + numDocs + " but tvx size is " + Tvx.FilePointer + " file=" + Tvx.ToString() + "; now aborting this merge to prevent index corruption"); } } /// <summary> /// Close all streams. </summary> protected override void Dispose(bool disposing) { if (disposing) { // make an effort to close all streams we can but remember and re-throw // the first exception encountered in this process IOUtils.Close(Tvx, Tvd, Tvf); Tvx = Tvd = Tvf = null; } } public override IComparer<BytesRef> Comparator { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } } }
// 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.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for EventHubsOperations. /// </summary> public static partial class EventHubsOperationsExtensions { /// <summary> /// Gets all the Event Hubs in a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639493.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<EventHubResource> ListAll(this IEventHubsOperations operations, string resourceGroupName, string namespaceName) { return operations.ListAllAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the Event Hubs in a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639493.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<EventHubResource>> ListAllAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a new Event Hub as a nested resource within a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639497.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='parameters'> /// Parameters supplied to create an Event Hub resource. /// </param> public static EventHubResource CreateOrUpdate(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, EventHubCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a new Event Hub as a nested resource within a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639497.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='parameters'> /// Parameters supplied to create an Event Hub resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EventHubResource> CreateOrUpdateAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, EventHubCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Event Hub from the specified Namespace and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639496.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='eventHubName'> /// The Event Hub name /// </param> public static void Delete(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { operations.DeleteAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Event Hub from the specified Namespace and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639496.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets an Event Hubs description for the specified Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639501.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='eventHubName'> /// The Event Hub name /// </param> public static EventHubResource Get(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { return operations.GetAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Gets an Event Hubs description for the specified Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639501.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EventHubResource> GetAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for an Event Hub. /// </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='eventHubName'> /// The Event Hub name /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for an Event Hub. /// </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='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates an AuthorizationRule for the specified Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706096.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an AuthorizationRule for the specified Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706096.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an AuthorizationRule for an Event Hub by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706097.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets an AuthorizationRule for an Event Hub by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706097.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Event Hub AuthorizationRule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706100.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static void DeleteAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Event Hub AuthorizationRule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706100.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the ACS and SAS connection strings for the Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706098.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static ResourceListKeys ListKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the ACS and SAS connection strings for the Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706098.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> ListKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the ACS and SAS connection strings for the Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706099.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the AuthorizationRule Keys /// (PrimaryKey/SecondaryKey). /// </param> public static ResourceListKeys RegenerateKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateKeysParameters parameters) { return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the ACS and SAS connection strings for the Event Hub. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt706099.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='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the AuthorizationRule Keys /// (PrimaryKey/SecondaryKey). /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> RegenerateKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the Event Hubs in a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639493.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<EventHubResource> ListAllNext(this IEventHubsOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the Event Hubs in a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639493.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<EventHubResource>> ListAllNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for an Event Hub. /// </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<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this IEventHubsOperations operations, string nextPageLink) { return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for an Event Hub. /// </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<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using UnityEngine; /// <summary> /// Manager singleton which sends update events for GUI elements. /// Currently only when an repaint event is fired by Unity. /// It also provides a lot of utils for locating and resizing of GUI custom elements. /// </summary> [ExecuteInEditMode] public class GUIScreenLayoutManager : MonoBehaviour { public static Vector2 MIN_RESOLUTION = new Vector2(480f, 320f); public static Matrix4x4 unityGUIMatrix = Matrix4x4.identity; // initialized with identity to allow earlier calls of OnGUI() that use this matrix private IGUIScreenLayout[] listeners = new IGUIScreenLayout[27]; // size controlled experimentally private int indexFirstEmpty = 0; private const float GUI_NEAR_PLANE_OFFSET = 0.01f; private const float DEG_2_RAD_0_5 = Mathf.Deg2Rad * 0.5f; private static float lastScreenWidth; private static float lastScreenHeight; private static Vector3 zero = Vector3.zero; private static Quaternion identity = Quaternion.identity; private static Vector3 scale = Vector3.zero; private static GUIScreenLayoutManager instance = null; private static bool duplicated = false; // usefull to avoid onDestroy() execution on duplicated instances being destroyed public static GUIScreenLayoutManager Instance { get { if (instance == null) { // creates a game object with this script component instance = new GameObject("GUIScreenLayoutManager").AddComponent<GUIScreenLayoutManager>(); } return instance; } } void Awake () { if (instance != null && instance != this) { duplicated = true; #if UNITY_EDITOR DestroyImmediate(this.gameObject); #else Destroy(this.gameObject); #endif } else { instance = this; DontDestroyOnLoad(gameObject); initialize(); } } void OnLevelWasLoaded(int level) { // This event is only call when the scene is loaded from Application.LoadLevel(). // If a game object already exists, this method is executed anyway before the Awake(). // So for non destroyable game objects this methods executes twice. lastScreenWidth = 0; // force the re calculation of GUI positioning } private void initialize () { // NOTE: set as current resolution so the first OnGUI event isn't a resized event. // That would cause a callback to all subscribers before correct initialization of them // Currently commented because the use of OnLevelWasLoaded() //lastScreenWidth = Screen.width; //lastScreenHeight = Screen.height; // update the GUI matrix used by several Unity GUI elements as a shortcut for GUI elems resizing setupUnityGUIMatrixForResizing(); } void OnDestroy() { for (int i=0, c=listeners.Length; i < c; ++i) listeners[i] = null; listeners = null; // this is to avoid nullifying or destroying static variables. Instance variables can be destroyed before this check if (duplicated) { duplicated = false; // reset the flag for next time return; } instance = null; } private void setupUnityGUIMatrixForResizing () { float widthRatio = ((float)Screen.width) / MIN_RESOLUTION.x; float heightRatio = ((float)Screen.height) / MIN_RESOLUTION.y; scale.Set(widthRatio, heightRatio, 1f); unityGUIMatrix = Matrix4x4.TRS(zero, identity, scale); } public void register (IGUIScreenLayout listener) { bool inserted = false; for (int i=indexFirstEmpty, c=listeners.Length; i < c; ++i) { if (listeners[i] == null) { listeners[i] = listener; inserted = true; indexFirstEmpty = i + 1; // I guess next cell is empty break; } } if (!inserted) Debug.LogError("listeners array out of space. Increment size one unit more."); } public void remove (IGUIScreenLayout listener) { int id = listener.GetHashCode(); for (int i=0, c=listeners.Length; i < c; ++i) { if (listeners[i] == null) continue; else if (id == listeners[i].GetHashCode()){ listeners[i] = null; if (i < indexFirstEmpty) indexFirstEmpty = i; break; } } } void OnGUI () { if (EventType.Repaint == Event.current.type) { // if screen is resized then need to notice all listeners if (Screen.width != lastScreenWidth || Screen.height != lastScreenHeight) { // update GUI matrix used by several Unity GUI elements as a shortcut for GUI elems resizing setupUnityGUIMatrixForResizing(); // notify to all listeners for (int i=0, c=listeners.Length; i<c; ++i) { if (listeners[i] != null) listeners[i].updateForGUI(); } // update screen dimension lastScreenWidth = Screen.width; lastScreenHeight = Screen.height; } } } /// <summary> /// Locates the GUITexture element in the screen according the layout value. /// It modifies the GUITexture's pixel inset. /// </summary> /// <param name='gt'> /// Gt. Unity'sGUITexture /// </param> /// <param name='offset'> /// Offset /// </param> /// <param name='layout'> /// Layout /// </param> public static void adjustPos (GUITexture gt, Vector2 offset, EnumScreenLayout layout) { Rect p = gt.pixelInset; switch (layout) { case EnumScreenLayout.TOP_LEFT: { p.x = offset.x; p.y = Screen.height - p.height + offset.y; break; } case EnumScreenLayout.TOP: { p.x = Screen.width/2 - p.width/2 + offset.x; p.y = Screen.height - p.height + offset.y; break; } case EnumScreenLayout.TOP_RIGHT: { p.x = Screen.width - p.width + offset.x; p.y = Screen.height - p.height + offset.y; break; } case EnumScreenLayout.CENTER_LEFT: { p.x = offset.x; p.y = Screen.height/2 - p.height/2 + offset.y; break; } case EnumScreenLayout.CENTER: { p.x = Screen.width/2 - p.width/2 + offset.x; p.y = Screen.height/2 - p.height/2 + offset.y; break; } case EnumScreenLayout.CENTER_RIGHT: { p.x = Screen.width - p.width + offset.x; p.y = Screen.height/2 - p.height/2 + offset.y; break; } case EnumScreenLayout.BOTTOM_LEFT: { p.x = offset.x; p.y = offset.y; break; } case EnumScreenLayout.BOTTOM: { p.x = Screen.width/2 - p.width + offset.x; p.y = offset.y; break; } case EnumScreenLayout.BOTTOM_RIGHT: { p.x = Screen.width - p.width + offset.x; p.y = offset.y; break; } default: break; } #if UNITY_EDITOR if (float.IsNegativeInfinity(p.x) || float.IsInfinity(p.x) || float.IsNaN(p.x)) p.x = 0f; if (float.IsNegativeInfinity(p.y) || float.IsInfinity(p.y) || float.IsNaN(p.y)) p.y = 0f; #endif gt.pixelInset = p; } /// <summary> /// Locates the transform element in the screen according the layout value. /// It depends on the way the transform originally was z-located and xy-scaled to act as a GUI element. /// </summary> /// <param name='tr'> /// Transform /// </param> /// <param name='guiElem'> /// Is the GUI element containing the info about size in pixels or as a proportion /// </param> /// <param name='offsetInPixels'> /// Offset measured in pixels. /// </param> /// <param name='layout'> /// Layout. Base screen positions /// </param> public static void adjustPos (Transform tr, GUICustomElement guiElem, Vector2 offsetInPixels, EnumScreenLayout layout) { Vector3 p = tr.localPosition; // assume the GUI element has its size as pixels Vector2 size = guiElem.virtualSize.x != 0 ? guiElem.virtualSize : guiElem.size; // convert to pixels if GUI element's size is set as a proportion if (!guiElem.sizeAsPixels) { size.x *= Screen.width; size.y *= Screen.height; } switch (layout) { case EnumScreenLayout.NONE: { Vector2 temp = screenToGUI(offsetInPixels.x, offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.TOP_LEFT: { Vector2 temp = screenToGUI(offsetInPixels.x + size.x/2f, Screen.height - size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.TOP: { Vector2 temp = screenToGUI(Screen.width/2 + offsetInPixels.x, Screen.height - size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.TOP_RIGHT: { Vector2 temp = screenToGUI(Screen.width + offsetInPixels.x - size.x/2f, Screen.height - size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.CENTER_LEFT: { Vector2 temp = screenToGUI(offsetInPixels.x + size.x/2f, Screen.height/2 + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.CENTER: { p.x = Screen.width/2 - size.x/2 + offsetInPixels.x; p.y = Screen.height/2 - size.y/2 + offsetInPixels.y; Vector2 temp = screenToGUI(Screen.width/2 + offsetInPixels.x, Screen.height/2 + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.CENTER_RIGHT: { Vector2 temp = screenToGUI(Screen.width + offsetInPixels.x - size.x/2f, Screen.height/2 + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.BOTTOM_LEFT: { Vector2 temp = screenToGUI(offsetInPixels.x + size.x/2f, size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.BOTTOM: { Vector2 temp = screenToGUI(Screen.width/2 + offsetInPixels.x, size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } case EnumScreenLayout.BOTTOM_RIGHT: { Vector2 temp = screenToGUI(Screen.width + offsetInPixels.x - size.x/2f, size.y/2f + offsetInPixels.y); p.x = temp.x; p.y = temp.y; break; } default: break; } #if UNITY_EDITOR if (float.IsNegativeInfinity(p.x) || float.IsInfinity(p.x) || float.IsNaN(p.x)) p.x = 0f; if (float.IsNegativeInfinity(p.y) || float.IsInfinity(p.y) || float.IsNaN(p.y)) p.y = 0f; #endif tr.localPosition = p; } /// <summary> /// Gets the z-pos and (w,h) scale factors for a custom GUI positioning in screen. /// The game object which wants to be transformed as a GUI element needs to be positioned at a Z coordinate /// and be scaled by the returned values. /// NOTE: the virtual plane for locating the game object is centered on screen and located in z = nearClipPlane + GUI_NEAR_PLANE_OFFSET. /// It's a virtual box with coordinates (-w/2, -h/2) to (w/2, h/2). /// </summary> /// <returns> /// Vector3. x,y = Width,Height factors. z = transform position for that axis. /// </returns> private static Vector3 getZLocationAndScaleForGUI () { Vector3 result; // position barely ahead from near clip plane float posAhead = Camera.main.nearClipPlane + GUI_NEAR_PLANE_OFFSET; // consider current cameras's facing direction (it can be rotated) // we're only interesting in z coordinate // NOTE: x and y are overwritten on next lines result = posAhead * Camera.main.transform.forward + Camera.main.transform.position; // optimized: I assume camera's forward is (0,0,1) //result.z = posAhead + Camera.main.transform.position.z; // calculate Width and Height of our virtual plane z-positioned in nearClipPlane + delta // keep z untouch (z-position of the GUI element), only set width and height if (Camera.main.orthographic) { float y = Camera.main.orthographicSize * 2f; result.y = y; result.x = (y / Screen.height) * Screen.width; } else { float y = 2f * Mathf.Tan(Camera.main.fieldOfView * DEG_2_RAD_0_5) * posAhead; result.y = y; result.x = y * Camera.main.aspect; } return result; } /// <summary> /// Converts pixel (x,y) coordinates from screen to custom GUI space. /// </summary> /// <returns> /// The x,y pixel coordinates where a transform component is located to as a GUI element. /// </returns> /// <param name='pixelX'> /// Pixel x coordinate. /// </param> /// <param name='pixelY'> /// Pixel y coordinate. /// </param> public static Vector2 screenToGUI (float pixelX, float pixelY) { Vector3 guiZposAndDimension = getZLocationAndScaleForGUI(); Vector2 result; float guiW = guiZposAndDimension.x; float guiH = guiZposAndDimension.y; // maps pixel coordinate to a box with coordinates (-w/2, -h/2) to (w/2, h/2). This is the custom GUI viewport result.x = guiW * (pixelX / Screen.width - 0.5f); result.y = guiH * (pixelY / Screen.height - 0.5f); return result; } /// <summary> /// Maps a GUI (x,y) coordinate to a (x,y) screen pixel coordinate. /// </summary> /// <returns> /// Vector2. Screen pixel X,Y /// </returns> /// <param name='guiX'> /// GUI x. X Coordinate in GUI space /// </param> /// <param name='guiY'> /// GUI y. Y Coordinate in GUI space /// </param> public static Vector2 GUIToScreen (float guiX, float guiY) { Vector3 guiZposAndDimension = getZLocationAndScaleForGUI(); Vector2 result; float guiW = guiZposAndDimension.x; float guiH = guiZposAndDimension.y; // maps GUI coordinate to screen pixels result.x = (guiX/guiW + 0.5f) * Screen.width; result.y = (guiY/guiH + 0.5f) * Screen.height; return result; } public static Vector2 sizeInGUI (Vector2 size) { // get z position and GUI space coordinates. The GUI coordinates act as scale factors Vector3 guiZposAndDimension = getZLocationAndScaleForGUI(); // imagine the size in pixels as a rect with min = (0,0) and max = size // and convert it to GUI space Vector2 result = screenToGUI(size.x, size.y); // the GUI space is a box with its (0,0) centered in screen, so we need to correct that result.x += guiZposAndDimension.x / 2f; result.y += guiZposAndDimension.y / 2f; return result; } public static Rect getPositionInScreen (GUICustomElement guiElem) { Vector3 guiPos = guiElem.transform.localPosition; // GUI custom element uses localPosition for correctly on screen location Vector2 sizeInGUI = guiElem.getSizeInGUI(); Vector2 sizeInPixels = guiElem.getSizeInPixels(); Vector2 pixelMin = GUIToScreen(guiPos.x - sizeInGUI.x/2f, guiPos.y - sizeInGUI.y/2f); return new Rect(pixelMin.x, pixelMin.y, sizeInPixels.x, sizeInPixels.y); } /// <summary> /// Sets z-position and scale (w,h) to a transform object for positioning in front of /// camera to act like a GUI element. /// The size parameter scales even more the transform to satisfy a desired size of the transform. /// NOTE: transform will be centered on screen. /// </summary> /// <param name='tr'> /// Transform of the game object to be modified for being a GUI element /// </param> /// <param name='sizeInPixels'> /// Size the element covers at screen /// </param> public static void locateForGUI (Transform tr, Vector2 sizeInPixels) { // get z position and GUI space coordinates. The GUI coordinates act as scale factors Vector3 guiZPosAndDimension = getZLocationAndScaleForGUI(); Vector3 thePos = tr.position; thePos.z = guiZPosAndDimension.z; tr.position = thePos; // apply scale to locate in GUI space. Consider user defined size Vector3 theScale = tr.localScale; theScale.x = (guiZPosAndDimension.x * sizeInPixels.x) / (float)Screen.width; theScale.y = (guiZPosAndDimension.y * sizeInPixels.y) / (float)Screen.height; theScale.z = 0f; tr.localScale = theScale; // modify local position (not world position) /*Vector3 theLocalPos = tr.localPosition; // x position doesn't work yet theLocalPos.y = guiZPosAndDimension.y * 0.5f * (1f - Mathf.Abs(sizeInPixels.y)) * Mathf.Sign(sizeInPixels.y); tr.localPosition = theLocalPos;*/ } }
using J2N.Numerics; using YAF.Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace YAF.Lucene.Net.Store { /* * 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 CodecUtil = YAF.Lucene.Net.Codecs.CodecUtil; using CorruptIndexException = YAF.Lucene.Net.Index.CorruptIndexException; using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames; using IOUtils = YAF.Lucene.Net.Util.IOUtils; /// <summary> /// Class for accessing a compound stream. /// This class implements a directory, but is limited to only read operations. /// Directory methods that would normally modify data throw an exception. /// <para/> /// All files belonging to a segment have the same name with varying extensions. /// The extensions correspond to the different file formats used by the <see cref="Codecs.Codec"/>. /// When using the Compound File format these files are collapsed into a /// single <c>.cfs</c> file (except for the <see cref="Codecs.LiveDocsFormat"/>, with a /// corresponding <c>.cfe</c> file indexing its sub-files. /// <para/> /// Files: /// <list type="bullet"> /// <item><description><c>.cfs</c>: An optional "virtual" file consisting of all the other /// index files for systems that frequently run out of file handles.</description></item> /// <item><description><c>.cfe</c>: The "virtual" compound file's entry table holding all /// entries in the corresponding .cfs file.</description></item> /// </list> /// <para>Description:</para> /// <list type="bullet"> /// <item><description>Compound (.cfs) --&gt; Header, FileData <sup>FileCount</sup></description></item> /// <item><description>Compound Entry Table (.cfe) --&gt; Header, FileCount, &lt;FileName, /// DataOffset, DataLength&gt; <sup>FileCount</sup>, Footer</description></item> /// <item><description>Header --&gt; <see cref="CodecUtil.WriteHeader"/></description></item> /// <item><description>FileCount --&gt; <see cref="DataOutput.WriteVInt32"/></description></item> /// <item><description>DataOffset,DataLength --&gt; <see cref="DataOutput.WriteInt64"/></description></item> /// <item><description>FileName --&gt; <see cref="DataOutput.WriteString"/></description></item> /// <item><description>FileData --&gt; raw file data</description></item> /// <item><description>Footer --&gt; <see cref="CodecUtil.WriteFooter"/></description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>FileCount indicates how many files are contained in this compound file. /// The entry table that follows has that many entries.</description></item> /// <item><description>Each directory entry contains a long pointer to the start of this file's data /// section, the files length, and a <see cref="string"/> with that file's name.</description></item> /// </list> /// <para/> /// @lucene.experimental /// </summary> public sealed class CompoundFileDirectory : BaseDirectory { /// <summary> /// Offset/Length for a slice inside of a compound file </summary> public sealed class FileEntry { internal long Offset { get; set; } internal long Length { get; set; } } private readonly Directory directory; private readonly string fileName; private readonly int readBufferSize; private readonly IDictionary<string, FileEntry> entries; private readonly bool openForWrite; private static readonly IDictionary<string, FileEntry> SENTINEL = Collections.EmptyMap<string, FileEntry>(); private readonly CompoundFileWriter writer; private readonly IndexInputSlicer handle; /// <summary> /// Create a new <see cref="CompoundFileDirectory"/>. /// </summary> public CompoundFileDirectory(Directory directory, string fileName, IOContext context, bool openForWrite) { this.directory = directory; this.fileName = fileName; this.readBufferSize = BufferedIndexInput.GetBufferSize(context); this.IsOpen = false; this.openForWrite = openForWrite; if (!openForWrite) { bool success = false; handle = directory.CreateSlicer(fileName, context); try { this.entries = ReadEntries(handle, directory, fileName); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(handle); } } this.IsOpen = true; writer = null; } else { Debug.Assert(!(directory is CompoundFileDirectory), "compound file inside of compound file: " + fileName); this.entries = SENTINEL; this.IsOpen = true; writer = new CompoundFileWriter(directory, fileName); handle = null; } } // LUCENENET NOTE: These MUST be sbyte because they can be negative private static readonly sbyte CODEC_MAGIC_BYTE1 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(24); private static readonly sbyte CODEC_MAGIC_BYTE2 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(16); private static readonly sbyte CODEC_MAGIC_BYTE3 = (sbyte)CodecUtil.CODEC_MAGIC.TripleShift(8); private static readonly sbyte CODEC_MAGIC_BYTE4 = (sbyte)CodecUtil.CODEC_MAGIC; /// <summary> /// Helper method that reads CFS entries from an input stream </summary> private static IDictionary<string, FileEntry> ReadEntries(IndexInputSlicer handle, Directory dir, string name) { IOException priorE = null; IndexInput stream = null; ChecksumIndexInput entriesStream = null; // read the first VInt. If it is negative, it's the version number // otherwise it's the count (pre-3.1 indexes) try { IDictionary<string, FileEntry> mapping; #pragma warning disable 612, 618 stream = handle.OpenFullSlice(); #pragma warning restore 612, 618 int firstInt = stream.ReadVInt32(); // impossible for 3.0 to have 63 files in a .cfs, CFS writer was not visible // and separate norms/etc are outside of cfs. if (firstInt == CODEC_MAGIC_BYTE1) { sbyte secondByte = (sbyte)stream.ReadByte(); sbyte thirdByte = (sbyte)stream.ReadByte(); sbyte fourthByte = (sbyte)stream.ReadByte(); if (secondByte != CODEC_MAGIC_BYTE2 || thirdByte != CODEC_MAGIC_BYTE3 || fourthByte != CODEC_MAGIC_BYTE4) { throw new CorruptIndexException("Illegal/impossible header for CFS file: " + secondByte + "," + thirdByte + "," + fourthByte); } int version = CodecUtil.CheckHeaderNoMagic(stream, CompoundFileWriter.DATA_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT); string entriesFileName = IndexFileNames.SegmentFileName( IndexFileNames.StripExtension(name), "", IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION); entriesStream = dir.OpenChecksumInput(entriesFileName, IOContext.READ_ONCE); CodecUtil.CheckHeader(entriesStream, CompoundFileWriter.ENTRY_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT); int numEntries = entriesStream.ReadVInt32(); mapping = new Dictionary<string, FileEntry>(numEntries); for (int i = 0; i < numEntries; i++) { FileEntry fileEntry = new FileEntry(); string id = entriesStream.ReadString(); FileEntry previous = mapping.Put(id, fileEntry); if (previous != null) { throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + entriesStream); } fileEntry.Offset = entriesStream.ReadInt64(); fileEntry.Length = entriesStream.ReadInt64(); } if (version >= CompoundFileWriter.VERSION_CHECKSUM) { CodecUtil.CheckFooter(entriesStream); } else { #pragma warning disable 612, 618 CodecUtil.CheckEOF(entriesStream); #pragma warning restore 612, 618 } } else { // TODO remove once 3.x is not supported anymore mapping = ReadLegacyEntries(stream, firstInt); } return mapping; } catch (IOException ioe) { priorE = ioe; } finally { IOUtils.DisposeWhileHandlingException(priorE, stream, entriesStream); } // this is needed until Java 7's real try-with-resources: throw new InvalidOperationException("impossible to get here"); } private static IDictionary<string, FileEntry> ReadLegacyEntries(IndexInput stream, int firstInt) { IDictionary<string, FileEntry> entries = new Dictionary<string, FileEntry>(); int count; bool stripSegmentName; if (firstInt < CompoundFileWriter.FORMAT_PRE_VERSION) { if (firstInt < CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX) { throw new CorruptIndexException("Incompatible format version: " + firstInt + " expected >= " + CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX + " (resource: " + stream + ")"); } // It's a post-3.1 index, read the count. count = stream.ReadVInt32(); stripSegmentName = false; } else { count = firstInt; stripSegmentName = true; } // read the directory and init files long streamLength = stream.Length; FileEntry entry = null; for (int i = 0; i < count; i++) { long offset = stream.ReadInt64(); if (offset < 0 || offset > streamLength) { throw new CorruptIndexException("Invalid CFS entry offset: " + offset + " (resource: " + stream + ")"); } string id = stream.ReadString(); if (stripSegmentName) { // Fix the id to not include the segment names. this is relevant for // pre-3.1 indexes. id = IndexFileNames.StripSegmentName(id); } if (entry != null) { // set length of the previous entry entry.Length = offset - entry.Offset; } entry = new FileEntry(); entry.Offset = offset; FileEntry previous = entries.Put(id, entry); if (previous != null) { throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + stream); } } // set the length of the final entry if (entry != null) { entry.Length = streamLength - entry.Offset; } return entries; } public Directory Directory { get { return directory; } } public string Name { get { return fileName; } } protected override void Dispose(bool disposing) { lock (this) { if (disposing) { if (!IsOpen) { // allow double close - usually to be consistent with other closeables return; // already closed } IsOpen = false; if (writer != null) { Debug.Assert(openForWrite); writer.Dispose(); } else { IOUtils.Dispose(handle); } } } } public override IndexInput OpenInput(string name, IOContext context) { lock (this) { EnsureOpen(); Debug.Assert(!openForWrite); string id = IndexFileNames.StripSegmentName(name); if (!entries.TryGetValue(id, out FileEntry entry) || entry == null) { throw new FileNotFoundException("No sub-file with id " + id + " found (fileName=" + name + " files: " + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", entries.Keys) + ")"); } return handle.OpenSlice(name, entry.Offset, entry.Length); } } /// <summary> /// Returns an array of strings, one for each file in the directory. </summary> public override string[] ListAll() { EnsureOpen(); string[] res; if (writer != null) { res = writer.ListAll(); } else { res = entries.Keys.ToArray(); // Add the segment name string seg = IndexFileNames.ParseSegmentName(fileName); for (int i = 0; i < res.Length; i++) { res[i] = seg + res[i]; } } return res; } /// <summary> /// Returns true iff a file with the given name exists. </summary> [Obsolete("this method will be removed in 5.0")] public override bool FileExists(string name) { EnsureOpen(); if (this.writer != null) { return writer.FileExists(name); } return entries.ContainsKey(IndexFileNames.StripSegmentName(name)); } /// <summary> /// Not implemented </summary> /// <exception cref="NotSupportedException"> always: not supported by CFS </exception> public override void DeleteFile(string name) { throw new NotSupportedException(); } /// <summary> /// Not implemented </summary> /// <exception cref="NotSupportedException"> always: not supported by CFS </exception> public void RenameFile(string from, string to) { throw new NotSupportedException(); } /// <summary> /// Returns the length of a file in the directory. </summary> /// <exception cref="IOException"> if the file does not exist </exception> public override long FileLength(string name) { EnsureOpen(); if (this.writer != null) { return writer.FileLength(name); } FileEntry e = entries[IndexFileNames.StripSegmentName(name)]; if (e == null) { throw new FileNotFoundException(name); } return e.Length; } public override IndexOutput CreateOutput(string name, IOContext context) { EnsureOpen(); return writer.CreateOutput(name, context); } public override void Sync(ICollection<string> names) { throw new NotSupportedException(); } /// <summary> /// Not implemented </summary> /// <exception cref="NotSupportedException"> always: not supported by CFS </exception> public override Lock MakeLock(string name) { throw new NotSupportedException(); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) { EnsureOpen(); Debug.Assert(!openForWrite); string id = IndexFileNames.StripSegmentName(name); if (!entries.TryGetValue(id, out FileEntry entry) || entry == null) { throw new FileNotFoundException("No sub-file with id " + id + " found (fileName=" + name + " files: " + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", entries.Keys) + ")"); } return new IndexInputSlicerAnonymousInnerClassHelper(this, entry); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly CompoundFileDirectory outerInstance; private FileEntry entry; public IndexInputSlicerAnonymousInnerClassHelper(CompoundFileDirectory outerInstance, FileEntry entry) { this.outerInstance = outerInstance; this.entry = entry; } protected override void Dispose(bool disposing) { } public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { return outerInstance.handle.OpenSlice(sliceDescription, entry.Offset + offset, length); } [Obsolete("Only for reading CFS files from 3.x indexes.")] public override IndexInput OpenFullSlice() { return OpenSlice("full-slice", 0, entry.Length); } } public override string ToString() { return "CompoundFileDirectory(file=\"" + fileName + "\" in dir=" + directory + ")"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestAllZerosInt16() { var test = new BooleanBinaryOpTest__TestAllZerosInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestAllZerosInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int Op2ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private BooleanBinaryOpTest__DataTable<Int16, Int16> _dataTable; static BooleanBinaryOpTest__TestAllZerosInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestAllZerosInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestAllZeros( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestAllZeros( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestAllZeros( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestAllZeros( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse41.TestAllZeros(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestAllZeros(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestAllZeros(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestAllZerosInt16(); var result = Sse41.TestAllZeros(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestAllZeros(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestAllZeros)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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. #if FEATURE_CTYPES using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Reflection.Emit; using System.Runtime.InteropServices; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.Scripting.Utils; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { private static WeakDictionary<PythonType, Dictionary<int, ArrayType>> _arrayTypes = new WeakDictionary<PythonType, Dictionary<int, ArrayType>>(); /// <summary> /// The meta class for ctypes array instances. /// </summary> [PythonType, PythonHidden] public class ArrayType : PythonType, INativeType { private int _length; private INativeType _type; public ArrayType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict) : base(context, name, bases, dict) { // TODO: is using TryGetBoundAttr the proper way to check the base types? similarly on the _type_ check if (!dict.TryGetValue("_length_", out object len) && !TryGetBoundAttr(context, this, "_length_", out len)) { throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"); } int iLen = len switch { BigInteger bi => checked((int)bi), int i => i, _ => throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"), }; if (iLen < 0) throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"); // TODO: ValueError with 3.8 object type; if (!dict.TryGetValue("_type_", out type) && !TryGetBoundAttr(context, this, "_type_", out type)) { throw PythonOps.AttributeError("class must define a '_type_' attribute"); } _length = iLen; _type = (INativeType)type; if (_type is SimpleType st) { if (st._type == SimpleTypeKind.Char) { SetCustomMember(context, "value", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetCharArrayValue))), NameType.Property | NameType.Python ) ); SetCustomMember(context, "raw", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetCharArrayRaw))), NameType.Property | NameType.Python ) ); } else if (st._type == SimpleTypeKind.WChar) { SetCustomMember(context, "value", new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod(nameof(CTypes.GetWCharArrayValue))), NameType.Property | NameType.Python ) ); } } } private ArrayType(Type underlyingSystemType) : base(underlyingSystemType) { } public _Array from_address(CodeContext/*!*/ context, int ptr) { _Array res = (_Array)CreateInstance(context); res.SetAddress(new IntPtr(ptr)); return res; } public _Array from_address(CodeContext/*!*/ context, BigInteger ptr) { _Array res = (_Array)CreateInstance(context); res.SetAddress(new IntPtr((long)ptr)); return res; } public _Array from_buffer(CodeContext/*!*/ context, ArrayModule.array array, [DefaultParameterValue(0)] int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); _Array res = (_Array)CreateInstance(context); IntPtr addr = array.GetArrayAddress(); res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size); res._memHolder.AddObject("ffffffff", array); return res; } public _Array from_buffer_copy(CodeContext/*!*/ context, ArrayModule.array array, [DefaultParameterValue(0)] int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); _Array res = (_Array)CreateInstance(context); res._memHolder = new MemoryHolder(((INativeType)this).Size); res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size)); GC.KeepAlive(array); return res; } public _Array from_buffer_copy(CodeContext/*!*/ context, Bytes array, [DefaultParameterValue(0)] int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); _Array res = (_Array)CreateInstance(context); res._memHolder = new MemoryHolder(((INativeType)this).Size); for (int i = 0; i < ((INativeType)this).Size; i++) { res._memHolder.WriteByte(i, ((IList<byte>)array)[i]); } return res; } public _Array from_buffer_copy(CodeContext/*!*/ context, string data, int offset = 0) { ValidateArraySizes(data, offset, ((INativeType)this).Size); _Array res = (_Array)CreateInstance(context); res._memHolder = new MemoryHolder(((INativeType)this).Size); for (int i = 0; i < ((INativeType)this).Size; i++) { res._memHolder.WriteByte(i, (byte)data[i]); } return res; } /// <summary> /// Converts an object into a function call parameter. /// </summary> public object from_param(object obj) { return null; } internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new ArrayType(underlyingSystemType)); } public static ArrayType/*!*/ operator *(ArrayType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, ArrayType type) { return MakeArrayType(type, count); } #region INativeType Members int INativeType.Size { get { return GetSize(); } } private int GetSize() { return _length * _type.Size; } int INativeType.Alignment { get { return _type.Alignment; } } object INativeType.GetValue(MemoryHolder owner, object readingFrom, int offset, bool raw) { if (_type is SimpleType st) { if (st._type == SimpleTypeKind.Char) { var str = owner.ReadBytes(offset, _length); // remove any trailing nulls for (int i = 0; i < str.Count; i++) { if (str[i] == 0) { return new Bytes(str.Substring(0, i)); } } return str; } if (st._type == SimpleTypeKind.WChar) { string str = owner.ReadUnicodeString(offset, _length); // remove any trailing nulls for (int i = 0; i < str.Length; i++) { if (str[i] == '\x00') { return str.Substring(0, i); } } return str; } } _Array arr = (_Array)CreateInstance(Context.SharedContext); arr._memHolder = new MemoryHolder(owner.UnsafeAddress.Add(offset), ((INativeType)this).Size, owner); return arr; } internal object GetRawValue(MemoryHolder owner, int offset) { Debug.Assert(_type is SimpleType st && st._type == SimpleTypeKind.Char); return owner.ReadBytes(offset, _length); } internal void SetRawValue(MemoryHolder owner, int offset, object value) { Debug.Assert(_type is SimpleType st && st._type == SimpleTypeKind.Char); if (value is IBufferProtocol bufferProtocol) { var buffer = bufferProtocol.GetBuffer(); var span = buffer.AsReadOnlySpan(); if (span.Length > _length) { throw PythonOps.ValueError("byte string too long ({0}, maximum length {1})", span.Length, _length); } owner.WriteSpan(offset, span); return; } throw PythonOps.TypeErrorForBytesLikeTypeMismatch(value); } object INativeType.SetValue(MemoryHolder address, int offset, object value) { if (_type is SimpleType st) { if (st._type == SimpleTypeKind.Char) { if (value is Bytes bytes) { if (bytes.Count > _length) { throw PythonOps.ValueError("byte string too long ({0}, maximum length {1})", bytes.Count, _length); } WriteBytes(address, offset, bytes); return null; } throw PythonOps.TypeError("bytes expected instead of {0} instance", PythonOps.GetPythonTypeName(value)); } if (st._type == SimpleTypeKind.WChar) { if (value is string str) { if (str.Length > _length) { throw PythonOps.ValueError("string too long ({0}, maximum length {1})", str.Length, _length); } WriteString(address, offset, str); return null; } throw PythonOps.TypeError("unicode string expected instead of {0} instance", PythonOps.GetPythonTypeName(value)); } } object[] arrArgs = value as object[]; if (arrArgs == null) { if (value is PythonTuple pt) { arrArgs = pt._data; } } if (arrArgs != null) { if (arrArgs.Length > _length) { throw PythonOps.RuntimeError("invalid index"); } for (int i = 0; i < arrArgs.Length; i++) { _type.SetValue(address, checked(offset + i * _type.Size), arrArgs[i]); } } else { if (value is _Array arr && arr.NativeType == this) { arr._memHolder.CopyTo(address, offset, ((INativeType)this).Size); return arr._memHolder.EnsureObjects(); } throw PythonOps.TypeError("unexpected {0} instance, got {1}", Name, PythonOps.GetPythonTypeName(value)); } return null; } private void WriteBytes(MemoryHolder address, int offset, Bytes bytes) { SimpleType st = (SimpleType)_type; Debug.Assert(st._type == SimpleTypeKind.Char && bytes.Count <= _length); address.WriteSpan(offset, bytes.AsSpan()); if (bytes.Count < _length) { address.WriteByte(checked(offset + bytes.Count), 0); } } private void WriteString(MemoryHolder address, int offset, string str) { SimpleType st = (SimpleType)_type; Debug.Assert(st._type == SimpleTypeKind.WChar && str.Length <= _length); if (str.Length < _length) { str = str + '\x00'; } address.WriteUnicodeString(offset, str); } Type/*!*/ INativeType.GetNativeType() { return typeof(IntPtr); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { Type argumentType = argIndex.Type; Label done = method.DefineLabel(); if (!argumentType.IsValueType) { Label next = method.DefineLabel(); argIndex.Emit(method); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Bne_Un, next); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Br, done); method.MarkLabel(next); } argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.CheckCDataType))); method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod()); method.MarkLabel(done); return null; } Type/*!*/ INativeType.GetPythonType() { return ((INativeType)this).GetNativeType(); } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { // TODO: Implement me value.Emit(method); } #endregion internal int Length { get { return _length; } } internal INativeType ElementType { get { return _type; } } string INativeType.TypeFormat { get { return _type.TypeFormat; } } internal string ShapeAndFormatRepr() { string size = "(" + Length; INativeType elemType = _type; while (elemType is ArrayType arrayType) { size += "," + arrayType.Length; elemType = arrayType.ElementType; } size += ")"; return size + _type.TypeFormat; } } private static ArrayType/*!*/ MakeArrayType(PythonType type, int count) { if (count < 0) { throw PythonOps.ValueError("cannot multiply ctype by negative number"); } lock (_arrayTypes) { if (!_arrayTypes.TryGetValue(type, out Dictionary<int, ArrayType> countDict)) { _arrayTypes[type] = countDict = new Dictionary<int, ArrayType>(); } if (!countDict.TryGetValue(count, out ArrayType res)) { res = countDict[count] = new ArrayType(type.Context.SharedContext, type.Name + "_Array_" + count, PythonTuple.MakeTuple(Array), PythonOps.MakeDictFromItems(new object[] { type, "_type_", count, "_length_" }) ); } return res; } } } } #endif
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable { private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance(); internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty; protected ExpressionCompilerTestBase() { // We never want to swallow Exceptions (generate a non-fatal Watson) when running tests. ExpressionEvaluatorFatalError.IsFailFastEnabled = true; } public override void Dispose() { base.Dispose(); foreach (var instance in _runtimeInstances) { instance.Dispose(); } _runtimeInstances.Free(); } internal static void WithRuntimeInstance(Compilation compilation, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, null, validator: validator); } internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, references, includeLocalSignatures: true, includeIntrinsicAssembly: true, validator: validator); } internal static void WithRuntimeInstance( Compilation compilation, IEnumerable<MetadataReference> references, bool includeLocalSignatures, bool includeIntrinsicAssembly, Action<RuntimeInstance> validator) { foreach (var debugFormat in new[] { DebugInformationFormat.Pdb, DebugInformationFormat.PortablePdb }) { using (var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly)) { validator(instance); } } } internal RuntimeInstance CreateRuntimeInstance(IEnumerable<ModuleInstance> modules) { var instance = RuntimeInstance.Create(modules); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( Compilation compilation, IEnumerable<MetadataReference> references = null, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly: true); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( ModuleInstance module, IEnumerable<MetadataReference> references) { var instance = RuntimeInstance.Create(module, references, DebugInformationFormat.Pdb); _runtimeInstances.Add(instance); return instance; } internal static void GetContextState( RuntimeInstance runtime, string methodOrTypeName, out ImmutableArray<MetadataBlock> blocks, out Guid moduleVersionId, out ISymUnmanagedReader symReader, out int methodOrTypeToken, out int localSignatureToken) { var moduleInstances = runtime.Modules; blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock); var compilation = blocks.ToCompilation(); var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName); var module = (PEModuleSymbol)methodOrType.ContainingModule; var id = module.Module.GetModuleVersionIdOrThrow(); var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id); moduleVersionId = id; symReader = (ISymUnmanagedReader)moduleInstance.SymReader; EntityHandle methodOrTypeHandle; if (methodOrType.Kind == SymbolKind.Method) { methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle; localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle); } else { methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle; localSignatureToken = -1; } MetadataReader reader = null; // null should be ok methodOrTypeToken = reader.GetToken(methodOrTypeHandle); } internal static EvaluationContext CreateMethodContext( RuntimeInstance runtime, string methodName, int atLineNumber = -1) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber); return EvaluationContext.CreateMethodContext( default(CSharpMetadataContext), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); } internal static EvaluationContext CreateTypeContext( RuntimeInstance runtime, string typeName) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); return EvaluationContext.CreateTypeContext( default(CSharpMetadataContext), blocks, moduleVersionId, typeToken); } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, int atLineNumber = -1, bool includeSymbols = true) { ResultProperties resultProperties; string error; var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols); Assert.Null(error); return result; } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, out ResultProperties resultProperties, out string error, int atLineNumber = -1, bool includeSymbols = true) { var compilation0 = CreateCompilationWithMscorlib( source, options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe); var runtime = CreateRuntimeInstance(compilation0, debugFormat: includeSymbols ? DebugInformationFormat.Pdb : 0); var context = CreateMethodContext(runtime, methodName, atLineNumber); var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return testData; } /// <summary> /// Verify all type parameters from the method /// are from that method or containing types. /// </summary> internal static void VerifyTypeParameters(MethodSymbol method) { Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType)); AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument)); AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type)); VerifyTypeParameters(method.ContainingType); } internal static void VerifyLocal( CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName = null, DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None, string expectedILOpt = null, bool expectedGeneric = false, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>( testData, typeName, localAndMethod, expectedMethodName, expectedLocalName, expectedLocalDisplayName ?? expectedLocalName, expectedFlags, VerifyTypeParameters, expectedILOpt, expectedGeneric, expectedValueSourcePath, expectedValueSourceLine); } /// <summary> /// Verify all type parameters from the type /// are from that type or containing types. /// </summary> internal static void VerifyTypeParameters(NamedTypeSymbol type) { AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument)); var container = type.ContainingType; if ((object)container != null) { VerifyTypeParameters(container); } } internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature) { string[] parameterTypeNames; var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames); var candidates = compilation.GetMembers(methodOrTypeName); var methodOrType = (parameterTypeNames == null) ? candidates.FirstOrDefault() : candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.Type.Name))); Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'."); return methodOrType; } internal static Alias VariableAlias(string name, Type type = null) { return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName) { return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ObjectIdAlias(uint id, Type type = null) { return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName) { Assert.NotEqual(0u, id); // Not a valid id. var name = $"${id}"; return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ReturnValueAlias(int id = -1, Type type = null) { return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName) { var name = $"Method M{(id < 0 ? "" : id.ToString())} returned"; var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}"; return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ExceptionAlias(Type type = null, bool stowed = false) { return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed); } internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false) { var name = "Error"; var fullName = stowed ? "$stowedexception" : "$exception"; var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception; return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, ReadOnlyCollection<byte> payload) { return new Alias(kind, name, fullName, type, (payload == null) ? default(Guid) : CustomTypeInfo.PayloadTypeId, payload); } internal static MethodDebugInfo<TypeSymbol, LocalSymbol> GetMethodDebugInfo(RuntimeInstance runtime, string qualifiedMethodName, int ilOffset = 0) { var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(); var peMethod = peCompilation.GlobalNamespace.GetMember<PEMethodSymbol>(qualifiedMethodName); var peModule = (PEModuleSymbol)peMethod.ContainingModule; var symReader = runtime.Modules.Single(mi => mi.ModuleVersionId == peModule.Module.GetModuleVersionIdOrThrow()).SymReader; var symbolProvider = new CSharpEESymbolProvider(peCompilation.SourceAssembly, peModule, peMethod); return MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo((ISymUnmanagedReader3)symReader, symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion: 1, ilOffset: ilOffset, isVisualBasicMethod: false); } internal static SynthesizedAttributeData GetDynamicAttributeIfAny(IMethodSymbol method) { return GetAttributeIfAny(method, "System.Runtime.CompilerServices.DynamicAttribute"); } internal static SynthesizedAttributeData GetTupleElementNamesAttributeIfAny(IMethodSymbol method) { return GetAttributeIfAny(method, "System.Runtime.CompilerServices.TupleElementNamesAttribute"); } internal static SynthesizedAttributeData GetAttributeIfAny(IMethodSymbol method, string typeName) { return method.GetSynthesizedAttributes(forReturnType: true). Where(a => a.AttributeClass.ToTestDisplayString() == typeName). SingleOrDefault(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.Mocks; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class ReplEvaluatorTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] public void ExecuteTest() { using (var evaluator = MakeEvaluator()) { var window = new MockReplWindow(evaluator); evaluator._Initialize(window); TestOutput(window, evaluator, "print 'hello'", true, "hello"); TestOutput(window, evaluator, "42", true, "42"); TestOutput(window, evaluator, "for i in xrange(2): print i\n", true, "0", "1"); TestOutput(window, evaluator, "raise Exception()\n", false, "Traceback (most recent call last):", " File \"<stdin>\", line 1, in <module>", "Exception"); TestOutput(window, evaluator, "try:\r\n print 'hello'\r\nexcept:\r\n print 'goodbye'\r\n \r\n ", true, "hello"); TestOutput(window, evaluator, "try:\r\n print 'hello'\r\nfinally:\r\n print 'goodbye'\r\n \r\n ", true, "hello", "goodbye"); TestOutput(window, evaluator, "import sys", true); TestOutput(window, evaluator, "sys.exit(0)", false); } } [TestMethod, Priority(3)] public void TestAbort() { using (var evaluator = MakeEvaluator()) { var window = new MockReplWindow(evaluator); evaluator._Initialize(window); TestOutput( window, evaluator, "while True: pass\n", false, (completed) => { Assert.IsTrue(!completed); Thread.Sleep(1000); evaluator.AbortExecution(); }, false, 20000, "KeyboardInterrupt" ); } } [TestMethod, Priority(1)] public void TestCanExecute() { using (var evaluator = MakeEvaluator()) { Assert.IsTrue(evaluator.CanExecuteCode("print 'hello'")); Assert.IsTrue(evaluator.CanExecuteCode("42")); Assert.IsTrue(evaluator.CanExecuteCode("for i in xrange(2): print i\r\n\r\n")); Assert.IsTrue(evaluator.CanExecuteCode("raise Exception()\n")); Assert.IsTrue(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nexcept:\r\n print 'goodbye'\r\n \r\n ")); Assert.IsTrue(evaluator.CanExecuteCode("try:\r\n print 'hello'\r\nfinally:\r\n print 'goodbye'\r\n \r\n ")); Assert.IsFalse(evaluator.CanExecuteCode("x = \\")); Assert.IsTrue(evaluator.CanExecuteCode("x = \\\r\n42\r\n\r\n")); } } [TestMethod, Priority(3)] public async Task TestGetAllMembers() { using (var evaluator = MakeEvaluator()) { var window = new MockReplWindow(evaluator); await evaluator._Initialize(window); await evaluator.ExecuteText("globals()['my_new_value'] = 123"); var names = evaluator.GetMemberNames(""); Assert.IsNotNull(names); AssertUtil.ContainsAtLeast(names.Select(m => m.Name), "my_new_value"); } } [TestMethod, Priority(1)] public void ReplSplitCodeTest() { // http://pytools.codeplex.com/workitem/606 var testCases = new[] { new { Code = @"def f(): pass def g(): pass f() g()", Expected = new[] { "def f():\r\n pass\r\n", "def g():\r\n pass\r\n", "f()", "g()" } }, new { Code = @"def f(): pass f() def g(): pass f() g()", Expected = new[] { "def f():\r\n pass\r\n", "f()", "def g():\r\n pass\r\n", "f()", "g()" } }, new { Code = @"def f(): pass f() f() def g(): pass f() g()", Expected = new[] { "def f():\r\n pass\r\n", "f()", "f()", "def g():\r\n pass\r\n", "f()", "g()" } }, new { Code = @" def f(): pass f() f() def g(): pass f() g()", Expected = new[] { "def f():\r\n pass\r\n", "f()", "f()", "def g():\r\n pass\r\n", "f()", "g()" } } }; using (var evaluator = MakeEvaluator()) { foreach (var testCase in testCases) { AssertUtil.AreEqual(evaluator.JoinCode(evaluator.SplitCode(testCase.Code)), testCase.Expected); } } } private static PythonReplEvaluator MakeEvaluator() { var python = PythonPaths.Python27 ?? PythonPaths.Python27_x64 ?? PythonPaths.Python26 ?? PythonPaths.Python26_x64; python.AssertInstalled(); var provider = new SimpleFactoryProvider(python.InterpreterPath, python.InterpreterPath); var eval = new PythonReplEvaluator(provider.GetInterpreterFactories().First(), PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions()); Assert.IsTrue(eval._Initialize(new MockReplWindow(eval)).Result.IsSuccessful); return eval; } class SimpleFactoryProvider : IPythonInterpreterFactoryProvider { private readonly string _pythonExe; private readonly string _pythonWinExe; private readonly string _pythonLib; public SimpleFactoryProvider(string pythonExe, string pythonWinExe) { _pythonExe = pythonExe; _pythonWinExe = pythonWinExe; _pythonLib = Path.Combine(Path.GetDirectoryName(pythonExe), "Lib"); } public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() { yield return InterpreterFactoryCreator.CreateInterpreterFactory(new InterpreterFactoryCreationOptions { LanguageVersion = new Version(2, 6), Description = "Python", InterpreterPath = _pythonExe, WindowInterpreterPath = _pythonWinExe, LibraryPath = _pythonLib, PathEnvironmentVariableName = "PYTHONPATH", Architecture = ProcessorArchitecture.X86, WatchLibraryForNewModules = false }); } public event EventHandler InterpreterFactoriesChanged { add { } remove { } } } private static void TestOutput(MockReplWindow window, PythonReplEvaluator evaluator, string code, bool success, params string[] expectedOutput) { TestOutput(window, evaluator, code, success, null, true, 3000, expectedOutput); } private static void TestOutput(MockReplWindow window, PythonReplEvaluator evaluator, string code, bool success, Action<bool> afterExecute, bool equalOutput, int timeout = 3000, params string[] expectedOutput) { window.ClearScreen(); bool completed = false; var task = evaluator.ExecuteText(code).ContinueWith(completedTask => { Assert.AreEqual(success, completedTask.Result.IsSuccessful); var output = success ? window.Output : window.Error; if (equalOutput) { if (output.Length == 0) { Assert.IsTrue(expectedOutput.Length == 0); } else { // don't count ending \n as new empty line output = output.Replace("\r\n", "\n"); if (output[output.Length - 1] == '\n') { output = output.Remove(output.Length - 1, 1); } var lines = output.Split('\n'); if (lines.Length != expectedOutput.Length) { for (int i = 0; i < lines.Length; i++) { Console.WriteLine("{0}: {1}", i, lines[i].ToString()); } } Assert.AreEqual(lines.Length, expectedOutput.Length); for (int i = 0; i < expectedOutput.Length; i++) { Assert.AreEqual(lines[i], expectedOutput[i]); } } } else { foreach (var line in expectedOutput) { Assert.IsTrue(output.Contains(line), string.Format("'{0}' does not contain '{1}'", output, line)); } } completed = true; }); if (afterExecute != null) { afterExecute(completed); } try { task.Wait(timeout); } catch (AggregateException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } if (!completed) { Assert.Fail(string.Format("command didn't complete in {0} seconds", timeout / 1000.0)); } } [TestMethod, Priority(1)] public void NoInterpreterPath() { // http://pytools.codeplex.com/workitem/662 var emptyFact = InterpreterFactoryCreator.CreateInterpreterFactory( new InterpreterFactoryCreationOptions() { Description = "Test Interpreter" } ); var replEval = new PythonReplEvaluator(emptyFact, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions()); var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow); var execute = replEval.ExecuteText("42"); Console.WriteLine(replWindow.Error); Assert.IsTrue( replWindow.Error.Contains("Test Interpreter cannot be started"), "Expected: <Test Interpreter cannot be started>\r\nActual: <" + replWindow.Error + ">" ); } [TestMethod, Priority(1)] public void BadInterpreterPath() { // http://pytools.codeplex.com/workitem/662 var emptyFact = InterpreterFactoryCreator.CreateInterpreterFactory( new InterpreterFactoryCreationOptions() { Description = "Test Interpreter", InterpreterPath = "C:\\Does\\Not\\Exist\\Some\\Interpreter.exe" } ); var replEval = new PythonReplEvaluator(emptyFact, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions()); var replWindow = new MockReplWindow(replEval); replEval._Initialize(replWindow); var execute = replEval.ExecuteText("42"); var errorText = replWindow.Error; const string expected = "The interactive window could not be started because the associated Python environment could not be found.\r\n" + "If this version of Python has recently been uninstalled, you can close this window.\r\n" + "Current interactive window is disconnected."; if (!errorText.Contains(expected)) { Assert.Fail(string.Format( "Did not find:\n{0}\n\nin:\n{1}", expected, errorText )); } } } }
//------------------------------------------------------------------------------ // <copyright file="CategoryAttribute.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.ComponentModel { using System; using System.ComponentModel; using System.Diagnostics; using System.Security.Permissions; /// <devdoc> /// <para>Specifies the category in which the property or event will be displayed in a /// visual designer.</para> /// </devdoc> [AttributeUsage(AttributeTargets.All)] public class CategoryAttribute : Attribute { private static volatile CategoryAttribute appearance; private static volatile CategoryAttribute asynchronous; private static volatile CategoryAttribute behavior; private static volatile CategoryAttribute data; private static volatile CategoryAttribute design; private static volatile CategoryAttribute action; private static volatile CategoryAttribute format; private static volatile CategoryAttribute layout; private static volatile CategoryAttribute mouse; private static volatile CategoryAttribute key; private static volatile CategoryAttribute focus; private static volatile CategoryAttribute windowStyle; private static volatile CategoryAttribute dragDrop; private static volatile CategoryAttribute defAttr; private bool localized; /// <devdoc> /// <para> /// Provides the actual category name. /// </para> /// </devdoc> private string categoryValue; /// <devdoc> /// <para>Gets the action category attribute.</para> /// </devdoc> public static CategoryAttribute Action { get { if (action == null) { action = new CategoryAttribute("Action"); } return action; } } /// <devdoc> /// <para>Gets the appearance category attribute.</para> /// </devdoc> public static CategoryAttribute Appearance { get { if (appearance == null) { appearance = new CategoryAttribute("Appearance"); } return appearance; } } /// <devdoc> /// <para>Gets the asynchronous category attribute.</para> /// </devdoc> public static CategoryAttribute Asynchronous { get { if (asynchronous == null) { asynchronous = new CategoryAttribute("Asynchronous"); } return asynchronous; } } /// <devdoc> /// <para>Gets the behavior category attribute.</para> /// </devdoc> public static CategoryAttribute Behavior { get { if (behavior == null) { behavior = new CategoryAttribute("Behavior"); } return behavior; } } /// <devdoc> /// <para>Gets the data category attribute.</para> /// </devdoc> public static CategoryAttribute Data { get { if (data == null) { data = new CategoryAttribute("Data"); } return data; } } /// <devdoc> /// <para>Gets the default category attribute.</para> /// </devdoc> public static CategoryAttribute Default { get { if (defAttr == null) { defAttr = new CategoryAttribute(); } return defAttr; } } /// <devdoc> /// <para>Gets the design category attribute.</para> /// </devdoc> public static CategoryAttribute Design { get { if (design == null) { design = new CategoryAttribute("Design"); } return design; } } /// <devdoc> /// <para>Gets the drag and drop category attribute.</para> /// </devdoc> public static CategoryAttribute DragDrop { get { if (dragDrop == null) { dragDrop = new CategoryAttribute("DragDrop"); } return dragDrop; } } /// <devdoc> /// <para>Gets the focus category attribute.</para> /// </devdoc> public static CategoryAttribute Focus { get { if (focus == null) { focus = new CategoryAttribute("Focus"); } return focus; } } /// <devdoc> /// <para>Gets the format category attribute.</para> /// </devdoc> public static CategoryAttribute Format { get { if (format == null) { format = new CategoryAttribute("Format"); } return format; } } /// <devdoc> /// <para>Gets the keyboard category attribute.</para> /// </devdoc> public static CategoryAttribute Key { get { if (key == null) { key = new CategoryAttribute("Key"); } return key; } } /// <devdoc> /// <para>Gets the layout category attribute.</para> /// </devdoc> public static CategoryAttribute Layout { get { if (layout == null) { layout = new CategoryAttribute("Layout"); } return layout; } } /// <devdoc> /// <para>Gets the mouse category attribute.</para> /// </devdoc> public static CategoryAttribute Mouse { get { if (mouse == null) { mouse = new CategoryAttribute("Mouse"); } return mouse; } } /// <devdoc> /// <para> Gets the window style category /// attribute.</para> /// </devdoc> public static CategoryAttribute WindowStyle { get { if (windowStyle == null) { windowStyle = new CategoryAttribute("WindowStyle"); } return windowStyle; } } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/> /// class with the default category.</para> /// </devdoc> public CategoryAttribute() : this("Default") { } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/> class with /// the specified category name.</para> /// </devdoc> public CategoryAttribute(string category) { this.categoryValue = category; this.localized = false; } /// <devdoc> /// <para>Gets the name of the category for the property or event /// that this attribute is bound to.</para> /// </devdoc> public string Category { get { if (!localized) { localized = true; string localizedValue = GetLocalizedString(categoryValue); if (localizedValue != null) { categoryValue = localizedValue; } } return categoryValue; } } /// <devdoc> /// </devdoc> /// <devdoc> /// </devdoc> /// <internalonly/> /// <internalonly/> public override bool Equals(object obj){ if (obj == this) { return true; } if (obj is CategoryAttribute){ return Category.Equals(((CategoryAttribute)obj).Category); } return false; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { return Category.GetHashCode(); } /// <devdoc> /// <para>Looks up the localized name of a given category.</para> /// </devdoc> protected virtual string GetLocalizedString(string value) { #if !SILVERLIGHT #if MONO switch (value) { case "Action": return "PropertyCategoryAction"; case "Appearance": return "PropertyCategoryAppearance"; case "Behavior": return "PropertyCategoryBehavior"; case "Data": return "PropertyCategoryData"; case "DDE": return "PropertyCategoryDDE"; case "Design": return "PropertyCategoryDesign"; case "Focus": return "PropertyCategoryFocus"; case "Font": return "PropertyCategoryFont"; case "Key": return "PropertyCategoryKey"; case "List": return "PropertyCategoryList"; case "Layout": return "PropertyCategoryLayout"; case "Mouse": return "PropertyCategoryMouse"; case "Position": return "PropertyCategoryPosition"; case "Text": return "PropertyCategoryText"; case "Scale": return "PropertyCategoryScale"; case "Config": return "PropertyCategoryConfig"; #if !MOBILE case "Default": return "PropertyCategoryDefault"; case "DragDrop": return "PropertyCategoryDragDrop"; case "WindowStyle": return "PropertyCategoryWindowStyle"; #endif } return value; #else return (string)SR.GetObject("PropertyCategory" + value); #endif #else bool usedFallback; string localizedString = SR.GetString("PropertyCategory" + value, out usedFallback); if (usedFallback) { return null; } return localizedString; #endif } #if !SILVERLIGHT /// <devdoc> /// </devdoc> /// <devdoc> /// </devdoc> /// <internalonly/> /// <internalonly/> public override bool IsDefaultAttribute() { return Category.Equals(Default.Category); } #endif } }
using System; using System.Data; using System.Collections; using System.Collections.Generic; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.system; using gView.Framework.Network; namespace gView.Framework.FDB { public interface IDatabase : IErrorMessage ,IDisposable { bool Create(string name); bool Open(string name); string lastErrorMsg { get; } Exception lastException { get; } } public interface IDatabaseNames { string TableName(string tableName); string DbColName(string fieldName); } /// <summary> /// /// </summary> public interface IFeatureDatabase : IDatabase, IFeatureUpdater { //int OpenDataset(string name); //int OpenFeatureClass(int DatasetID,string name); int CreateDataset(string name, ISpatialReference sRef); int CreateFeatureClass( string dsname, string fcname, IGeometryDef geomDef, IFields Fields); IFeatureDataset this[string name] { get; } bool DeleteDataset(string dsName); bool DeleteFeatureClass(string fcName); bool RenameDataset(string name, string newName); bool RenameFeatureClass(string name, string newName); IFeatureCursor Query(IFeatureClass fc,IQueryFilter filter); string[] DatasetNames { get; } } public interface IFeatureDatabase2 : IFeatureDatabase { int CreateDataset(string name, ISpatialReference sRef, ISpatialIndexDef sIndexDef); } public interface IFeatureDatabase3 : IFeatureDatabase2 { int DatasetID(string dsname); int FeatureClassID(int datasetId, string fcname); int GetFeatureClassID(string fcname); } public interface IFileFeatureDatabase : IFeatureDatabase, IFeatureUpdater { bool Flush(IFeatureClass fc); string DatabaseName { get; } int MaxFieldNameLength { get; } } public interface IImageDB { int CreateImageDataset(string name, ISpatialReference sRef, ISpatialIndexDef sIndexDef, string imageSpace, IFields fields); bool IsImageDataset(string dsname, out string imageSpace); } public interface IReportProgress { void AddDelegate(object Delegate); } public interface IFeatureUpdater : IErrorMessage { bool Insert(IFeatureClass fClass,IFeature feature); bool Insert(IFeatureClass fClass, List<IFeature> features); bool Update(IFeatureClass fClass, IFeature feature); bool Update(IFeatureClass fClass, List<IFeature> features); bool Delete(IFeatureClass fClass, int oid); bool Delete(IFeatureClass fClass, string where); int SuggestedInsertFeatureCountPerTransaction { get; } } public interface IFeatureImportEvents { void BeforeInsertFeaturesEvent(IFeatureClass sourceFc, IFeatureClass destFc); void AfterInsertFeaturesEvent(IFeatureClass sourceFc, IFeatureClass destFc); } public interface IAltertable { bool AlterTable(string table, IField oldField, IField newField); } public interface IAlterDatabase { bool DropTable(string tabname); } public interface ISpatialIndexNode { int NID { get ; } int PID { get ; } short Page { get ; } IGeometry Rectangle { get; } List<int> IDs { get; } } public interface ISpatialIndexNode2 { int NID { get ; } int PID { get ; } short Page { get ; } } public interface ISpatialTreeInfo { string type { get; } IEnvelope Bounds { get; } double SpatialRatio { get; } int MaxFeaturesPerNode { get; } List<SpatialIndexNode> SpatialIndexNodes { get ; } } public class SpatialIndexNode : ISpatialIndexNode,IComparable { private int _NID=0,_PID=0; private short _page; private IGeometry _geom; private List<int> _IDs; #region ISpatialIndexNode Member public int NID { get { return _NID; } set { _NID=value; } } public int PID { get { return _PID; } set { _PID=value; } } public IGeometry Rectangle { get { return _geom; } set { _geom=value; } } public List<int> IDs { get { return _IDs; } set { _IDs=value; } } public short Page { get { return _page; } set { _page=value; } } #endregion #region IComparable Member public int CompareTo(object obj) { return (this.NID < (((ISpatialIndexNode)obj).NID)) ? -1 : 1; //return 0; } #endregion } public class SpatialIndexNode2 : ISpatialIndexNode2 { private int _NID=0,_PID=0; private short _page; #region ISpatialIndexNode Member public int NID { get { return _NID; } set { _NID=value; } } public int PID { get { return _PID; } set { _PID=value; } } public short Page { get { return _page; } set { _page=value; } } #endregion } public interface ISpatialIndexDef { GeometryFieldType GeometryType { get; } IEnvelope SpatialIndexBounds { get; } double SplitRatio { get; } int MaxPerNode { get; } int Levels { get; } ISpatialReference SpatialReference { get; } bool ProjectTo(ISpatialReference sRef); } public interface IFDBDataset { ISpatialIndexDef SpatialIndexDef { get; } } public interface ISpatialIndex { bool InitIndex(string FCName); bool InsertNodes(string FCName,List<SpatialIndexNode> nodes); DataTable QueryIDs(IEnvelope env); } public interface IIndexTree { List<int> FindShapeIds( IEnvelope Bounds ); } public interface IAutoField : IField { string AutoFieldName { get; } string AutoFieldDescription { get; } string AutoFieldPrimayName { get; } FieldType AutoFieldType { get; } bool OnInsert(IFeatureClass fc, IFeature feature); bool OnUpdate(IFeatureClass fc, IFeature feature); } public interface IFDBDatabase : IFeatureDatabase3 { bool SetSpatialIndexBounds(string FCName, string TreeType, IEnvelope Bounds, double SpatialRatio, int maxPerNode, int maxLevels); ISpatialIndexDef SpatialIndexDef(string dsName); bool ShrinkSpatialIndex(string fcName, List<long> NIDs); bool SetFeatureclassExtent(string fcName, IEnvelope envelope); bool CalculateExtent(string fcName); } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements. /// </summary> public abstract class AbstractCodeElement : AbstractCodeModelObject, ICodeElementContainer<AbstractCodeElement>, EnvDTE.CodeElement, EnvDTE80.CodeElement2 { private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly int? _nodeKind; internal AbstractCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int? nodeKind = null) : base(state) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKind = nodeKind; } internal FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } protected SyntaxTree GetSyntaxTree() { return FileCodeModel.GetSyntaxTree(); } protected Document GetDocument() { return FileCodeModel.GetDocument(); } protected SemanticModel GetSemanticModel() { return FileCodeModel.GetSemanticModel(); } protected ProjectId GetProjectId() { return FileCodeModel.GetProjectId(); } internal bool IsValidNode() { SyntaxNode node; if (!TryLookupNode(out node)) { return false; } if (_nodeKind != null && _nodeKind.Value != node.RawKind) { return false; } return true; } internal virtual SyntaxNode LookupNode() { SyntaxNode node; if (!TryLookupNode(out node)) { throw Exceptions.ThrowEFail(); } return node; } internal abstract bool TryLookupNode(out SyntaxNode node); internal virtual ISymbol LookupSymbol() { var semanticModel = GetSemanticModel(); var node = LookupNode(); return semanticModel.GetDeclaredSymbol(node); } protected void UpdateNode<T>(Action<SyntaxNode, T> updater, T value) { FileCodeModel.EnsureEditor(() => { var node = LookupNode(); updater(node, value); }); } public abstract EnvDTE.vsCMElement Kind { get; } protected virtual string GetName() { var node = LookupNode(); return CodeModelService.GetName(node); } protected virtual void SetName(string value) { UpdateNode(FileCodeModel.UpdateName, value); } public string Name { get { return GetName(); } set { SetName(value); } } protected virtual string GetFullName() { var node = LookupNode(); var semanticModel = GetSemanticModel(); return CodeModelService.GetFullName(node, semanticModel); } public string FullName { get { return GetFullName(); } } public abstract object Parent { get; } public abstract EnvDTE.CodeElements Children { get; } EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() { return Children; } protected virtual EnvDTE.CodeElements GetCollection() { return GetCollection<AbstractCodeElement>(Parent); } public virtual EnvDTE.CodeElements Collection { get { return GetCollection(); } } public EnvDTE.TextPoint StartPoint { get { var point = FileCodeModel.EnsureEditor(() => CodeModelService.GetStartPoint(LookupNode())); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } } public EnvDTE.TextPoint EndPoint { get { var point = CodeModelService.GetEndPoint(LookupNode()); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } } public virtual EnvDTE.TextPoint GetStartPoint(EnvDTE.vsCMPart part) { var point = FileCodeModel.EnsureEditor(() => CodeModelService.GetStartPoint(LookupNode(), part)); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } public virtual EnvDTE.TextPoint GetEndPoint(EnvDTE.vsCMPart part) { var point = CodeModelService.GetEndPoint(LookupNode(), part); if (point == null) { return null; } return FileCodeModel.TextManagerAdapter.CreateTextPoint(FileCodeModel, point.Value); } public virtual EnvDTE.vsCMInfoLocation InfoLocation { get { // The default implementation assumes project-located elements... return EnvDTE.vsCMInfoLocation.vsCMInfoLocationProject; } } public virtual bool IsCodeType { get { return false; } } public EnvDTE.ProjectItem ProjectItem { get { return FileCodeModel.Parent; } } public string ExtenderCATID { get { throw new NotImplementedException(); } } protected virtual object GetExtenderNames() { throw Exceptions.ThrowENotImpl(); } public object ExtenderNames { get { return GetExtenderNames(); } } protected virtual object GetExtender(string name) { throw Exceptions.ThrowENotImpl(); } public object get_Extender(string extenderName) { return GetExtender(extenderName); } public string ElementID { get { throw new NotImplementedException(); } } public virtual void RenameSymbol(string newName) { if (string.IsNullOrEmpty(newName)) { throw new ArgumentException(); } CodeModelService.Rename(LookupSymbol(), newName, this.Workspace.CurrentSolution); } protected virtual Document DeleteCore(Document document) { var node = LookupNode(); return CodeModelService.Delete(document, node); } /// <summary> /// Delete the element from the source file. /// </summary> internal void Delete() { FileCodeModel.PerformEdit(document => { return DeleteCore(document); }); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Required by interface")] public string get_Prototype(int flags) { return CodeModelService.GetPrototype(LookupNode(), LookupSymbol(), (PrototypeFlags)flags); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ctor_str_int_parity_int_stopbits : PortsTest { private enum ThrowAt { Set, Open }; [Fact] public void COM1_9600_Odd_5_1() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.Odd; int dataBits = 5; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM2_14400_None_5_1() { string portName = "COM2"; int baudRate = 14400; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM3_28800_None_5_15() { string portName = "COM3"; int baudRate = 28800; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM4_57600_Even_5_15() { string portName = "COM2"; int baudRate = 57600; int parity = (int)Parity.Even; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM256_115200_Mark_5_2() { string portName = "COM256"; int baudRate = 115200; int parity = (int)Parity.Mark; int dataBits = 5; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM1_9600_None_5_2() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM2_14400_Even_6_1() { string portName = "COM2"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 6; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM3_28800_Odd_7_2() { string portName = "COM3"; int baudRate = 28800; int parity = (int)Parity.Odd; int dataBits = 7; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM1_9600_Odd_8_1() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.Odd; int dataBits = 8; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM2_14400_None_8_1() { string portName = "COM2"; int baudRate = 14400; int parity = (int)Parity.None; int dataBits = 8; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM256_115200_Mark_8_2() { string portName = "COM256"; int baudRate = 115200; int parity = (int)Parity.Mark; int dataBits = 8; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void COM1_9600_None_8_2() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 8; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } //[] Error checking for PortName [Fact] public void Empty_9600_None_5_15() { string portName = string.Empty; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Set); } [Fact] public void Null_14400_Even_6_1() { string portName = null; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 6; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentNullException), ThrowAt.Set); } [Fact] public void COM257_57600_Mark_8_2() { string portName = "COM257"; int baudRate = 57600; int parity = (int)Parity.Mark; int dataBits = 8; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } [Fact] public void Filename_9600_Space_8_1() { string portName; int baudRate = 9600; int parity = (int)Parity.Space; int dataBits = 8; int stopBits = (int)StopBits.One; string fileName = portName = GetTestFilePath(); FileStream testFile = File.Open(fileName, FileMode.Create); ASCIIEncoding asciiEncd = new ASCIIEncoding(); string testStr = "Hello World"; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { throw; } finally { File.Delete(fileName); } } [Fact] public void PHYSICALDRIVE0_14400_Even_5_15() { string portName = "PHYSICALDRIVE0"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); } //[] Error checking for BaudRate [Fact] public void COM1_Int32MinValue_None_5_15() { string portName = "Com1"; int baudRate = int.MinValue; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM2_Neg1_Even_6_1() { string portName = "Com2"; int baudRate = -1; int parity = (int)Parity.Even; int dataBits = 6; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM3_0_Odd_7_2() { string portName = "Com3"; int baudRate = 0; int parity = (int)Parity.Odd; int dataBits = 7; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM4_Int32MaxValue_Mark_8_2() { string portName = "Com4"; int baudRate = int.MaxValue; int parity = (int)Parity.Mark; int dataBits = 8; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open); } //[] Error checking for Parity [Fact] public void COM1_9600_Int32MinValue_5_15() { string portName = "Com1"; int baudRate = 9600; int parity = int.MinValue; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM2_14400_Neg1_6_1() { string portName = "Com2"; int baudRate = 14400; int parity = -1; int dataBits = 6; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM3_28800_5_7_2() { string portName = "Com3"; int baudRate = 28800; int parity = 5; int dataBits = 7; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM4_57600_Int32MaxValue_8_2() { string portName = "Com4"; int baudRate = 57600; int parity = int.MaxValue; int dataBits = 8; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } //[] Error checking for DataBits [Fact] public void COM1_9600_None_Int32MinValue_1() { string portName = "Com1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = int.MinValue; int stopBits = (int)StopBits.OnePointFive; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM2_14400_Even_Neg1_15() { string portName = "Com2"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = -1; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM3_28800_Odd_4_2() { string portName = "Com3"; int baudRate = 28800; int parity = (int)Parity.Odd; int dataBits = 4; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM4_57600_Mark_9_1() { string portName = "Com4"; int baudRate = 57600; int parity = (int)Parity.Mark; int dataBits = 9; int stopBits = (int)StopBits.Two; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM255_115200_Space_Int32MaxValue_15() { string portName = "Com255"; int baudRate = 115200; int parity = (int)Parity.Space; int dataBits = int.MaxValue; int stopBits = (int)StopBits.One; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } //[] Error checking for StopBits [Fact] public void COM1_9600_None_5_Int32MinValue() { string portName = "Com1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; int stopBits = int.MinValue; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM2_14400_Even_6_Neg1() { string portName = "Com2"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 6; int stopBits = -1; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM3_28800_Odd_7_0() { string portName = "Com3"; int baudRate = 28800; int parity = (int)Parity.Odd; int dataBits = 7; int stopBits = 0; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM4_57600_Mark_8_4() { string portName = "Com4"; int baudRate = 57600; int parity = (int)Parity.Mark; int dataBits = 8; int stopBits = 4; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } [Fact] public void COM255_115200_Space_8_Int32MaxValue() { string portName = "Com255"; int baudRate = 115200; int parity = (int)Parity.Space; int dataBits = 8; int stopBits = int.MaxValue; VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits) { VerifyCtor(portName, baudRate, parity, dataBits, stopBits, null, ThrowAt.Set); } private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits, Type expectedException, ThrowAt throwAt) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3},StopBits={4}", portName, baudRate, parity, dataBits, stopBits); try { using (SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits, (StopBits)stopBits)) { if (null != expectedException && throwAt == ThrowAt.Set) { Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); } serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", portName); serPortProp.SetProperty("BaudRate", baudRate); serPortProp.SetProperty("Parity", (Parity)parity); serPortProp.SetProperty("DataBits", dataBits); serPortProp.SetProperty("StopBits", (StopBits)stopBits); serPortProp.VerifyPropertiesAndPrint(com); } } catch (Exception e) { if (null == expectedException) { Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); } else if (throwAt == ThrowAt.Open) { Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); } else if (e.GetType() != expectedException) { Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // ---------------------------------------------------------------------------- // // AggregateType // // Represents a genericructed (or instantiated) type. Parent is the AggregateSymbol. // ---------------------------------------------------------------------------- internal partial class AggregateType : CType { private TypeArray _pTypeArgsThis; private TypeArray _pTypeArgsAll; // includes args from outer types private AggregateSymbol _pOwningAggregate; #if ! CSEE // The EE can't cache these since the AGGSYMs may change as things are imported. private AggregateType _baseType; // This is the result of calling SubstTypeArray on the aggregate's baseClass. private TypeArray _ifacesAll; // This is the result of calling SubstTypeArray on the aggregate's ifacesAll. private TypeArray _winrtifacesAll; //This is the list of collection interfaces implemented by a WinRT object. #else // !CSEE public short proxyOID; // oid for the managed proxy in the host running inside the debugee public short typeConverterID; #endif // !CSEE public bool fConstraintsChecked; // Have theraints been checked yet? public bool fConstraintError; // Did theraints check produce an error? // These two flags are used to track hiding within interfaces. // Their use and validity is always localized. See e.g. MemberLookup::LookupInInterfaces. public bool fAllHidden; // All members are hidden by a derived interface member. public bool fDiffHidden; // Members other than a specific kind are hidden by a derived interface member or class member. public AggregateType outerType; // the outer type if this is a nested type public void SetOwningAggregate(AggregateSymbol agg) { _pOwningAggregate = agg; } public AggregateSymbol GetOwningAggregate() { return _pOwningAggregate; } public AggregateType GetBaseClass() { #if CSEE AggregateType atsBase = getAggregate().GetBaseClass(); if (!atsBase || GetTypeArgsAll().size == 0 || atsBase.GetTypeArgsAll().size == 0) return atsBase; return getAggregate().GetTypeManager().SubstType(atsBase, GetTypeArgsAll()).AsAggregateType(); #else // !CSEE if (_baseType == null) { _baseType = getAggregate().GetTypeManager().SubstType(getAggregate().GetBaseClass(), GetTypeArgsAll()) as AggregateType; } return _baseType; #endif // !CSEE } public void SetTypeArgsThis(TypeArray pTypeArgsThis) { TypeArray pOuterTypeArgs; if (outerType != null) { Debug.Assert(outerType.GetTypeArgsThis() != null); Debug.Assert(outerType.GetTypeArgsAll() != null); pOuterTypeArgs = outerType.GetTypeArgsAll(); } else { pOuterTypeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(pTypeArgsThis != null); _pTypeArgsThis = pTypeArgsThis; SetTypeArgsAll(pOuterTypeArgs); } public void SetTypeArgsAll(TypeArray outerTypeArgs) { Debug.Assert(_pTypeArgsThis != null); // Here we need to check our current type args. If we have an open placeholder, // then we need to have all open placeholders, and we want to flush // our outer type args so that they're open placeholders. // // This is because of the following scenario: // // class B<T> // { // class C<U> // { // } // class D // { // void Foo() // { // Type T = typeof(C<>); // } // } // } // // The outer type will be B<T>, but the inner type will be C<>. However, // this will eventually be represented in IL as B<>.C<>. As such, we should // keep our data structures clear - if we have one open type argument, then // all of them must be open type arguments. // // Ensure that invariant here. TypeArray pCheckedOuterTypeArgs = outerTypeArgs; TypeManager pTypeManager = getAggregate().GetTypeManager(); if (_pTypeArgsThis.Size > 0 && AreAllTypeArgumentsUnitTypes(_pTypeArgsThis)) { if (outerTypeArgs.Size > 0 && !AreAllTypeArgumentsUnitTypes(outerTypeArgs)) { // We have open placeholder types in our type, but not the parent. pCheckedOuterTypeArgs = pTypeManager.CreateArrayOfUnitTypes(outerTypeArgs.Size); } } _pTypeArgsAll = pTypeManager.ConcatenateTypeArrays(pCheckedOuterTypeArgs, _pTypeArgsThis); } public bool AreAllTypeArgumentsUnitTypes(TypeArray typeArray) { if (typeArray.Size == 0) { return true; } for (int i = 0; i < typeArray.size; i++) { Debug.Assert(typeArray.Item(i) != null); if (!typeArray.Item(i).IsOpenTypePlaceholderType()) { return false; } } return true; } public TypeArray GetTypeArgsThis() { return _pTypeArgsThis; } public TypeArray GetTypeArgsAll() { return _pTypeArgsAll; } public TypeArray GetIfacesAll() { if (_ifacesAll == null) { _ifacesAll = getAggregate().GetTypeManager().SubstTypeArray(getAggregate().GetIfacesAll(), GetTypeArgsAll()); } return _ifacesAll; } public TypeArray GetWinRTCollectionIfacesAll(SymbolLoader pSymbolLoader) { if (_winrtifacesAll == null) { TypeArray ifaces = GetIfacesAll(); System.Collections.Generic.List<CType> typeList = new System.Collections.Generic.List<CType>(); for (int i = 0; i < ifaces.size; i++) { AggregateType type = ifaces.Item(i).AsAggregateType(); Debug.Assert(type.isInterfaceType()); if (type.IsCollectionType()) { typeList.Add(type); } } _winrtifacesAll = pSymbolLoader.getBSymmgr().AllocParams(typeList.Count, typeList.ToArray()); } return _winrtifacesAll; } public TypeArray GetDelegateParameters(SymbolLoader pSymbolLoader) { Debug.Assert(isDelegateType()); MethodSymbol invoke = pSymbolLoader.LookupInvokeMeth(this.getAggregate()); if (invoke == null || !invoke.isInvoke()) { // This can happen if the delegate is internal to another assembly. return null; } return this.getAggregate().GetTypeManager().SubstTypeArray(invoke.Params, this); } public CType GetDelegateReturnType(SymbolLoader pSymbolLoader) { Debug.Assert(isDelegateType()); MethodSymbol invoke = pSymbolLoader.LookupInvokeMeth(this.getAggregate()); if (invoke == null || !invoke.isInvoke()) { // This can happen if the delegate is internal to another assembly. return null; } return this.getAggregate().GetTypeManager().SubstType(invoke.RetType, 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; using System.Text.RegularExpressions; using Xunit; public class GroupNamesAndNumber { /* Tested Methods: public string[] GetGroupNames(); public int[] GetGroupNumbers(); public string GroupNameFromNumber(int i); public int GroupNumberFromName(string name); */ [Fact] public static void GroupNamesAndNumberTestCase() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Regex r; String s; String[] expectedNames; String[] expectedGroups; int[] expectedNumbers; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// //[]Vanilla s = "Ryan Byington"; r = new Regex("(?<first_name>\\S+)\\s(?<last_name>\\S+)"); strLoc = "Loc_498yg"; iCountTestcases++; expectedNames = new String[] { "0", "first_name", "last_name" } ; expectedNumbers = new int[] { 0, 1, 2 } ; expectedGroups = new String[] { "Ryan Byington", "Ryan", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_79793asdwk! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_08712saopz! Unexpected Groups"); } //[]RegEx from SDK s = "abc208923xyzanqnakl"; r = new Regex(@"((?<One>abc)\d+)?(?<Two>xyz)(.*)"); strLoc = "Loc_0822aws"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "One", "Two" } ; expectedNumbers = new int[] { 0, 1, 2, 3, 4 } ; expectedGroups = new String[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_79793asdwk! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_0822klas! Unexpected Groups"); } //[]RegEx with numeric names s = "0272saasdabc8978xyz][]12_+-"; r = new Regex(@"((?<256>abc)\d+)?(?<16>xyz)(.*)"); strLoc = "Loc_0982asd"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "16", "256" } ; expectedNumbers = new int[] { 0, 1, 2, 16, 256 } ; expectedGroups = new String[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_79793asdwk! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_7072ankla! Unexpected Groups"); } //[]RegEx with numeric names and string names s = "0272saasdabc8978xyz][]12_+-"; r = new Regex(@"((?<4>abc)(?<digits>\d+))?(?<2>xyz)(?<everything_else>.*)"); strLoc = "Loc_98968asdf"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "digits", "4", "everything_else" } ; expectedNumbers = new int[] { 0, 1, 2, 3, 4, 5 } ; expectedGroups = new String[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_9496sad! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_6984awsd! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_7072ankla! Unexpected Groups"); } //[]RegEx with 0 numeric names try { r = new Regex(@"foo(?<0>bar)"); iCountErrors++; Console.WriteLine("Err_16891 Expected Regex to throw ArgumentException and nothing was thrown"); } catch (ArgumentException) { } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_9877sawa Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e); } //[]RegEx without closing > try { r = new Regex(@"foo(?<1bar)"); iCountErrors++; Console.WriteLine("Err_2389uop Expected Regex to throw ArgumentException and nothing was thrown"); } catch (ArgumentException) { } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_3298asoia Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e); } //[] Duplicate string names s = "Ryan Byington"; r = new Regex("(?<first_name>\\S+)\\s(?<first_name>\\S+)"); strLoc = "Loc_sdfa9849"; iCountTestcases++; expectedNames = new String[] { "0", "first_name" } ; expectedNumbers = new int[] { 0, 1 } ; expectedGroups = new String[] { "Ryan Byington", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_32189asdd! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_7978assd! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_98732soiya! Unexpected Groups"); } //[] Duplicate numeric names s = "Ryan Byington"; r = new Regex("(?<15>\\S+)\\s(?<15>\\S+)"); strLoc = "Loc_89198asda"; iCountTestcases++; expectedNames = new String[] { "0", "15" } ; expectedNumbers = new int[] { 0, 15 } ; expectedGroups = new String[] { "Ryan Byington", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_97654awwa! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_6498asde! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_316jkkl! Unexpected Groups"); } /****************************************************************** Repeat the same steps from above but using (?'foo') instead ******************************************************************/ //[]Vanilla s = "Ryan Byington"; r = new Regex("(?'first_name'\\S+)\\s(?'last_name'\\S+)"); strLoc = "Loc_0982aklpas"; iCountTestcases++; expectedNames = new String[] { "0", "first_name", "last_name" } ; expectedNumbers = new int[] { 0, 1, 2 } ; expectedGroups = new String[] { "Ryan Byington", "Ryan", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_464658safsd! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_15689asda! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_31568kjkj! Unexpected Groups"); } //[]RegEx from SDK s = "abc208923xyzanqnakl"; r = new Regex(@"((?'One'abc)\d+)?(?'Two'xyz)(.*)"); strLoc = "Loc_98977uouy"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "One", "Two" } ; expectedNumbers = new int[] { 0, 1, 2, 3, 4 } ; expectedGroups = new String[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_65498yuiy! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_5698yuiyh! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_2168hkjh! Unexpected Groups"); } //[]RegEx with numeric names s = "0272saasdabc8978xyz][]12_+-"; r = new Regex(@"((?'256'abc)\d+)?(?'16'xyz)(.*)"); strLoc = "Loc_9879hjly"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "16", "256" } ; expectedNumbers = new int[] { 0, 1, 2, 16, 256 } ; expectedGroups = new String[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_21689hjkh! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_2689juj! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_2358adea! Unexpected Groups"); } //[]RegEx with numeric names and string names s = "0272saasdabc8978xyz][]12_+-"; r = new Regex(@"((?'4'abc)(?'digits'\d+))?(?'2'xyz)(?'everything_else'.*)"); strLoc = "Loc_23189uioyp"; iCountTestcases++; expectedNames = new String[] { "0", "1", "2", "digits", "4", "everything_else" } ; expectedNumbers = new int[] { 0, 1, 2, 3, 4, 5 } ; expectedGroups = new String[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_3219hjkj! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_23189aseq! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_2318adew! Unexpected Groups"); } //[]RegEx with 0 numeric names try { r = new Regex(@"foo(?'0'bar)"); iCountErrors++; Console.WriteLine("Err_16891 Expected Regex to throw ArgumentException and nothing was thrown"); } catch (ArgumentException) { } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_9877sawa Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e); } //[]RegEx without closing > try { r = new Regex(@"foo(?'1bar)"); iCountErrors++; Console.WriteLine("Err_979asja Expected Regex to throw ArgumentException and nothing was thrown"); } catch (ArgumentException) { } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_16889asdfw Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e); } //[] Duplicate string names s = "Ryan Byington"; r = new Regex("(?'first_name'\\S+)\\s(?'first_name'\\S+)"); strLoc = "Loc_2318opa"; iCountTestcases++; expectedNames = new String[] { "0", "first_name" } ; expectedNumbers = new int[] { 0, 1 } ; expectedGroups = new String[] { "Ryan Byington", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_28978adfe! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_3258adsw! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_2198asd! Unexpected Groups"); } //[] Duplicate numeric names s = "Ryan Byington"; r = new Regex("(?'15'\\S+)\\s(?'15'\\S+)"); strLoc = "Loc_3289hjaa"; iCountTestcases++; expectedNames = new String[] { "0", "15" } ; expectedNumbers = new int[] { 0, 15 } ; expectedGroups = new String[] { "Ryan Byington", "Byington" } ; if (!VerifyGroupNames(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_13289asd! Unexpected GroupNames"); } if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_23198asdf! Unexpected GroupNumbers"); } if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers)) { iCountErrors++; Console.WriteLine("Err_15689teraku! Unexpected Groups"); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } public static bool VerifyGroupNames(Regex r, String[] expectedNames, int[] expectedNumbers) { string[] names = r.GetGroupNames(); if (names.Length != expectedNames.Length) { Console.WriteLine("Err_08722aswa! Expect {0} names actual={1}", expectedNames.Length, names.Length); return false; } for (int i = 0; i < expectedNames.Length; i++) { if (!names[i].Equals(expectedNames[i])) { Console.WriteLine("Err_09878asfas! Expected GroupNames[{0}]={1} actual={2}", i, expectedNames[i], names[i]); return false; } if (expectedNames[i] != r.GroupNameFromNumber(expectedNumbers[i])) { Console.WriteLine("Err_6589sdafn!GroupNameFromNumber({0})={1} actual={2}", expectedNumbers[i], expectedNames[i], r.GroupNameFromNumber(expectedNumbers[i])); return false; } } return true; } public static bool VerifyGroupNumbers(Regex r, String[] expectedNames, int[] expectedNumbers) { int[] numbers = r.GetGroupNumbers(); if (numbers.Length != expectedNumbers.Length) { Console.WriteLine("Err_7978awoyp! Expect {0} numbers actual={1}", expectedNumbers.Length, numbers.Length); return false; } for (int i = 0; i < expectedNumbers.Length; i++) { if (numbers[i] != expectedNumbers[i]) { Console.WriteLine("Err_4342asnmc! Expected GroupNumbers[{0}]={1} actual={2}", i, expectedNumbers[i], numbers[i]); return false; } if (expectedNumbers[i] != r.GroupNumberFromName(expectedNames[i])) { Console.WriteLine("Err_98795ajkas!GroupNumberFromName({0})={1} actual={2}", expectedNames[i], expectedNumbers[i], r.GroupNumberFromName(expectedNames[i])); return false; } } return true; } public static bool VerifyGroups(Regex r, String s, String[] expectedGroups, String[] expectedNames, int[] expectedNumbers) { Match m = r.Match(s); Group g; if (!m.Success) { Console.WriteLine("Err_08220kha Match not a success"); return false; } if (m.Groups.Count != expectedGroups.Length) { Console.WriteLine("Err_9722asqa! Expect {0} groups actual={1}", expectedGroups.Length, m.Groups.Count); return false; } for (int i = 0; i < expectedNumbers.Length; i++) { if (null == (g = m.Groups[expectedNames[i]]) || expectedGroups[i] != g.Value) { Console.WriteLine("Err_3327nkoo! Expected Groups[{0}]={1} actual={2}", expectedNames[i], expectedGroups[i], g == null ? "<null>" : g.Value); return false; } if (null == (g = m.Groups[expectedNumbers[i]]) || expectedGroups[i] != g.Value) { Console.WriteLine("Err_9465sdjh! Expected Groups[{0}]={1} actual={2}", expectedNumbers[i], expectedGroups[i], g == null ? "<null>" : g.Value); return false; } } return true; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary>The class that contains the unit tests of the ThreadLocal.</summary> public static class ThreadLocalTests { /// <summary>Tests for the Ctor.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest1_Ctor() { ThreadLocal<object> testObject; testObject = new ThreadLocal<object>(); testObject = new ThreadLocal<object>(true); testObject = new ThreadLocal<object>(() => new object()); testObject = new ThreadLocal<object>(() => new object(), true); } [Fact] public static void RunThreadLocalTest1_Ctor_Negative() { try { new ThreadLocal<object>(null); } catch (ArgumentNullException) { // No other exception should be thrown. // With a previous issue, if the constructor threw an exception, the finalizer would throw an exception as well. } } /// <summary>Tests for the ToString.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest2_ToString() { ThreadLocal<object> tlocal = new ThreadLocal<object>(() => (object)1); if (tlocal.ToString() != 1.ToString()) { Assert.True(false, string.Format("RunThreadLocalTest2_ToString: > test failed - Unexpected return value from ToString(); Actual={0}, Expected={1}.", tlocal.ToString(), 1.ToString())); } } /// <summary>Tests for the Initialized property.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest3_IsValueCreated() { ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test"); if (tlocal.IsValueCreated) { Assert.True(false, "RunThreadLocalTest3_IsValueCreated: > test failed - expected ThreadLocal to be uninitialized."); } string temp = tlocal.Value; if (!tlocal.IsValueCreated) { Assert.True(false, "RunThreadLocalTest3_IsValueCreated: > test failed - expected ThreadLocal to be initialized."); } } [Fact] public static void RunThreadLocalTest4_Value() { ThreadLocal<string> tlocal = null; // different threads call Value int numOfThreads = 10; Task[] threads = new Task[numOfThreads]; object alock = new object(); List<string> seenValuesFromAllThreads = new List<string>(); int counter = 0; tlocal = new ThreadLocal<string>(() => (++counter).ToString()); //CancellationToken ct = new CancellationToken(); for (int i = 0; i < threads.Length; ++i) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. threads[i] = new Task(() => { string value = tlocal.Value; Debug.WriteLine("Val: " + value); seenValuesFromAllThreads.Add(value); }, TaskCreationOptions.LongRunning); threads[i].Start(TaskScheduler.Default); threads[i].Wait(); } bool successful = true; string values = ""; for (int i = 1; i <= threads.Length; ++i) { string seenValue = seenValuesFromAllThreads[i - 1]; values += seenValue + ","; if (seenValue != i.ToString()) { successful = false; } } if (!successful) { Debug.WriteLine("RunThreadLocalTest4_Value: > test failed - ThreadLocal test failed. Seen values are: " + values.Substring(0, values.Length - 1)); Assert.True(false, string.Format("RunThreadLocalTest4_Value: > test failed - ThreadLocal test failed. Seen values are: " + values.Substring(0, values.Length - 1))); } } [Fact] public static void RunThreadLocalTest4_Value_NegativeCases() { ThreadLocal<string> tlocal = null; try { int x = 0; tlocal = new ThreadLocal<string>(delegate { if (x++ < 5) return tlocal.Value; else return "Test"; }); string str = tlocal.Value; Assert.True(false, string.Format("RunThreadLocalTest4_Value: > test failed - expected exception InvalidOperationException")); } catch (InvalidOperationException) { } } [Fact] public static void RunThreadLocalTest5_Dispose() { // test recycling the combination index; ThreadLocal<string> tl = new ThreadLocal<string>(() => null); if (tl.IsValueCreated) { Assert.True(false, string.Format("RunThreadLocalTest5_Dispose: Failed: IsValueCreated expected to return false.")); } if (tl.Value != null) { Assert.True(false, string.Format("RunThreadLocalTest5_Dispose: Failed: reusing the same index kept the old value and didn't use the new value.")); } // Test that a value is not kept alive by a departed thread var threadLocal = new ThreadLocal<SetMreOnFinalize>(); var mres = new ManualResetEventSlim(false); // (Careful when editing this test: saving the created thread into a local variable would likely break the // test in Debug build.) // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. new Task(() => { threadLocal.Value = new SetMreOnFinalize(mres); }, TaskCreationOptions.LongRunning).Start(TaskScheduler.Default); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 500); if (!mres.IsSet) { Assert.True(false, string.Format("RunThreadLocalTest5_Dispose: Failed: Expected ThreadLocal to release the object and for it to be finalized")); } } [Fact] public static void RunThreadLocalTest5_Dispose_Negative() { ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test"); string value = tl.Value; tl.Dispose(); Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.Value; }); // Failure Case: The Value property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { bool tmp = tl.IsValueCreated; }); // Failure Case: The IsValueCreated property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.ToString(); }); // Failure Case: The ToString method of the disposed ThreadLocal object should throw ODE } [Fact] public static void RunThreadLocalTest6_SlowPath() { // the maximum fast path instances for each type is 16 ^ 3 = 4096, when this number changes in the product code, it should be changed here as well int MaximumFastPathPerInstance = 4096; ThreadLocal<int>[] locals_int = new ThreadLocal<int>[MaximumFastPathPerInstance + 10]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); var val = locals_int[i].Value; } for (int i = 0; i < locals_int.Length; i++) { if (locals_int[i].Value != i) { Assert.True(false, string.Format("RunThreadLocalTest6_SlowPath: Failed, Slowpath value failed, expected {0}, actual {1}.", i, locals_int[i].Value)); } } // The maximum slowpath for all Ts is MaximumFastPathPerInstance * 4; locals_int = new ThreadLocal<int>[4096]; ThreadLocal<long>[] locals_long = new ThreadLocal<long>[4096]; ThreadLocal<float>[] locals_float = new ThreadLocal<float>[4096]; ThreadLocal<double>[] locals_double = new ThreadLocal<double>[4096]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); locals_long[i] = new ThreadLocal<long>(() => i); locals_float[i] = new ThreadLocal<float>(() => i); locals_double[i] = new ThreadLocal<double>(() => i); } ThreadLocal<string> local = new ThreadLocal<string>(() => "slow path"); if (local.Value != "slow path") { Assert.True(false, string.Format("RunThreadLocalTest6_SlowPath: Failed, Slowpath value failed, expected slow path, actual {0}.", local.Value)); } } private class ThreadLocalWeakReferenceTest { private object _foo; private WeakReference _wFoo; [MethodImplAttribute(MethodImplOptions.NoInlining)] private void Method() { _foo = new Object(); _wFoo = new WeakReference(_foo); new ThreadLocal<object>() { Value = _foo }.Dispose(); } public void Run() { Method(); _foo = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // s_foo should have been garbage collected if (_wFoo.IsAlive) Assert.True(false, string.Format("RunThreadLocalTest7_Bug919869: Failed, The ThreadLocal value is still alive after disposing the ThreadLocal instance")); } } [Fact] public static void RunThreadLocalTest7_WeakReference() { var threadLocalWeakReferenceTest = new ThreadLocalWeakReferenceTest(); threadLocalWeakReferenceTest.Run(); } [Fact] public static void RunThreadLocalTest8_Values() { // Test adding values and updating values { var threadLocal = new ThreadLocal<int>(true); Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values"); Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0"); Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value"); Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value"); threadLocal.Value = 42; Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value"); Assert.True(threadLocal.Values[0] == 42, "RunThreadLocalTest8_Values: Expected values to contain updated value"); ((IAsyncResult)Task.Run(() => threadLocal.Value = 43)).AsyncWaitHandle.WaitOne(); Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value"); Assert.True(threadLocal.Values.Contains(42) && threadLocal.Values.Contains(43), "RunThreadLocalTest8_Values: Expected values to contain both thread's values"); int numTasks = 1000; Task[] allTasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(); } var values = threadLocal.Values; Assert.True(values.Count == 1002, "RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values"); for (int i = 0; i < 1000; i++) { Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i); } threadLocal.Dispose(); } // Test that thread values remain after threads depart { var tl = new ThreadLocal<string>(true); var t = Task.Run(() => tl.Value = "Parallel"); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization"); Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'"); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres) { var tl = new ThreadLocal<object>(true); var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres)); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value"); Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type"); tl.Dispose(); object values; Assert.Throws<ObjectDisposedException>(() => values = tl.Values); } [Fact] public static void RunThreadLocalTest8_Values_NegativeCases() { // Test that Dispose works and that objects are released on dispose { var mres = new ManualResetEventSlim(); RunThreadLocalTest8Helper(mres); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 1000); Assert.True(mres.IsSet, "RunThreadLocalTest8_Values: Expected thread local to release the object and for it to be finalized"); } // Test that Values property throws an exception unless true was passed into the constructor { ThreadLocal<int> t = new ThreadLocal<int>(); t.Value = 5; Exception exceptionCaught = null; try { var randomValue = t.Values.Count; } catch (Exception ex) { exceptionCaught = ex; } Assert.True(exceptionCaught != null, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. No exception was thrown."); Assert.True( exceptionCaught != null && exceptionCaught is InvalidOperationException, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. Wrong exception was thrown: " + exceptionCaught.GetType().ToString()); } } [Fact] public static void RunThreadLocalTest9_Uninitialized() { for (int iter = 0; iter < 10; iter++) { ThreadLocal<int> t1 = new ThreadLocal<int>(); t1.Value = 177; ThreadLocal<int> t2 = new ThreadLocal<int>(); Assert.True(!t2.IsValueCreated, "RunThreadLocalTest9_Uninitialized: The ThreadLocal instance should have been uninitialized."); } } private class SetMreOnFinalize { private ManualResetEventSlim _mres; public SetMreOnFinalize(ManualResetEventSlim mres) { _mres = mres; } ~SetMreOnFinalize() { _mres.Set(); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Animations { /// <summary> /// Class inheriting <see cref="AnimatorBase"/> to animate the /// <see cref="System.Windows.Forms.Control.ForeColor"/> of a <see cref="Control"/>. /// </summary> public class ControlForeColorAnimator : AnimatorBase { #region Fields private Control _control; private Color _startColor; private Color _endColor; #endregion #region Constructors /// <summary> /// Creates a new instance. /// </summary> /// <param name="container">Container the new instance should be added to.</param> public ControlForeColorAnimator(IContainer container) : base(container) { Initialize(); } /// <summary> /// Creates a new instance. /// </summary> public ControlForeColorAnimator() { Initialize(); } private void Initialize() { _startColor = DefaultStartColor; _endColor = DefaultEndColor; } #endregion #region Public interface /// <summary> /// Gets or sets the starting color for the animation. /// </summary> [Browsable(true), Category("Appearance")] [Description("Gets or sets the starting color for the animation.")] public Color StartColor { get { return _startColor; } set { if (_startColor == value) return; _startColor = value; OnStartValueChanged(EventArgs.Empty); } } /// <summary> /// Gets or sets the ending Color for the animation. /// </summary> [Browsable(true), Category("Appearance")] [Description("Gets or sets the ending Color for the animation.")] public Color EndColor { get { return _endColor; } set { if (_endColor == value) return; _endColor = value; OnEndValueChanged(EventArgs.Empty); } } /// <summary> /// Gets or sets the <see cref="Control"/> which /// <see cref="System.Windows.Forms.Control.ForeColor"/> should be animated. /// </summary> [Browsable(true), Category("Behavior")] [DefaultValue(null), RefreshProperties(RefreshProperties.Repaint)] [Description("Gets or sets which Control should be animated.")] public Control Control { get { return _control; } set { if (_control == value) return; if (_control != null) _control.ForeColorChanged -= new EventHandler(OnCurrentValueChanged); _control = value; if (_control != null) _control.ForeColorChanged += new EventHandler(OnCurrentValueChanged); base.ResetValues(); } } #endregion #region Overridden from AnimatorBase /// <summary> /// Gets or sets the currently shown value. /// </summary> protected override object CurrentValueInternal { get { return _control == null ? Color.Empty : _control.ForeColor; } set { if (_control != null) _control.ForeColor = (Color)value; } } /// <summary> /// Gets or sets the starting value for the animation. /// </summary> public override object StartValue { get { return StartColor; } set { StartColor = (Color)value; } } /// <summary> /// Gets or sets the ending value for the animation. /// </summary> public override object EndValue { get { return EndColor; } set { EndColor = (Color)value; } } /// <summary> /// Calculates an interpolated value between <see cref="StartValue"/> and /// <see cref="EndValue"/> for a given step in %. /// Giving 0 will return the <see cref="StartValue"/>. /// Giving 100 will return the <see cref="EndValue"/>. /// </summary> /// <param name="step">Animation step in %</param> /// <returns>Interpolated value for the given step.</returns> protected override object GetValueForStep(double step) { if (_startColor == Color.Empty || _endColor == Color.Empty) return CurrentValue; return InterpolateColors(_startColor, _endColor, step); } #endregion #region Protected /// <summary> /// Gets the default value of the <see cref="StartColor"/> property. /// </summary> protected virtual Color DefaultStartColor { get { return Color.Empty; } } /// <summary> /// Gets the default value of the <see cref="EndColor"/> property. /// </summary> protected virtual Color DefaultEndColor { get { return Color.Empty; } } /// <summary> /// Indicates the designer whether <see cref="StartColor"/> needs /// to be serialized. /// </summary> protected virtual bool ShouldSerializeStartColor() { return _startColor != DefaultStartColor; } /// <summary> /// Indicates the designer whether <see cref="EndColor"/> needs /// to be serialized. /// </summary> protected virtual bool ShouldSerializeEndColor() { return _endColor != DefaultEndColor; } #endregion } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class JoinLogDecoder { public const ushort BLOCK_LENGTH = 36; public const ushort TEMPLATE_ID = 40; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private JoinLogDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public JoinLogDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public JoinLogDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LogPositionId() { return 1; } public static int LogPositionSinceVersion() { return 0; } public static int LogPositionEncodingOffset() { return 0; } public static int LogPositionEncodingLength() { return 8; } public static string LogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public long LogPosition() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int MaxLogPositionId() { return 2; } public static int MaxLogPositionSinceVersion() { return 0; } public static int MaxLogPositionEncodingOffset() { return 8; } public static int MaxLogPositionEncodingLength() { return 8; } public static string MaxLogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long MaxLogPositionNullValue() { return -9223372036854775808L; } public static long MaxLogPositionMinValue() { return -9223372036854775807L; } public static long MaxLogPositionMaxValue() { return 9223372036854775807L; } public long MaxLogPosition() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int MemberIdId() { return 3; } public static int MemberIdSinceVersion() { return 0; } public static int MemberIdEncodingOffset() { return 16; } public static int MemberIdEncodingLength() { return 4; } public static string MemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int MemberIdNullValue() { return -2147483648; } public static int MemberIdMinValue() { return -2147483647; } public static int MemberIdMaxValue() { return 2147483647; } public int MemberId() { return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian); } public static int LogSessionIdId() { return 4; } public static int LogSessionIdSinceVersion() { return 0; } public static int LogSessionIdEncodingOffset() { return 20; } public static int LogSessionIdEncodingLength() { return 4; } public static string LogSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LogSessionIdNullValue() { return -2147483648; } public static int LogSessionIdMinValue() { return -2147483647; } public static int LogSessionIdMaxValue() { return 2147483647; } public int LogSessionId() { return _buffer.GetInt(_offset + 20, ByteOrder.LittleEndian); } public static int LogStreamIdId() { return 5; } public static int LogStreamIdSinceVersion() { return 0; } public static int LogStreamIdEncodingOffset() { return 24; } public static int LogStreamIdEncodingLength() { return 4; } public static string LogStreamIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LogStreamIdNullValue() { return -2147483648; } public static int LogStreamIdMinValue() { return -2147483647; } public static int LogStreamIdMaxValue() { return 2147483647; } public int LogStreamId() { return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian); } public static int IsStartupId() { return 6; } public static int IsStartupSinceVersion() { return 0; } public static int IsStartupEncodingOffset() { return 28; } public static int IsStartupEncodingLength() { return 4; } public static string IsStartupMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public BooleanType IsStartup() { return (BooleanType)_buffer.GetInt(_offset + 28, ByteOrder.LittleEndian); } public static int RoleId() { return 7; } public static int RoleSinceVersion() { return 0; } public static int RoleEncodingOffset() { return 32; } public static int RoleEncodingLength() { return 4; } public static string RoleMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int RoleNullValue() { return -2147483648; } public static int RoleMinValue() { return -2147483647; } public static int RoleMaxValue() { return 2147483647; } public int Role() { return _buffer.GetInt(_offset + 32, ByteOrder.LittleEndian); } public static int LogChannelId() { return 8; } public static int LogChannelSinceVersion() { return 0; } public static string LogChannelCharacterEncoding() { return "US-ASCII"; } public static string LogChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LogChannelHeaderLength() { return 4; } public int LogChannelLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetLogChannel(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetLogChannel(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string LogChannel() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[JoinLog](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogPosition="); builder.Append(LogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='maxLogPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("MaxLogPosition="); builder.Append(MaxLogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("MemberId="); builder.Append(MemberId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='logSessionId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=20, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogSessionId="); builder.Append(LogSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='logStreamId', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogStreamId="); builder.Append(LogStreamId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='isStartup', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=0, deprecated=0, encodedLength=4, offset=28, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}} builder.Append("IsStartup="); builder.Append(IsStartup()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='role', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("Role="); builder.Append(Role()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='logChannel', referencedName='null', description='null', id=8, version=0, deprecated=0, encodedLength=0, offset=36, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogChannel="); builder.Append(LogChannel()); Limit(originalLimit); return builder; } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using Medusa.Log; using Medusa.Siren.IO; using Medusa.Siren.Schema; namespace Medusa.Siren.Code.Binary { public class CompactBinaryReader : BaseBinaryReader { public CompactBinaryReader() { } public override void OnVersion() { } public override void OnStructBegin() { } public override void OnStructEnd() { if (mIsPropertyWaiting && mCurrentPropertyType == (byte)Schema.SirenTypeId.Null) { mIsPropertyWaiting = false; } else { Stream.SkipBytes(1); } } public override void OnListBegin(out SirenTypeId dataType,out int count) { dataType = (SirenTypeId)Stream.ReadUInt8(); count = (int)Stream.ReadVarUInt32(); } public override void OnListEnd() { } public override void OnDictionaryBegin(out SirenTypeId keyDataType, out SirenTypeId valueDataType,out int count) { keyDataType = (SirenTypeId)Stream.ReadUInt8(); valueDataType = (SirenTypeId)Stream.ReadUInt8(); count = (int)Stream.ReadVarUInt32(); } public override void OnDictionaryEnd() { } public override int OnFieldBegin(string name, ushort id, SirenTypeId dataType, out ushort outId, out SirenTypeId outDataType) { if (!mIsPropertyWaiting) { ushort tempId; uint raw = Stream.ReadUInt8(); var type = (SirenTypeId)(raw & 0x1f); raw >>= 5; if (raw < 6) { tempId = (ushort)raw; } else if (raw == 6) { tempId = Stream.ReadUInt8(); } else { tempId = Stream.ReadUInt16(); } mCurrentPropertyId = tempId; mCurrentPropertyType = type; mIsPropertyWaiting = true; } outId = mCurrentPropertyId; outDataType = mCurrentPropertyType; if (id == mCurrentPropertyId) { mIsPropertyWaiting = false; return 0; } else if (id < mCurrentPropertyId) { return -1; } mIsPropertyWaiting = false; return 1; } public override void OnFieldEnd() { } public override void OnFieldSkip(SirenTypeId dataType) { SkipPropertyHelper(dataType); } public override object OnValue(Type type) { if (type == typeof(bool)) { return Stream.ReadUInt8() == 1; } else if (type == typeof(char)) { return (char)Stream.ReadUInt8(); } else if (type == typeof(short)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt16()); } else if (type == typeof(int)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt32()); } else if (type == typeof(Int64)) { return IntegerHelper.DecodeZigzag(Stream.ReadVarUInt64()); } else if (type == typeof(byte)) { return Stream.ReadUInt8(); } else if (type == typeof(ushort)) { return Stream.ReadVarUInt16(); } else if (type == typeof(uint)) { return Stream.ReadVarUInt32(); } else if (type == typeof(UInt64)) { return Stream.ReadVarUInt64(); } else if (type == typeof(float)) { return Stream.ReadFloat(); } else if (type == typeof(double)) { return Stream.ReadDouble(); } else { if (type.IsEnum) { return Stream.ReadVarUInt32(); } else { Logger.ErrorLine("Invalid value type:{0}", type); } } return null; } public override string OnString() { uint length = Stream.ReadVarUInt32(); return Stream.ReadString((int)length); } public override byte[] OnMemoryData() { uint length = Stream.ReadVarUInt32(); return Stream.ReadBytes((int)length); } public override void OnError() { } void SkipProperty() { uint raw = Stream.ReadUInt8(); var type = (SirenTypeId)(raw & 0x1f); raw >>= 5; if (raw < 6) { } else if (raw == 6) { Stream.ReadUInt8(); } else { Stream.ReadUInt16(); } SkipPropertyHelper(type); } void SkipPropertyHelper(SirenTypeId type) { switch (type) { case SirenTypeId.Bool: Stream.SkipBytes(sizeof(byte)); break; case SirenTypeId.Int8: case SirenTypeId.UInt8: Stream.SkipBytes(sizeof(byte)); break; case SirenTypeId.Int16: case SirenTypeId.UInt16: Stream.ReadVarUInt16(); break; case SirenTypeId.Int32: case SirenTypeId.UInt32: Stream.ReadVarUInt32(); break; case SirenTypeId.Int64: case SirenTypeId.UInt64: Stream.ReadVarUInt64(); break; case SirenTypeId.Float: Stream.SkipBytes(sizeof(float)); break; case SirenTypeId.Double: Stream.SkipBytes(sizeof(double)); break; case SirenTypeId.String: { uint length= Stream.ReadVarUInt32(); Stream.SkipBytes((int)length); } break; case SirenTypeId.Blob: { uint length= Stream.ReadVarUInt32(); Stream.SkipBytes((int)length); } break; case SirenTypeId.Struct: SkipProperty(); break; case SirenTypeId.List: { SirenTypeId valueType=(SirenTypeId)Stream.ReadUInt8(); uint count= Stream.ReadVarUInt32(); for (int i = 0; i < count; i++) { SkipPropertyHelper(valueType); } } break; case SirenTypeId.Dictionary: { SirenTypeId keyType=(SirenTypeId)Stream.ReadUInt8(); SirenTypeId valueType=(SirenTypeId)Stream.ReadUInt8(); uint count= Stream.ReadVarUInt32(); for (int i = 0; i < count; i++) { SkipPropertyHelper(keyType); SkipPropertyHelper(valueType); } } break; } } } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.SwaggerGen; using HETSAPI.Models; using HETSAPI.ViewModels; using HETSAPI.Services; using HETSAPI.Authorization; using HETSAPI.Services.Impl; namespace HETSAPI.Controllers { /// <summary> /// Equipment Controller /// </summary> [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class EquipmentController : Controller { private readonly IEquipmentService _service; /// <summary> /// Equipment Controller Constructor /// </summary> public EquipmentController(IEquipmentService service) { _service = service; } /// <summary> /// Create bulk equipment records /// </summary> /// <param name="items"></param> /// <response code="200">Equipment created</response> [HttpPost] [Route("/api/equipment/bulk")] [SwaggerOperation("EquipmentBulkPost")] [RequiresPermission(Permission.Admin)] public virtual IActionResult EquipmentBulkPost([FromBody]Equipment[] items) { return _service.EquipmentBulkPostAsync(items); } /// <summary> /// Get equipment by id /// </summary> /// <param name="id">id of Equipment to fetch</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}")] [SwaggerOperation("EquipmentIdGet")] [SwaggerResponse(200, type: typeof(Equipment))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdGet([FromRoute]int id) { return _service.EquipmentIdGetAsync(id); } /// <summary> /// Update equipment /// </summary> /// <param name="id">id of Equipment to update</param> /// <param name="item"></param> /// <response code="200">OK</response> [HttpPut] [Route("/api/equipment/{id}")] [SwaggerOperation("EquipmentIdPut")] [SwaggerResponse(200, type: typeof(Equipment))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdPut([FromRoute]int id, [FromBody]Equipment item) { return _service.EquipmentIdPutAsync(id, item); } /// <summary> /// Update equipment status /// </summary> /// <param name="id">id of Equipment to update</param> /// <param name="item"></param> /// <response code="200">OK</response> [HttpPut] [Route("/api/equipment/{id}/status")] [SwaggerOperation("EquipmentIdStatusPut")] [SwaggerResponse(200, type: typeof(Equipment))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdStatusPut([FromRoute]int id, [FromBody]EquipmentStatus item) { return _service.EquipmentIdStatusPutAsync(id, item); } /// <summary> /// Create equipment /// </summary> /// <param name="item"></param> /// <response code="200">Equipment created</response> [HttpPost] [Route("/api/equipment")] [SwaggerOperation("EquipmentPost")] [SwaggerResponse(200, type: typeof(Equipment))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentPost([FromBody]Equipment item) { return _service.EquipmentPostAsync(item); } /// <summary> /// Searches Equipment /// </summary> /// <remarks>Used for the equipment search page.</remarks> /// <param name="localareas">Local Areas (comma seperated list of id numbers)</param> /// <param name="types">Equipment Types (comma seperated list of id numbers)</param> /// <param name="equipmentAttachment">Searches equipmentAttachment type</param> /// <param name="owner"></param> /// <param name="status">Status</param> /// <param name="hired">Hired</param> /// <param name="notverifiedsincedate">Not Verified Since Date</param> /// <param name="equipmentId">Equipment Code</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/search")] [SwaggerOperation("EquipmentSearchGet")] [SwaggerResponse(200, type: typeof(List<EquipmentViewModel>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentSearchGet([FromQuery]string localareas, [FromQuery]string types, [FromQuery]string equipmentAttachment, [FromQuery]int? owner, [FromQuery]string status, [FromQuery]bool? hired, [FromQuery]DateTime? notverifiedsincedate, [FromQuery]string equipmentId = null) { return _service.EquipmentSearchGetAsync(localareas, types, equipmentAttachment, owner, status, hired, notverifiedsincedate, equipmentId); } #region Clone Project Agreements /// <summary> /// Get renatal agreements associated with an equipment id /// </summary> /// <remarks>Gets as Equipment&#39;s Rental Agreements</remarks> /// <param name="id">id of Equipment to fetch agreements for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/rentalAgreements")] [SwaggerOperation("EquipmentIdRentalAgreementsGet")] [SwaggerResponse(200, type: typeof(List<RentalAgreement>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdRentalAgreementsGet([FromRoute]int id) { return _service.EquipmentIdGetAgreementsAsync(id); } /// <summary> /// Update a rental agreement by cloning a previous equipment rental agreement /// </summary> /// <param name="id">Project id</param> /// <param name="item"></param> /// <response code="200">Rental Agreement cloned</response> [HttpPost] [Route("/api/equipment/{id}/rentalAgreementClone")] [SwaggerOperation("EquipmentRentalAgreementClonePost")] [SwaggerResponse(200, type: typeof(RentalAgreement))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentRentalAgreementClonePost([FromRoute]int id, [FromBody]EquipmentRentalAgreementClone item) { return _service.EquipmentRentalAgreementClonePostAsync(id, item); } #endregion #region Duplicate Equipment Records /// <summary> /// Get all duplicate equipment records /// </summary> /// <param name="id">id of Equipment to fetch EquipmentAttachments for</param> /// <param name="serialNumber"></param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/duplicates/{serialNumber}")] [SwaggerOperation("EquipmentIdEquipmentduplicatesGet")] [SwaggerResponse(200, type: typeof(List<DuplicateEquipmentViewModel>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdEquipmentduplicatesGet([FromRoute]int id, [FromRoute]string serialNumber) { return _service.EquipmentIdEquipmentduplicatesGetAsync(id, serialNumber); } #endregion #region Equipment Attachment Records /// <summary> /// Get all equipment attachments for an equipment record /// </summary> /// <param name="id">id of Equipment to fetch EquipmentAttachments for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/equipmentattachments")] [SwaggerOperation("EquipmentIdEquipmentattachmentsGet")] [SwaggerResponse(200, type: typeof(List<EquipmentAttachment>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdEquipmentattachmentsGet([FromRoute]int id) { return _service.EquipmentIdEquipmentattachmentsGetAsync(id); } #endregion #region Attachments /// <summary> /// Get all attachments associated with an equipment record /// </summary> /// <remarks>Returns attachments for a particular Equipment</remarks> /// <param name="id">id of Equipment to fetch attachments for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/attachments")] [SwaggerOperation("EquipmentIdAttachmentsGet")] [SwaggerResponse(200, type: typeof(List<AttachmentViewModel>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdAttachmentsGet([FromRoute]int id) { return _service.EquipmentIdAttachmentsGetAsync(id); } #endregion #region Equipment History Records /// <summary> /// Get equipment history /// </summary> /// <remarks>Returns History for a particular Equipment</remarks> /// <param name="id">id of Equipment to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/history")] [SwaggerOperation("EquipmentIdHistoryGet")] [SwaggerResponse(200, type: typeof(List<HistoryViewModel>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit) { return _service.EquipmentIdHistoryGetAsync(id, offset, limit); } /// <summary> /// Create equipment history /// </summary> /// <remarks>Add a History record to the Equipment</remarks> /// <param name="id">id of Equipment to add History for</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="201">History created</response> [HttpPost] [Route("/api/equipment/{id}/history")] [SwaggerOperation("EquipmentIdHistoryPost")] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdHistoryPost([FromRoute]int id, [FromBody]History item) { return _service.EquipmentIdHistoryPostAsync(id, item); } #endregion #region Equipment Note Records /// <summary> /// Get note records associated with equipment /// </summary> /// <param name="id">id of Equipment to fetch Notes for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/{id}/notes")] [SwaggerOperation("EquipmentsIdNotesGet")] [SwaggerResponse(200, type: typeof(List<Note>))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdNotesGet([FromRoute]int id) { return _service.EquipmentIdNotesGetAsync(id); } /// <summary> /// Update or create a note associated with a equipment /// </summary> /// <remarks>Update a Equipment&#39;s Notes</remarks> /// <param name="id">id of Equipment to update Notes for</param> /// <param name="item">Equipment Note</param> /// <response code="200">OK</response> [HttpPost] [Route("/api/equipment/{id}/note")] [SwaggerOperation("EquipmentIdNotePost")] [SwaggerResponse(200, type: typeof(Note))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdNotePost([FromRoute]int id, [FromBody]Note item) { return _service.EquipmentIdNotesPostAsync(id, item); } /// <summary> /// pdate or create an array of notes associated with a equipment /// </summary> /// <remarks>Adds Note Records</remarks> /// <param name="id">id of Equipment to add notes for</param> /// <param name="items">Array of Equipment Notes</param> /// <response code="200">OK</response> [HttpPost] [Route("/api/equipment/{id}/notes")] [SwaggerOperation("EquipmentIdNotesBulkPostAsync")] [SwaggerResponse(200, type: typeof(TimeRecord))] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentIdNotesBulkPostAsync([FromRoute]int id, [FromBody]Note[] items) { return _service.EquipmentIdNotesBulkPostAsync(id, items); } #endregion #region Seniority List Pdf /// <summary> /// Get a pdf version of the seniority list /// </summary> /// <remarks>Returns a PDF version of the seniority list</remarks> /// <param name="localareas">Local Areas (comma seperated list of id numbers)</param> /// <param name="types">Equipment Types (comma seperated list of id numbers)</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/equipment/seniorityListPdf")] [SwaggerOperation("EquipmentSeniorityListPdfGet")] [RequiresPermission(Permission.Login)] public virtual IActionResult EquipmentSeniorityListPdfGet([FromQuery]string localareas, [FromQuery]string types) { return _service.EquipmentSeniorityListPdfGetAsync(localareas, types); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; using OpenMetaverse.StructuredData; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar presence information (for tracking current location and /// message routing) to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_serverUrl = String.Empty; private SimianActivityDetector m_activityDetector; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); } public string Name { get { return "SimianPresenceServiceConnector"; } } public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface<IPresenceService>(this); scene.RegisterModuleInterface<IGridUserService>(this); m_activityDetector.AddRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface<IPresenceService>(this); scene.UnregisterModuleInterface<IGridUserService>(this); m_activityDetector.RemoveRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } #endregion ISharedRegionModule public SimianPresenceServiceConnector(IConfigSource source) { Initialise(source); } public void Initialise(IConfigSource source) { if (Simian.IsSimianEnabled(source, "PresenceServices", this.Name)) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig == null) { m_log.Error("[SIMIAN PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini"); throw new Exception("Presence connector init error"); } string serviceUrl = gridConfig.GetString("PresenceServerURI"); if (String.IsNullOrEmpty(serviceUrl)) { m_log.Error("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI in section PresenceService"); throw new Exception("Presence connector init error"); } m_serverUrl = serviceUrl; } } #region IPresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}", userID, sessionID, secureSessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddSession" }, { "UserID", userID.ToString() } }; if (sessionID != UUID.Zero) { requestArgs["SessionID"] = sessionID.ToString(); requestArgs["SecureSessionID"] = secureSessionID.ToString(); } OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString()); return success; } public bool LogoutAgent(UUID sessionID) { m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSession" }, { "SessionID", sessionID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString()); return success; } public bool LogoutRegionAgents(UUID regionID) { m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSessions" }, { "SceneID", regionID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString()); return success; } public bool ReportAgent(UUID sessionID, UUID regionID) { // Not needed for SimianGrid return true; } public PresenceInfo GetAgent(UUID sessionID) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSession" }, { "SessionID", sessionID.ToString() } }; OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (sessionResponse["Success"].AsBoolean()) { UUID userID = sessionResponse["UserID"].AsUUID(); m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (userResponse["Success"].AsBoolean()) return ResponseToPresenceInfo(sessionResponse, userResponse); else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString()); } else { m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString()); } return null; } public PresenceInfo[] GetAgents(string[] userIDs) { List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length); for (int i = 0; i < userIDs.Length; i++) { UUID userID; if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero) presences.AddRange(GetSessions(userID)); } return presences.ToArray(); } #endregion IPresenceService #region IGridUserService public GridUserInfo LoggedIn(string userID) { // Never implemented at the sim return null; } public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // Save our last position as user data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "HomeLocation", SerializeLocation(regionID, position, lookAt) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { return UpdateSession(sessionID, regionID, lastPosition, lastLookAt); } public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // Never called return false; } public GridUserInfo GetGridUserInfo(string user) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user); UUID userID = new UUID(user); m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (userResponse["Success"].AsBoolean()) return ResponseToGridUserInfo(userResponse); else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString()); return null; } #endregion #region Helpers private OSDMap GetUserData(UUID userID) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean() && response["User"] is OSDMap) return response; else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString()); return null; } // private OSDMap GetSessionData(UUID sessionID) // { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for session " + sessionID); // // NameValueCollection requestArgs = new NameValueCollection // { // { "RequestMethod", "GetSession" }, // { "SessionID", sessionID.ToString() } // }; // // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); // if (response["Success"].AsBoolean()) // return response; // else // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session data for session " + sessionID); // // return null; // } private List<PresenceInfo> GetSessions(UUID userID) { List<PresenceInfo> presences = new List<PresenceInfo>(1); OSDMap userResponse = GetUserData(userID); if (userResponse != null) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSession" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { PresenceInfo presence = ResponseToPresenceInfo(response, userResponse); if (presence != null) presences.Add(presence); } else { m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString()); } } return presences; } private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // Save our current location as session data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "UpdateSession" }, { "SessionID", sessionID.ToString() }, { "SceneID", regionID.ToString() }, { "ScenePosition", lastPosition.ToString() }, { "SceneLookAt", lastLookAt.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString()); return success; } ///// <summary> ///// Fetch the last known avatar location with GetSession and persist it ///// as user data with AddUserData ///// </summary> //private bool SetLastLocation(UUID sessionID) //{ // NameValueCollection requestArgs = new NameValueCollection // { // { "RequestMethod", "GetSession" }, // { "SessionID", sessionID.ToString() } // }; // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); // bool success = response["Success"].AsBoolean(); // if (success) // { // UUID userID = response["UserID"].AsUUID(); // UUID sceneID = response["SceneID"].AsUUID(); // Vector3 position = response["ScenePosition"].AsVector3(); // Vector3 lookAt = response["SceneLookAt"].AsVector3(); // return SetLastLocation(userID, sceneID, position, lookAt); // } // else // { // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve presence information for session " + sessionID + // " while saving last location: " + response["Message"].AsString()); // } // return success; //} private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse) { if (sessionResponse == null) return null; PresenceInfo info = new PresenceInfo(); info.UserID = sessionResponse["UserID"].AsUUID().ToString(); info.RegionID = sessionResponse["SceneID"].AsUUID(); return info; } private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse) { if (userResponse != null && userResponse["User"] is OSDMap) { GridUserInfo info = new GridUserInfo(); info.Online = true; info.UserID = userResponse["UserID"].AsUUID().ToString(); info.LastRegionID = userResponse["SceneID"].AsUUID(); info.LastPosition = userResponse["ScenePosition"].AsVector3(); info.LastLookAt = userResponse["SceneLookAt"].AsVector3(); OSDMap user = (OSDMap)userResponse["User"]; info.Login = user["LastLoginDate"].AsDate(); info.Logout = user["LastLogoutDate"].AsDate(); DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt); return info; } return null; } private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt) { return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}"; } private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt) { OSDMap map = null; try { map = OSDParser.DeserializeJson(location) as OSDMap; } catch { } if (map != null) { regionID = map["SceneID"].AsUUID(); if (Vector3.TryParse(map["Position"].AsString(), out position) && Vector3.TryParse(map["LookAt"].AsString(), out lookAt)) { return true; } } regionID = UUID.Zero; position = Vector3.Zero; lookAt = Vector3.Zero; return false; } #endregion Helpers } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase { [Fact] public void WithoutExpressionHoles() { var source = @" using System.Diagnostics; class C0 { } [DebuggerDisplay(""Value"")] class C1 { } [DebuggerDisplay(""Value"", Name=""Name"")] class C2 { } [DebuggerDisplay(""Value"", Type=""Type"")] class C3 { } [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class C4 { } class Wrapper { C0 c0 = new C0(); C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None), EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None), EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None), EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None), EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None)); } [Fact] public void OnlyExpressionHoles() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("c", value)), EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void FormatStrings() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BindingError() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{missing}>"")] class C { } "; const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it. var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks. } [Fact] public void RecursiveDebuggerDisplay() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"")] class C { C value; C() { this.value = this; } } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // No stack overflow, since attribute on computed value is ignored. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); } [Fact] public void MultipleAttributes() { var source = @" using System.Diagnostics; [DebuggerDisplay(""V1"")] [DebuggerDisplay(""V2"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // First attribute wins, as in dev12. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "V1", "C", rootExpr)); } [Fact] public void NullValues() { var source = @" using System.Diagnostics; [DebuggerDisplay(null, Name=null, Type=null)] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr)); } [Fact] public void EmptyStringValues() { var source = @" using System.Diagnostics; [DebuggerDisplay("""", Name="""", Type="""")] class C { } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("", "", "", "w.c")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Name"")] class C<T> { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult("c", "Name", "C<int>", rootExpr)); } [Fact] public void MemberExpansion() { var source = @" using System.Diagnostics; interface I { D P { get; } } class C : I { D I.P { get { return new D(); } } D Q { get { return new D(); } } } [DebuggerDisplay(""Value"", Name=""Name"")] class D { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult(rootExpr, value); Verify(root, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(root), EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name". EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void PointerDereferenceExpansion_Null() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } class Wrapper { Display display = new Display(); } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("wrapper", value); Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3), EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"), EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer")); } [WorkItem(321, "https://github.com/dotnet/roslyn/issues/321")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/321")] public void PointerDereferenceExpansion_NonNull() { var source = @" using System; using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe class C { Display* DisplayPointer; NoDisplay* NoDisplayPointer; public C(IntPtr d, IntPtr nd) { this.DisplayPointer = (Display*)d; this.NoDisplayPointer = (NoDisplay*)nd; this.DisplayPointer->DisplayPointer = this.DisplayPointer; this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer; this.NoDisplayPointer->DisplayPointer = this.DisplayPointer; this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer; } } "; var assembly = GetUnsafeAssembly(source); unsafe { var displayType = assembly.GetType("Display"); var displayInstance = displayType.Instantiate(); var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned); var displayPtr = displayHandle.AddrOfPinnedObject(); var noDisplayType = assembly.GetType("NoDisplay"); var noDisplayInstance = noDisplayType.Instantiate(); var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned); var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject(); var testType = assembly.GetType("C"); var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr); var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None); var displayPtrString = PointerToString(displayPtr); var noDisplayPtrString = PointerToString(noDisplayPtr); Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable)); displayHandle.Free(); noDisplayHandle.Free(); } } [Fact] public void ArrayExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] struct Display { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } struct NoDisplay { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } class C { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; public C() { this.DisplayArray = new[] { new Display() }; this.NoDisplayArray = new[] { new NoDisplay() }; this.DisplayArray[0].DisplayArray = this.DisplayArray; this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray; this.NoDisplayArray[0].DisplayArray = this.DisplayArray; this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray; } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void DebuggerTypeProxyExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] public struct Display { } public struct NoDisplay { } [DebuggerTypeProxy(typeof(P))] public class C { public Display DisplayC = new Display(); public NoDisplay NoDisplayC = new NoDisplay(); } public class P { public Display DisplayP = new Display(); public NoDisplay NoDisplayP = new NoDisplay(); public P(C c) { } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "new P(c).DisplayP"), EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"), EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Name", "Value", "Type", "c.DisplayC"), EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC")); } [Fact] public void NullInstance() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Hello"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "null", "C", rootExpr)); } [Fact] public void NonGenericDisplayAttributeOnGenericBase() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Type={GetType()}"")] class A<T> { } class B : A<int> { } "; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var result = FormatResult("b", value); Verify(result, EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None)); } [WorkItem(1016895)] [Fact] public void RootVersusInternal() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name = ""Name"")] class A { } class B { A a; public B(A a) { this.a = a; } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var instanceA = typeA.Instantiate(); var instanceB = typeB.Instantiate(instanceA); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)); result = FormatResult("b", CreateDkmClrValue(instanceB)); Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None)); } [Fact] public void Error() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class A { } class B { bool f; internal A P { get { return new A(); } } internal A Q { get { while(f) { } return new A(); } } } "; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q"), EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean)); } } [Fact] public void Exception() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value}"")] class A { internal int Value; } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var instanceA = typeA.Instantiate(); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None)); } private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth) { var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); DepthFirstSearchInternal(builder, root, 0, maxDepth); return builder.ToImmutableAndFree(); } private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth) { Assert.InRange(depth, 0, maxDepth); builder.Add(curr); var childDepth = depth + 1; if (childDepth <= maxDepth) { foreach (var child in GetChildren(curr)) { DepthFirstSearchInternal(builder, child, childDepth, maxDepth); } } } } }
/* * 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 log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// This module loads and saves OpenSimulator inventory archives /// </summary> public class InventoryArchiverModule : IRegionModule, IInventoryArchiverModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "Inventory Archiver Module"; } } public bool IsSharedModule { get { return true; } } /// <value> /// Enable or disable checking whether the iar user is actually logged in /// </value> public bool DisablePresenceChecks { get; set; } public event InventoryArchiveSaved OnInventoryArchiveSaved; /// <summary> /// The file to load and save inventory if no filename has been specified /// </summary> protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar"; /// <value> /// Pending save completions initiated from the console /// </value> protected List<Guid> m_pendingConsoleSaves = new List<Guid>(); /// <value> /// All scenes that this module knows about /// </value> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private Scene m_aScene; public InventoryArchiverModule() {} public InventoryArchiverModule(bool disablePresenceChecks) { DisablePresenceChecks = disablePresenceChecks; } public void Initialise(Scene scene, IConfigSource source) { if (m_scenes.Count == 0) { scene.RegisterModuleInterface<IInventoryArchiverModule>(this); OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted; scene.AddCommand( this, "load iar", "load iar <first> <last> <inventory path> <password> [<IAR path>]", //"load iar [--merge] <first> <last> <inventory path> <password> [<IAR path>]", "Load user inventory archive (IAR).", //"--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" //+ "<first> is user's first name." + Environment.NewLine "<first> is user's first name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<password> is the user's password." + Environment.NewLine + "<IAR path> is the filesystem path or URI from which to load the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleLoadInvConsoleCommand); scene.AddCommand( this, "save iar", "save iar <first> <last> <inventory path> <password> [<IAR path>]", "Save user inventory archive (IAR).", "<first> is the user's first name." + Environment.NewLine + "<last> is the user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleSaveInvConsoleCommand); m_aScene = scene; } m_scenes[scene.RegionInfo.RegionID] = scene; } public void PostInitialise() {} public void Close() {} /// <summary> /// Trigger the inventory archive saved event. /// </summary> protected internal void TriggerInventoryArchiveSaved( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; if (handlerInventoryArchiveSaved != null) handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream) { return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>()); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, string savePath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream) { return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>()); } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, Stream loadStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, string loadPath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } /// <summary> /// Load inventory from an inventory file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams) { try { m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; }); List<string> mainParams = optionSet.Parse(cmdparams); if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is load iar [--merge] <first name> <last name> <inventory path> <user password> [<load file path>]"); return; } string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", loadPath, invPath, firstName, lastName); if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options)) m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}", loadPath, firstName, lastName); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams) { Guid id = Guid.NewGuid(); try { if (cmdparams.Length < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> <user password> [<save file path>]"); return; } m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); string firstName = cmdparams[2]; string lastName = cmdparams[3]; string invPath = cmdparams[4]; string pass = cmdparams[5]; string savePath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", savePath, invPath, firstName, lastName); ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, new Dictionary<string, object>()); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } lock (m_pendingConsoleSaves) m_pendingConsoleSaves.Add(id); } private void SaveInvConsoleCommandCompleted( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { lock (m_pendingConsoleSaves) { if (m_pendingConsoleSaves.Contains(id)) m_pendingConsoleSaves.Remove(id); else return; } if (succeeded) { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName); } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } /// <summary> /// Get user information for the given name. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="pass">User password</param> /// <returns></returns> protected UserAccount GetUserInfo(string firstName, string lastName, string pass) { UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName); if (null == account) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", firstName, lastName); return null; } try { string encpass = Util.Md5Hash(pass); if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty) { return account; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.", firstName, lastName); return null; } } catch (Exception e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message); return null; } } /// <summary> /// Notify the client of loaded nodes if they are logged in /// </summary> /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param> private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes) { if (loadedNodes.Count == 0) return; foreach (Scene scene in m_scenes.Values) { ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID); if (user != null && !user.IsChildAgent) { foreach (InventoryNodeBase node in loadedNodes) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}", // user.Name, node.Name); user.ControllingClient.SendBulkUpdateInventory(node); } break; } } } /// <summary> /// Check if the given user is present in any of the scenes. /// </summary> /// <param name="userId">The user to check</param> /// <returns>true if the user is in any of the scenes, false otherwise</returns> protected bool CheckPresence(UUID userId) { if (DisablePresenceChecks) return true; foreach (Scene scene in m_scenes.Values) { ScenePresence p; if ((p = scene.GetScenePresence(userId)) != null) { p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false); return true; } } return false; } } }
// 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! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>CustomAudience</c> resource.</summary> public sealed partial class CustomAudienceName : gax::IResourceName, sys::IEquatable<CustomAudienceName> { /// <summary>The possible contents of <see cref="CustomAudienceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </summary> CustomerCustomAudience = 1, } private static gax::PathTemplate s_customerCustomAudience = new gax::PathTemplate("customers/{customer_id}/customAudiences/{custom_audience_id}"); /// <summary>Creates a <see cref="CustomAudienceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomAudienceName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomAudienceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomAudienceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomAudienceName"/> with the pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomAudienceName"/> constructed from the provided ids.</returns> public static CustomAudienceName FromCustomerCustomAudience(string customerId, string customAudienceId) => new CustomAudienceName(ResourceNameType.CustomerCustomAudience, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customAudienceId: gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomAudienceName"/> with pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomAudienceName"/> with pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </returns> public static string Format(string customerId, string customAudienceId) => FormatCustomerCustomAudience(customerId, customAudienceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomAudienceName"/> with pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomAudienceName"/> with pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c>. /// </returns> public static string FormatCustomerCustomAudience(string customerId, string customAudienceId) => s_customerCustomAudience.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId))); /// <summary> /// Parses the given resource name string into a new <see cref="CustomAudienceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item> /// </list> /// </remarks> /// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomAudienceName"/> if successful.</returns> public static CustomAudienceName Parse(string customAudienceName) => Parse(customAudienceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomAudienceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomAudienceName"/> if successful.</returns> public static CustomAudienceName Parse(string customAudienceName, bool allowUnparsed) => TryParse(customAudienceName, allowUnparsed, out CustomAudienceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomAudienceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item> /// </list> /// </remarks> /// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomAudienceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customAudienceName, out CustomAudienceName result) => TryParse(customAudienceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomAudienceName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customAudiences/{custom_audience_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customAudienceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomAudienceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customAudienceName, bool allowUnparsed, out CustomAudienceName result) { gax::GaxPreconditions.CheckNotNull(customAudienceName, nameof(customAudienceName)); gax::TemplatedResourceName resourceName; if (s_customerCustomAudience.TryParseName(customAudienceName, out resourceName)) { result = FromCustomerCustomAudience(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customAudienceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomAudienceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customAudienceId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomAudienceId = customAudienceId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="CustomAudienceName"/> class from the component parts of pattern /// <c>customers/{customer_id}/customAudiences/{custom_audience_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customAudienceId">The <c>CustomAudience</c> ID. Must not be <c>null</c> or empty.</param> public CustomAudienceName(string customerId, string customAudienceId) : this(ResourceNameType.CustomerCustomAudience, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customAudienceId: gax::GaxPreconditions.CheckNotNullOrEmpty(customAudienceId, nameof(customAudienceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CustomAudience</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CustomAudienceId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCustomAudience: return s_customerCustomAudience.Expand(CustomerId, CustomAudienceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomAudienceName); /// <inheritdoc/> public bool Equals(CustomAudienceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomAudienceName a, CustomAudienceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomAudienceName a, CustomAudienceName b) => !(a == b); } public partial class CustomAudience { /// <summary> /// <see cref="gagvr::CustomAudienceName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CustomAudienceName ResourceNameAsCustomAudienceName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomAudienceName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CustomAudienceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CustomAudienceName CustomAudienceName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomAudienceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation test jobs. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> internal partial class TestJobOperations : IServiceOperations<AutomationManagementClient>, ITestJobOperations { /// <summary> /// Initializes a new instance of the TestJobOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TestJobOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a test job of the runbook. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create test job operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create test job operation. /// </returns> public async Task<TestJobCreateResponse> CreateAsync(string resourceGroupName, string automationAccount, TestJobCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.RunbookName == null) { throw new ArgumentNullException("parameters.RunbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.RunbookName); url = url + "/draft/testJob"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject testJobCreateParametersValue = new JObject(); requestDoc = testJobCreateParametersValue; if (parameters.Parameters != null) { if (parameters.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Parameters).IsInitialized) { JObject parametersDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Parameters) { string parametersKey = pair.Key; string parametersValue = pair.Value; parametersDictionary[parametersKey] = parametersValue; } testJobCreateParametersValue["parameters"] = parametersDictionary; } } if (parameters.RunOn != null) { testJobCreateParametersValue["runOn"] = parameters.RunOn; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TestJobCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TestJobCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TestJob testJobInstance = new TestJob(); result.TestJob = testJobInstance; JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); testJobInstance.CreationTime = creationTimeInstance; } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); testJobInstance.Status = statusInstance; } JToken statusDetailsValue = responseDoc["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); testJobInstance.StatusDetails = statusDetailsInstance; } JToken runOnValue = responseDoc["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); testJobInstance.RunOn = runOnInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); testJobInstance.StartTime = startTimeInstance; } JToken endTimeValue = responseDoc["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); testJobInstance.EndTime = endTimeInstance; } JToken exceptionValue = responseDoc["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); testJobInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); testJobInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey2 = ((string)property.Name); string parametersValue2 = ((string)property.Value); testJobInstance.Parameters.Add(parametersKey2, parametersValue2); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the test job for the specified runbook. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get test job operation. /// </returns> public async Task<TestJobGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/Runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/testJob"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TestJobGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TestJobGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TestJob testJobInstance = new TestJob(); result.TestJob = testJobInstance; JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); testJobInstance.CreationTime = creationTimeInstance; } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); testJobInstance.Status = statusInstance; } JToken statusDetailsValue = responseDoc["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); testJobInstance.StatusDetails = statusDetailsInstance; } JToken runOnValue = responseDoc["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); testJobInstance.RunOn = runOnInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); testJobInstance.StartTime = startTimeInstance; } JToken endTimeValue = responseDoc["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); testJobInstance.EndTime = endTimeInstance; } JToken exceptionValue = responseDoc["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); testJobInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); testJobInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); testJobInstance.Parameters.Add(parametersKey, parametersValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Resume the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> ResumeAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "ResumeAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/testJob/resume"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Stop the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> StopAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "StopAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/testJob/stop"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Suspend the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SuspendAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "SuspendAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/testJob/suspend"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // Reflect.cs: Creates Element classes from an instance // // Author: // Miguel de Icaza (miguel@gnome.org) // // Copyright 2010, Novell, Inc. // // Code licensed under the MIT X11 license // using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using UIKit; using CoreGraphics; using Foundation; using MonoTouch.Dialog; /* Cloned from https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Reflect.cs to add localization ability. Unfortunately RootElement.group is marked 'internal' in MonoTouch.Dialog so this implementation is missing RadioGroup functionality ~ scroll to the end of the file to see the commented-out lines. Patch to original file https://github.com/conceptdev/MonoTouch.Dialog/commit/74a7898861d542b367af3b98b7d84079f08926f4 */ namespace MonoTouch.Dialog { [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)] public class LocalizeAttribute : Attribute {} public class LocalizableBindingContext : IDisposable { public RootElement Root; Dictionary<Element,MemberAndInstance> mappings; class MemberAndInstance { public MemberAndInstance (MemberInfo mi, object o) { Member = mi; Obj = o; } public MemberInfo Member; public object Obj; } static object GetValue (MemberInfo mi, object o) { var fi = mi as FieldInfo; if (fi != null) return fi.GetValue (o); var pi = mi as PropertyInfo; var getMethod = pi.GetGetMethod (); return getMethod.Invoke (o, new object [0]); } static void SetValue (MemberInfo mi, object o, object val) { var fi = mi as FieldInfo; if (fi != null){ fi.SetValue (o, val); return; } var pi = mi as PropertyInfo; var setMethod = pi.GetSetMethod (); setMethod.Invoke (o, new object [] { val }); } static string MakeCaption (string name) { var sb = new StringBuilder (name.Length); bool nextUp = true; foreach (char c in name){ if (nextUp){ sb.Append (Char.ToUpper (c)); nextUp = false; } else { if (c == '_'){ sb.Append (' '); continue; } if (Char.IsUpper (c)) sb.Append (' '); sb.Append (c); } } return sb.ToString (); } // Returns the type for fields and properties and null for everything else static Type GetTypeForMember (MemberInfo mi) { if (mi is FieldInfo) return ((FieldInfo) mi).FieldType; else if (mi is PropertyInfo) return ((PropertyInfo) mi).PropertyType; return null; } public LocalizableBindingContext (object callbacks, object o, string title) { if (o == null) throw new ArgumentNullException ("o"); mappings = new Dictionary<Element,MemberAndInstance> (); Root = new RootElement (title); Populate (callbacks, o, Root); } void Populate (object callbacks, object o, RootElement root) { MemberInfo last_radio_index = null; var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); Section section = null; foreach (var mi in members) { Type mType = GetTypeForMember (mi); if (mType == null) continue; string caption = null; string key = null; // l18n object [] attrs = mi.GetCustomAttributes (false); bool skip = false; bool localize = false; foreach (var attr in attrs) { if (attr is LocalizeAttribute) { localize = true; break; } } foreach (var attr in attrs) { if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute) skip = true; else if (attr is CaptionAttribute) { caption = ((CaptionAttribute)attr).Caption; if (localize) caption = NSBundle.MainBundle.LocalizedString (caption, caption); } else if (attr is SectionAttribute) { if (section != null) root.Add (section); var sa = attr as SectionAttribute; var header = sa.Caption; var footer = sa.Footer; if (localize) { header = NSBundle.MainBundle.LocalizedString (header, header); footer = NSBundle.MainBundle.LocalizedString (footer, footer); } section = new Section (header, footer); } } if (skip) continue; if (caption == null) { caption = MakeCaption (mi.Name); if (localize) caption = NSBundle.MainBundle.LocalizedString (caption, caption); } if (section == null) section = new Section (); Element element = null; if (mType == typeof(string)) { PasswordAttribute pa = null; AlignmentAttribute align = null; EntryAttribute ea = null; object html = null; Action invoke = null; bool multi = false; foreach (object attr in attrs) { if (attr is PasswordAttribute) pa = attr as PasswordAttribute; else if (attr is EntryAttribute) ea = attr as EntryAttribute; else if (attr is MultilineAttribute) multi = true; else if (attr is HtmlAttribute) html = attr; else if (attr is AlignmentAttribute) align = attr as AlignmentAttribute; if (attr is OnTapAttribute) { string mname = ((OnTapAttribute)attr).Method; if (callbacks == null) { throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor"); } var method = callbacks.GetType ().GetMethod (mname); if (method == null) throw new Exception ("Did not find method " + mname); invoke = delegate { method.Invoke (method.IsStatic ? null : callbacks, new object [0]); }; } } string value = (string)GetValue (mi, o); if (pa != null) { var placeholder = pa.Placeholder; if (localize) placeholder = NSBundle.MainBundle.LocalizedString (placeholder, placeholder); element = new EntryElement (caption, placeholder, value, true); } else if (ea != null) { var placeholder = ea.Placeholder; if (localize) placeholder = NSBundle.MainBundle.LocalizedString (placeholder, placeholder); element = new EntryElement (caption, placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode }; } else if (multi) element = new MultilineElement (caption, value); else if (html != null) element = new HtmlElement (caption, value); else { var selement = new StringElement (caption, value); element = selement; if (align != null) selement.Alignment = align.Alignment; } if (invoke != null) ((StringElement)element).Tapped += invoke; } else if (mType == typeof(float)) { var floatElement = new FloatElement (null, null, (float)GetValue (mi, o)); floatElement.Caption = caption; element = floatElement; foreach (object attr in attrs) { if (attr is RangeAttribute) { var ra = attr as RangeAttribute; floatElement.MinValue = ra.Low; floatElement.MaxValue = ra.High; floatElement.ShowCaption = ra.ShowCaption; } } } else if (mType == typeof(bool)) { bool checkbox = false; foreach (object attr in attrs) { if (attr is CheckboxAttribute) checkbox = true; } if (checkbox) element = new CheckboxElement (caption, (bool)GetValue (mi, o)); else element = new BooleanElement (caption, (bool)GetValue (mi, o)); } else if (mType == typeof(DateTime)) { var dateTime = (DateTime)GetValue (mi, o); bool asDate = false, asTime = false; foreach (object attr in attrs) { if (attr is DateAttribute) asDate = true; else if (attr is TimeAttribute) asTime = true; } if (asDate) element = new DateElement (caption, dateTime); else if (asTime) element = new TimeElement (caption, dateTime); else element = new DateTimeElement (caption, dateTime); } else if (mType.IsEnum) { var csection = new Section (); ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null); int idx = 0; int selected = 0; foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)) { ulong v = Convert.ToUInt64 (GetValue (fi, null)); if (v == evalue) selected = idx; CaptionAttribute ca = Attribute.GetCustomAttribute (fi, typeof(CaptionAttribute)) as CaptionAttribute; var cap = ca != null ? ca.Caption : MakeCaption (fi.Name); if (localize) NSBundle.MainBundle.LocalizedString (cap, cap); csection.Add (new RadioElement (cap)); idx++; } element = new RootElement (caption, new RadioGroup (null, selected)) { csection }; } else if (mType == typeof (UIImage)){ element = new ImageElement ((UIImage) GetValue (mi, o)); } else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){ var csection = new Section (); int count = 0; if (last_radio_index == null) throw new Exception ("IEnumerable found, but no previous int found"); foreach (var e in (IEnumerable) GetValue (mi, o)){ csection.Add (new RadioElement (e.ToString ())); count++; } int selected = (int) GetValue (last_radio_index, o); if (selected >= count || selected < 0) selected = 0; element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection }; last_radio_index = null; } else if (typeof (int) == mType){ foreach (object attr in attrs){ if (attr is RadioSelectionAttribute){ last_radio_index = mi; break; } } } else { var nested = GetValue (mi, o); if (nested != null){ var newRoot = new RootElement (caption); Populate (callbacks, nested, newRoot); element = newRoot; } } if (element == null) continue; section.Add (element); mappings [element] = new MemberAndInstance (mi, o); } root.Add (section); } class MemberRadioGroup : RadioGroup { public MemberInfo mi; public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected) { this.mi = mi; } } public void Dispose () { Dispose (true); } protected virtual void Dispose (bool disposing) { if (disposing){ foreach (var element in mappings.Keys){ element.Dispose (); } mappings = null; } } public void Fetch () { foreach (var dk in mappings){ Element element = dk.Key; MemberInfo mi = dk.Value.Member; object obj = dk.Value.Obj; if (element is DateTimeElement) SetValue (mi, obj, ((DateTimeElement) element).DateValue); else if (element is FloatElement) SetValue (mi, obj, ((FloatElement) element).Value); else if (element is BooleanElement) SetValue (mi, obj, ((BooleanElement) element).Value); else if (element is CheckboxElement) SetValue (mi, obj, ((CheckboxElement) element).Value); else if (element is EntryElement){ var entry = (EntryElement) element; entry.FetchValue (); SetValue (mi, obj, entry.Value); } else if (element is ImageElement) SetValue (mi, obj, ((ImageElement) element).Value); else if (element is RootElement){ //HACK: RootElement.group is INTERNAL // var re = element as RootElement; // if (re.group as MemberRadioGroup != null){ // var group = re.group as MemberRadioGroup; // SetValue (group.mi, obj, re.RadioSelected); // } else if (re.group as RadioGroup != null){ // var mType = GetTypeForMember (mi); // var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected]; // // SetValue (mi, obj, fi.GetValue (null)); // } } } } } }
using System.Collections.Generic; using Codecov.Services.ContinuousIntegrationServers; using FluentAssertions; using Moq; using Xunit; namespace Codecov.Tests.Services.ContiniousIntegrationServers { public class AzurePipelinesTests { public static IEnumerable<object[]> Build_Url_Empty_Data { get { var possibleDomains = new[] { null, string.Empty, "https://dev.azure.com/", "http://localhost:5234/" }; var possibleDummies = new[] { null, string.Empty, "foo", "bar" }; foreach (var domain in possibleDomains) { foreach (var project in possibleDummies) { foreach (var build in possibleDummies) { if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(project) || string.IsNullOrEmpty(build)) { yield return new object[] { domain, project, build }; } } } } } } [Fact] public void Branch_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_TARGETBRANCH")).Returns(string.Empty); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEBRANCHNAME")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var branch = pipelines.Branch; // Then branch.Should().BeEmpty(); } [Fact] public void Branch_Should_Be_Set_When_Branch_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_TARGETBRANCH")).Returns(string.Empty); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEBRANCHNAME")).Returns("develop"); var pipelines = new AzurePipelines(ev.Object); // When var branch = pipelines.Branch; // Then branch.Should().Be("develop"); } [Fact] public void Branch_Should_Be_Set_When_PR_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_TARGETBRANCH")).Returns("develop"); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEBRANCHNAME")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var branch = pipelines.Branch; // Then branch.Should().Be("develop"); } [Fact] public void Branch_Should_Prefer_Pull_Request() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_TARGETBRANCH")).Returns("pr"); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEBRANCHNAME")).Returns("master"); var pipelines = new AzurePipelines(ev.Object); // When var branch = pipelines.Branch; // Then branch.Should().Be("pr"); } [Fact] public void Build_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDNUMBER")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var build = pipelines.Build; // Then build.Should().BeEmpty(); } [Fact] public void Build_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDNUMBER")).Returns("123"); var pipelines = new AzurePipelines(ev.Object); // When var build = pipelines.Build; // Then build.Should().Be("123"); } [Theory, MemberData(nameof(Build_Url_Empty_Data))] public void BuildUrl_Should_Be_Empty_String_When_Environment_Variables_Do_Not_Exist(string serverUrl, string project, string build) { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONSERVERURI")).Returns(serverUrl); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")).Returns(project); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDID")).Returns(build); var pipelines = new AzurePipelines(ev.Object); // When var buildUrl = pipelines.BuildUrl; // Then buildUrl.Should().BeEmpty(); } [Theory, InlineData("http://"), InlineData("http://."), InlineData("http://.."), InlineData("http://../"), InlineData("http://?"), InlineData("http://??"), InlineData("http://#"), InlineData("http://##"), InlineData("//"), InlineData("//a"), InlineData("///a"), InlineData("///"), InlineData("foo.com"), InlineData("rdar://1234"), InlineData("h://test"), InlineData("http:// shouldfail.com"), InlineData(":// should fail"), InlineData("ftps://foo.bar/"), InlineData("http://.www.foo.bar/")] public void BuildUrl_Should_Be_Empty_When_Appveyor_Url_Is_Invalid_Domain(string urlData) { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONSERVERURI")).Returns(urlData); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")).Returns("project"); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDID")).Returns("build"); var pipelines = new AzurePipelines(ev.Object); // When var buildUrl = pipelines.BuildUrl; // Then buildUrl.Should().BeEmpty(); } [Fact] public void BuildUrl_Should_Not_Empty_String_When_Environment_Variable_Exists() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONSERVERURI")).Returns("https://dev.azure.com/"); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")).Returns("project"); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDID")).Returns("build"); var pipelines = new AzurePipelines(ev.Object); // When var buildUrl = pipelines.BuildUrl; // Then buildUrl.Should().Be("https://dev.azure.com/project/_build/results?buildId=build"); } [Fact] public void Commit_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEVERSION")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var commit = pipelines.Commit; // Then commit.Should().BeEmpty(); } [Fact] public void Commit_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_SOURCEVERSION")).Returns("123"); var pipelines = new AzurePipelines(ev.Object); // When var commit = pipelines.Commit; // Then commit.Should().Be("123"); } [Theory, InlineData(null), InlineData(""), InlineData("False"), InlineData("foo")] public void Detecter_Should_Be_False_When_TfBuild_Enviornment_Variable_Does_Not_Exit(string pipelinesData) { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("TF_BUILD")).Returns(pipelinesData); var pipelines = new AzurePipelines(ev.Object); // When var detecter = pipelines.Detecter; // Then detecter.Should().BeFalse(); } [Theory, InlineData("", ""), InlineData("foo", "")] public void Job_Should_Be_Empty_String_When_Enviornment_Variables_Do_Not_Exit(string slugData, string versionData) { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_REPOSITORY_NAME")).Returns(slugData); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDID")).Returns(versionData); var pipelines = new AzurePipelines(ev.Object); // When var job = pipelines.Job; // Then job.Should().BeEmpty(); } [Fact] public void Job_Should_Not_Be_Empty_String_When_Enviornment_Variables_Exit() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_REPOSITORY_NAME")).Returns("foo/bar"); ev.Setup(s => s.GetEnvironmentVariable("BUILD_BUILDID")).Returns("bang"); var pipelines = new AzurePipelines(ev.Object); // When var job = pipelines.Job; // Then job.Should().Be("bang"); } [Fact] public void Pr_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var pr = pipelines.Pr; // Then pr.Should().BeEmpty(); } [Fact] public void Pr_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER")).Returns("123"); var pipelines = new AzurePipelines(ev.Object); // When var pr = pipelines.Pr; // Then pr.Should().Be("123"); } [Fact] public void Project_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var project = pipelines.Project; // Then project.Should().BeEmpty(); } [Fact] public void Project_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMPROJECT")).Returns("123"); var pipelines = new AzurePipelines(ev.Object); // When var project = pipelines.Project; // Then project.Should().Be("123"); } [Fact] public void ServerUri_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONSERVERURI")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var serverUri = pipelines.ServerUri; // Then serverUri.Should().BeEmpty(); } [Fact] public void ServerUri_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONSERVERURI")).Returns("123"); var pipelines = new AzurePipelines(ev.Object); // When var serverUri = pipelines.ServerUri; // Then serverUri.Should().Be("123"); } [Fact] public void Service_Should_Be_Set_To_AzurePipelines() { // Given var pipelines = new AzurePipelines(new Mock<IEnviornmentVariables>().Object); // When var service = pipelines.Service; // Then service.Should().Be("azure_pipelines"); } [Fact] public void Slug_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_REPOSITORY_NAME")).Returns(string.Empty); var pipelines = new AzurePipelines(ev.Object); // When var slug = pipelines.Slug; // Then slug.Should().BeEmpty(); } [Fact] public void Slug_Should_Be_Set_When_Enviornment_Variable_Exits() { // Given var ev = new Mock<IEnviornmentVariables>(); ev.Setup(s => s.GetEnvironmentVariable("BUILD_REPOSITORY_NAME")).Returns("foo/bar"); var pipelines = new AzurePipelines(ev.Object); // When var slug = pipelines.Slug; // Then slug.Should().Be("foo/bar"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net.Http; using PaymillWrapper.Models; using PaymillWrapper.Utils; using System.Threading.Tasks; namespace PaymillWrapper.Service { public class ChecksumService : AbstractService<Checksum> { public ChecksumService(HttpClient client, string apiUrl) : base(Resource.Checksums, client, apiUrl) { } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged.</param> /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <returns> /// Checksum object. /// </returns> public async Task<Checksum> CreateChecksumForPaypalAsync(int amount, String currency, String returnUrl, String cancelUrl) { return await CreateChecksumForPaypalWithDescriptionAsync(amount, currency, returnUrl, cancelUrl, null); } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged.</param> /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <param name="fee"> /// A {@link Fee}.</param> /// <param name="appId"> /// App (ID) that created this refund or null if created by yourself.</param> /// <returns> /// Checksum object. /// </returns> public async Task<Checksum> CreateChecksumForPaypalWithFeeAsync(int amount, String currency, String returnUrl, String cancelUrl, Fee fee, String appId) { return await CreateChecksumForPaypalWithFeeAndDescriptionAsync(amount, currency, returnUrl, cancelUrl, fee, null, appId); } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged</param>. /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <param name="description"> /// A short description for the transaction.</param> /// <returns> /// Checksum object. /// </returns> public async Task<Checksum> CreateChecksumForPaypalWithDescriptionAsync(int amount, String currency, String returnUrl, String cancelUrl, String description) { return await CreateChecksumForPaypalWithItemsAndAddressAsync(amount, currency, returnUrl, cancelUrl, description, null, null, null); } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged.</param> /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <param name="fee"> /// A {@link Fee}.</param> /// <param name="description"> /// A short description for the transaction.</param> /// <param name="appId"> /// App (ID) that created this refund or null if created by yourself.</param> /// <returns> /// Checksum object. /// </returns> public async Task<Checksum> CreateChecksumForPaypalWithFeeAndDescriptionAsync(int amount, String currency, String returnUrl, String cancelUrl, Fee fee, String description, String appId) { return await CreateChecksumForPaypalWithFeeAndItemsAndAddressAsync(amount, currency, returnUrl, cancelUrl, fee, description, null, null, null, appId); } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged.</param> /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <param name="description"> /// A short description for the transaction or <code>null</code>.</param> /// <param name="items"> /// {@link List} of {@link ShoppingCartItem}s</param> /// <param name="billing /// Billing {@link Address} for this transaction. /// <param name="shipping"> /// Shipping {@link Address} for this transaction. /// <returns> /// Checksum object. /// </returns> public async Task<Checksum> CreateChecksumForPaypalWithItemsAndAddressAsync(int amount, String currency, String returnUrl, String cancelUrl, String description, List<ShoppingCartItem> items, Address shipping, Address billing) { return await CreateChecksumForPaypalWithFeeAndItemsAndAddressAsync(amount, currency, returnUrl, cancelUrl, null, description, items, shipping, billing, null); } /// <summary> /// Created a {@link Checksum} of {@link Checksum.Type} with amount in the given currency. /// </summary> /// <param name="amount"> /// Amount (in cents) which will be charged.</param> /// <param name="currency"> /// ISO 4217 formatted currency code.</param> /// <param name="returnUrl"> /// URL to redirect customers to after checkout has completed.</param> /// <param name="cancelUrl"> /// URL to redirect customers to after they have canceled the checkout. As a result, there will be no transaction.</param> /// <param name="fee"> /// A {@link Fee}. /// <param name="description"> /// A short description for the transaction or <code>null</code>.</param> /// <param name="items"> /// {@link List} of {@link ShoppingCartItem}s</param> /// <param name="billing"> /// Billing {@link Address} for this transaction.</param> /// <param name="shipping"> /// Shipping {@link Address} for this transaction.</param> /// <param name="appId"> /// App (ID) that created this refund or null if created by yourself.</param> /// <returns> /// Checksum object. /// </returns> private async Task<Checksum> CreateChecksumForPaypalWithFeeAndItemsAndAddressAsync(int amount, String currency, String returnUrl, String cancelUrl, Fee fee, String description, List<ShoppingCartItem> items, Address shipping, Address billing, String appId) { ValidationUtils.ValidatesAmount(amount); ValidationUtils.ValidatesCurrency(currency); ValidationUtils.ValidatesUrl(cancelUrl); ValidationUtils.ValidatesUrl(returnUrl); ValidationUtils.ValidatesFee(fee); ParameterMap<String, String> paramsMap = new ParameterMap<String, String>(); paramsMap.Add("checksum_type", "paypal"); paramsMap.Add("amount", amount.ToString()); paramsMap.Add("currency", currency); paramsMap.Add("cancel_url", cancelUrl); paramsMap.Add("return_url", returnUrl); if (String.IsNullOrWhiteSpace(description) == false) { paramsMap.Add("description", description); } if (fee != null && fee.Amount != null) { paramsMap.Add("fee_amount", fee.Amount.ToString()); } if (fee != null && String.IsNullOrWhiteSpace(fee.Payment) == false) { paramsMap.Add("fee_payment", fee.Payment); } if (fee != null && String.IsNullOrWhiteSpace(fee.Currency) == false) { paramsMap.Add("fee_currency", fee.Currency); } if (String.IsNullOrWhiteSpace(appId) == false) { paramsMap.Add("app_id", appId); } this.parametrizeItems(items, paramsMap); this.parametrizeAddress(billing, paramsMap, "billing_address"); this.parametrizeAddress(shipping, paramsMap, "shipping_address"); return await createAsync(null, new UrlEncoder().EncodeParamsMap<string, string>(paramsMap)); } private void parametrizeItems(List<ShoppingCartItem> items, ParameterMap<String, String> paramsMap) { if (items != null) { for (int i = 0; i < items.Count(); i++) { if (String.IsNullOrWhiteSpace(items[i].Name) == false) { paramsMap.Add("items[" + i + "][name]", items[i].Name); } if (String.IsNullOrWhiteSpace(items[i].Description) == false) { paramsMap.Add("items[" + i + "][description]", items[i].Description); } if (items[i].Amount != 0) { paramsMap.Add("items[" + i + "][amount]", items[i].Amount.ToString()); } if (items[i].Quantity != 0) { paramsMap.Add("items[" + i + "][quantity]", items[i].Quantity.ToString()); } if (String.IsNullOrWhiteSpace(items[i].ItemNumber) == false) { paramsMap.Add("items[" + i + "][item_number]", items[i].ItemNumber); } if (String.IsNullOrWhiteSpace(items[i].Url) == false) { paramsMap.Add("items[" + i + "][url]", items[i].Url); } } } } protected override string GetResourceId(Checksum obj) { return obj.Id; } private void parametrizeAddress(Address address, ParameterMap<String, String> paramsMap, String prefix) { if (address != null) { if (String.IsNullOrWhiteSpace(address.Name) == false) { paramsMap.Add(prefix + "[name]", address.Name); } if (String.IsNullOrWhiteSpace(address.StreetAddress) == false) { paramsMap.Add(prefix + "[street_address]", address.StreetAddress); } if (String.IsNullOrWhiteSpace(address.StreetAddressAddition) == false) { paramsMap.Add(prefix + "[street_address_addition]", address.StreetAddressAddition); } if (String.IsNullOrWhiteSpace(address.City) == false) { paramsMap.Add(prefix + "[city]", address.City); } if (String.IsNullOrWhiteSpace(address.State) == false) { paramsMap.Add(prefix + "[state]", address.State); } if (String.IsNullOrWhiteSpace(address.PostalCode) == false) { paramsMap.Add(prefix + "[postal_code]", address.PostalCode); } if (String.IsNullOrWhiteSpace(address.Country) == false) { paramsMap.Add(prefix + "[country]", address.Country); } if (String.IsNullOrWhiteSpace(address.Phone) == false) { paramsMap.Add(prefix + "[phone]", address.Phone); } } } } }
// 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 Microsoft.Win32; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; namespace System.ComponentModel { /// <summary> /// <para>Provides a type converter to convert object references to and from various /// other representations.</para> /// </summary> public class ReferenceConverter : TypeConverter { private static readonly string s_none = SR.toStringNone; private Type _type; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.ReferenceConverter'/> class. /// </para> /// </summary> public ReferenceConverter(Type type) { _type = type; } /// <internalonly/> /// <summary> /// <para>Gets a value indicating whether this converter can convert an object in the /// given source type to a reference object using the specified context.</para> /// </summary> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string) && context != null) { return true; } return base.CanConvertFrom(context, sourceType); } /// <internalonly/> /// <summary> /// <para>Converts the given object to the reference type.</para> /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string text = ((string)value).Trim(); if (!String.Equals(text, s_none) && context != null) { // Try the reference service first. // IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object obj = refSvc.GetReference(text); if (obj != null) { return obj; } } // Now try IContainer // IContainer cont = context.Container; if (cont != null) { object obj = cont.Components[text]; if (obj != null) { return obj; } } } return null; } return base.ConvertFrom(context, culture, value); } /// <internalonly/> /// <summary> /// <para>Converts the given value object to the reference type /// using the specified context and arguments.</para> /// </summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { if (value != null) { // Try the reference service first. // IReferenceService refSvc = (IReferenceService) context?.GetService(typeof(IReferenceService)); if (refSvc != null) { string name = refSvc.GetName(value); if (name != null) { return name; } } // Now see if this is an IComponent. // if (!Marshal.IsComObject(value) && value is IComponent) { IComponent comp = (IComponent)value; ISite site = comp.Site; string name = site?.Name; if (name != null) { return name; } } // Couldn't find it. return String.Empty; } return s_none; } return base.ConvertTo(context, culture, value, destinationType); } /// <internalonly/> /// <summary> /// <para>Gets a collection of standard values for the reference data type.</para> /// </summary> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { object[] components = null; if (context != null) { List<object> list = new List<object>(); list.Add(null); // Try the reference service first. // IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object[] objs = refSvc.GetReferences(_type); int count = objs.Length; for (int i = 0; i < count; i++) { if (IsValueAllowed(context, objs[i])) list.Add(objs[i]); } } else { // Now try IContainer. // IContainer cont = context.Container; if (cont != null) { ComponentCollection objs = cont.Components; foreach (IComponent obj in objs) { if (obj != null && _type.IsInstanceOfType(obj) && IsValueAllowed(context, obj)) { list.Add(obj); } } } } components = list.ToArray(); Array.Sort(components, 0, components.Length, new ReferenceComparer(this)); } return new StandardValuesCollection(components); } /// <internalonly/> /// <summary> /// <para>Gets a value indicating whether the list of standard values returned from /// <see cref='System.ComponentModel.ReferenceConverter.GetStandardValues'/> is an exclusive list. </para> /// </summary> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } /// <internalonly/> /// <summary> /// <para>Gets a value indicating whether this object supports a standard set of values /// that can be picked from a list.</para> /// </summary> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// <summary> /// <para>Gets a value indicating whether a particular value can be added to /// the standard values collection.</para> /// </summary> protected virtual bool IsValueAllowed(ITypeDescriptorContext context, object value) { return true; } /// <summary> /// IComparer object used for sorting references /// </summary> private class ReferenceComparer : IComparer { private ReferenceConverter _converter; public ReferenceComparer(ReferenceConverter converter) { _converter = converter; } public int Compare(object item1, object item2) { String itemName1 = _converter.ConvertToString(item1); String itemName2 = _converter.ConvertToString(item2); return string.Compare(itemName1, itemName2, false, CultureInfo.InvariantCulture); } } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; namespace Ctrip.Core { /// <summary> /// A strongly-typed collection of <see cref="Level"/> objects. /// </summary> /// <author>Nicko Cadell</author> public class LevelCollection : ICollection, IList, IEnumerable, ICloneable { #region Interfaces /// <summary> /// Supports type-safe iteration over a <see cref="LevelCollection"/>. /// </summary> public interface ILevelCollectionEnumerator { /// <summary> /// Gets the current element in the collection. /// </summary> Level Current { get; } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> bool MoveNext(); /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> void Reset(); } #endregion private const int DEFAULT_CAPACITY = 16; #region Implementation (data) private Level[] m_array; private int m_count = 0; private int m_version = 0; #endregion #region Static Wrappers /// <summary> /// Creates a read-only wrapper for a <c>LevelCollection</c> instance. /// </summary> /// <param name="list">list to create a readonly wrapper arround</param> /// <returns> /// A <c>LevelCollection</c> wrapper that is read-only. /// </returns> public static LevelCollection ReadOnly(LevelCollection list) { if(list==null) throw new ArgumentNullException("list"); return new ReadOnlyLevelCollection(list); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that is empty and has the default initial capacity. /// </summary> public LevelCollection() { m_array = new Level[DEFAULT_CAPACITY]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that has the specified initial capacity. /// </summary> /// <param name="capacity"> /// The number of elements that the new <c>LevelCollection</c> is initially capable of storing. /// </param> public LevelCollection(int capacity) { m_array = new Level[capacity]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <c>LevelCollection</c>. /// </summary> /// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param> public LevelCollection(LevelCollection c) { m_array = new Level[c.Count]; AddRange(c); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> array. /// </summary> /// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param> public LevelCollection(Level[] a) { m_array = new Level[a.Length]; AddRange(a); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> collection. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param> public LevelCollection(ICollection col) { m_array = new Level[col.Count]; AddRange(col); } /// <summary> /// Type visible only to our subclasses /// Used to access protected constructor /// </summary> protected internal enum Tag { /// <summary> /// A value /// </summary> Default } /// <summary> /// Allow subclasses to avoid our default constructors /// </summary> /// <param name="tag"></param> protected internal LevelCollection(Tag tag) { m_array = null; } #endregion #region Operations (type-safe ICollection) /// <summary> /// Gets the number of elements actually contained in the <c>LevelCollection</c>. /// </summary> public virtual int Count { get { return m_count; } } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> public virtual void CopyTo(Level[] array) { this.CopyTo(array, 0); } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array, starting at the specified index of the target array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> /// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param> public virtual void CopyTo(Level[] array, int start) { if (m_count > array.GetUpperBound(0) + 1 - start) { throw new System.ArgumentException("Destination array was not long enough."); } Array.Copy(m_array, 0, array, start, m_count); } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</value> public virtual bool IsSynchronized { get { return m_array.IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> public virtual object SyncRoot { get { return m_array.SyncRoot; } } #endregion #region Operations (type-safe IList) /// <summary> /// Gets or sets the <see cref="Level"/> at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual Level this[int index] { get { ValidateIndex(index); // throws return m_array[index]; } set { ValidateIndex(index); // throws ++m_version; m_array[index] = value; } } /// <summary> /// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The index at which the value has been added.</returns> public virtual int Add(Level item) { if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } m_array[m_count] = item; m_version++; return m_count++; } /// <summary> /// Removes all elements from the <c>LevelCollection</c>. /// </summary> public virtual void Clear() { ++m_version; m_array = new Level[DEFAULT_CAPACITY]; m_count = 0; } /// <summary> /// Creates a shallow copy of the <see cref="LevelCollection"/>. /// </summary> /// <returns>A new <see cref="LevelCollection"/> with a shallow copy of the collection data.</returns> public virtual object Clone() { LevelCollection newCol = new LevelCollection(m_count); Array.Copy(m_array, 0, newCol.m_array, 0, m_count); newCol.m_count = m_count; newCol.m_version = m_version; return newCol; } /// <summary> /// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to check for.</param> /// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns> public virtual bool Contains(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return true; } } return false; } /// <summary> /// Returns the zero-based index of the first occurrence of a <see cref="Level"/> /// in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param> /// <returns> /// The zero-based index of the first occurrence of <paramref name="item"/> /// in the entire <c>LevelCollection</c>, if found; otherwise, -1. /// </returns> public virtual int IndexOf(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return i; } } return -1; } /// <summary> /// Inserts an element into the <c>LevelCollection</c> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The <see cref="Level"/> to insert.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void Insert(int index, Level item) { ValidateIndex(index, true); // throws if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } if (index < m_count) { Array.Copy(m_array, index, m_array, index + 1, m_count - index); } m_array[index] = item; m_count++; m_version++; } /// <summary> /// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param> /// <exception cref="ArgumentException"> /// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>. /// </exception> public virtual void Remove(Level item) { int i = IndexOf(item); if (i < 0) { throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); } ++m_version; RemoveAt(i); } /// <summary> /// Removes the element at the specified index of the <c>LevelCollection</c>. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void RemoveAt(int index) { ValidateIndex(index); // throws m_count--; if (index < m_count) { Array.Copy(m_array, index + 1, m_array, index, m_count - index); } // We can't set the deleted entry equal to null, because it might be a value type. // Instead, we'll create an empty single-element array of the right type and copy it // over the entry we want to erase. Level[] temp = new Level[1]; Array.Copy(temp, 0, m_array, m_count, 1); m_version++; } /// <summary> /// Gets a value indicating whether the collection has a fixed size. /// </summary> /// <value>true if the collection has a fixed size; otherwise, false. The default is false</value> public virtual bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the IList is read-only. /// </summary> /// <value>true if the collection is read-only; otherwise, false. The default is false</value> public virtual bool IsReadOnly { get { return false; } } #endregion #region Operations (type-safe IEnumerable) /// <summary> /// Returns an enumerator that can iterate through the <c>LevelCollection</c>. /// </summary> /// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns> public virtual ILevelCollectionEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Public helpers (just to mimic some nice features of ArrayList) /// <summary> /// Gets or sets the number of elements the <c>LevelCollection</c> can contain. /// </summary> public virtual int Capacity { get { return m_array.Length; } set { if (value < m_count) { value = m_count; } if (value != m_array.Length) { if (value > 0) { Level[] temp = new Level[value]; Array.Copy(m_array, 0, temp, 0, m_count); m_array = temp; } else { m_array = new Level[DEFAULT_CAPACITY]; } } } } /// <summary> /// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(LevelCollection x) { if (m_count + x.Count >= m_array.Length) { EnsureCapacity(m_count + x.Count); } Array.Copy(x.m_array, 0, m_array, m_count, x.Count); m_count += x.Count; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(Level[] x) { if (m_count + x.Length >= m_array.Length) { EnsureCapacity(m_count + x.Length); } Array.Copy(x, 0, m_array, m_count, x.Length); m_count += x.Length; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(ICollection col) { if (m_count + col.Count >= m_array.Length) { EnsureCapacity(m_count + col.Count); } foreach(object item in col) { Add((Level)item); } return m_count; } /// <summary> /// Sets the capacity to the actual number of elements. /// </summary> public virtual void TrimToSize() { this.Capacity = m_count; } #endregion #region Implementation (helpers) /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="i"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i) { ValidateIndex(i, false); } /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="i"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i, bool allowEqualEnd) { int max = (allowEqualEnd) ? (m_count) : (m_count-1); if (i < 0 || i > max) { throw Ctrip.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); } } private void EnsureCapacity(int min) { int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); if (newCapacity < min) { newCapacity = min; } this.Capacity = newCapacity; } #endregion #region Implementation (ICollection) void ICollection.CopyTo(Array array, int start) { Array.Copy(m_array, 0, array, start, m_count); } #endregion #region Implementation (IList) object IList.this[int i] { get { return (object)this[i]; } set { this[i] = (Level)value; } } int IList.Add(object x) { return this.Add((Level)x); } bool IList.Contains(object x) { return this.Contains((Level)x); } int IList.IndexOf(object x) { return this.IndexOf((Level)x); } void IList.Insert(int pos, object x) { this.Insert(pos, (Level)x); } void IList.Remove(object x) { this.Remove((Level)x); } void IList.RemoveAt(int pos) { this.RemoveAt(pos); } #endregion #region Implementation (IEnumerable) IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(this.GetEnumerator()); } #endregion #region Nested enumerator class /// <summary> /// Supports simple iteration over a <see cref="LevelCollection"/>. /// </summary> private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator { #region Implementation (data) private readonly LevelCollection m_collection; private int m_index; private int m_version; #endregion #region Construction /// <summary> /// Initializes a new instance of the <c>Enumerator</c> class. /// </summary> /// <param name="tc"></param> internal Enumerator(LevelCollection tc) { m_collection = tc; m_index = -1; m_version = tc.m_version; } #endregion #region Operations (type-safe IEnumerator) /// <summary> /// Gets the current element in the collection. /// </summary> public Level Current { get { return m_collection[m_index]; } } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() { if (m_version != m_collection.m_version) { throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); } ++m_index; return (m_index < m_collection.Count); } /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> public void Reset() { m_index = -1; } #endregion #region Implementation (IEnumerator) object IEnumerator.Current { get { return this.Current; } } #endregion } #endregion #region Nested Read Only Wrapper class private sealed class ReadOnlyLevelCollection : LevelCollection { #region Implementation (data) private readonly LevelCollection m_collection; #endregion #region Construction internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default) { m_collection = list; } #endregion #region Type-safe ICollection public override void CopyTo(Level[] array) { m_collection.CopyTo(array); } public override void CopyTo(Level[] array, int start) { m_collection.CopyTo(array,start); } public override int Count { get { return m_collection.Count; } } public override bool IsSynchronized { get { return m_collection.IsSynchronized; } } public override object SyncRoot { get { return this.m_collection.SyncRoot; } } #endregion #region Type-safe IList public override Level this[int i] { get { return m_collection[i]; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int Add(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Clear() { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool Contains(Level x) { return m_collection.Contains(x); } public override int IndexOf(Level x) { return m_collection.IndexOf(x); } public override void Insert(int pos, Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Remove(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void RemoveAt(int pos) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool IsFixedSize { get { return true; } } public override bool IsReadOnly { get { return true; } } #endregion #region Type-safe IEnumerable public override ILevelCollectionEnumerator GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region Public Helpers // (just to mimic some nice features of ArrayList) public override int Capacity { get { return m_collection.Capacity; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int AddRange(LevelCollection x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override int AddRange(Level[] x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } #endregion } #endregion } }
namespace AngleSharp.Css.Tests.Styling { using AngleSharp.Css.Dom; using AngleSharp.Css.Parser; using AngleSharp.Css.Tests.Mocks; using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using AngleSharp.Io; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading.Tasks; using static CssConstructionFunctions; [TestFixture] public class HtmlCssIntegrationTests { [Test] public void DetectStylesheet() { var source = @"<!DOCTYPE html> <html> <head> <meta charset=""utf-8"" /> <title></title> <style> body { background-color: green !important; } </style> </head> <body> </body> </html>"; var doc = ParseDocument(source); Assert.AreEqual(1, doc.StyleSheets.Length); var css = doc.StyleSheets[0] as CssStyleSheet; Assert.AreEqual(1, css.Rules.Length); var style = css.Rules[0] as CssStyleRule; Assert.AreEqual("body", style.SelectorText); Assert.AreEqual(1, style.Style.Length); var decl = style.Style; Assert.IsInstanceOf<CssStyleDeclaration>(decl); var rule = decl.GetProperty("background-color"); Assert.IsTrue(rule.IsImportant); Assert.AreEqual("background-color", rule.Name); Assert.AreEqual(rule.Name, decl[0]); Assert.AreEqual("rgba(0, 128, 0, 1)", rule.Value); } [Test] public void ParsedCssCanHaveExtraWhitespace() { var source = "<div style=\"background-color: http://www.codeplex.com?url=<!--[if gte IE 4]><SCRIPT>alert('XSS');</SCRIPT><![endif]-->\">"; var doc = ParseDocument(source, new CssParserOptions { IsIncludingUnknownDeclarations = true, IsIncludingUnknownRules = true }); var div = doc.QuerySelector<IHtmlElement>("div"); Assert.AreEqual("", div.GetStyle()["background-color"]); Assert.AreEqual("", div.GetStyle().CssText); } [Test] public async Task CssWithImportRuleShouldBeAbleToHandleNestedStylesheets() { var files = new Dictionary<String, String> { { "index.html", "<!doctype html><html><link rel=stylesheet href=origin.css type=text/css><style>@import url('linked2.css');</style>" }, { "origin.css", "@import url(linked1.css);" }, { "linked1.css", "" }, { "linked2.css", "@import url(\"linked3.css\"); @import 'linked4.css';" }, { "linked3.css", "" }, { "linked4.css", "" }, }; var requester = new TestServerRequester(files); var config = Configuration.Default .With(requester) .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) .WithCss(); var document = await BrowsingContext.New(config).OpenAsync("http://localhost/index.html"); var link = document.QuerySelector<IHtmlLinkElement>("link"); var style = document.QuerySelector<IHtmlStyleElement>("style"); await Task.Delay(100); Assert.IsNotNull(link); Assert.IsNotNull(style); var origin = link.Sheet as ICssStyleSheet; Assert.IsNotNull(origin); Assert.AreEqual("http://localhost/origin.css", origin.Href); Assert.AreEqual(1, origin.Rules.Length); Assert.AreEqual(CssRuleType.Import, origin.Rules[0].Type); var linked1 = (origin.Rules[0] as ICssImportRule).Sheet; Assert.IsNotNull(linked1); Assert.AreEqual("http://localhost/linked1.css", linked1.Href); Assert.AreEqual(0, linked1.Rules.Length); var styleSheet = style.Sheet as ICssStyleSheet; Assert.IsNotNull(styleSheet); Assert.AreEqual(null, styleSheet.Href); Assert.AreEqual(1, styleSheet.Rules.Length); Assert.AreEqual(CssRuleType.Import, styleSheet.Rules[0].Type); var linked2 = (styleSheet.Rules[0] as ICssImportRule).Sheet; Assert.IsNotNull(linked2); Assert.AreEqual("http://localhost/linked2.css", linked2.Href); Assert.AreEqual(2, linked2.Rules.Length); Assert.AreEqual(CssRuleType.Import, linked2.Rules[0].Type); Assert.AreEqual(CssRuleType.Import, linked2.Rules[1].Type); var linked3 = (linked2.Rules[0] as ICssImportRule).Sheet; Assert.IsNotNull(linked3); Assert.AreEqual("http://localhost/linked3.css", linked3.Href); Assert.AreEqual(0, linked3.Rules.Length); var linked4 = (linked2.Rules[1] as ICssImportRule).Sheet; Assert.IsNotNull(linked4); Assert.AreEqual("http://localhost/linked4.css", linked4.Href); Assert.AreEqual(0, linked4.Rules.Length); } [Test] public async Task CssWithImportRuleShouldStopRecursion() { var files = new Dictionary<String, String> { { "index.html", "<!doctype html><html><link rel=stylesheet href=origin.css type=text/css>" }, { "origin.css", "@import url(linked.css);" }, { "linked.css", "@import url(origin.css);" }, }; var requester = new TestServerRequester(files); var config = Configuration.Default .With(requester) .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) .WithCss(); var document = await BrowsingContext.New(config).OpenAsync("http://localhost/index.html"); var link = document.QuerySelector<IHtmlLinkElement>("link"); await Task.Delay(100); Assert.IsNotNull(link); var origin = link.Sheet as ICssStyleSheet; Assert.IsNotNull(origin); Assert.AreEqual("http://localhost/origin.css", origin.Href); Assert.AreEqual(1, origin.Rules.Length); Assert.AreEqual(CssRuleType.Import, origin.Rules[0].Type); var linked = (origin.Rules[0] as ICssImportRule).Sheet; Assert.IsNotNull(linked); Assert.AreEqual("http://localhost/linked.css", linked.Href); Assert.AreEqual(1, linked.Rules.Length); var originAborted = (linked.Rules[0] as ICssImportRule).Sheet; Assert.IsNull(originAborted); } [Test] public async Task StylePropertyOfElementFromDocumentWithCssShouldNotBeNull() { var config = Configuration.Default.WithCss(); var document = await BrowsingContext.New(config).OpenNewAsync(); var div = document.CreateElement<IHtmlDivElement>(); Assert.IsNotNull(div.GetStyle()); } [Test] public async Task StylePropertyOfClonedElementShouldNotBeNull() { var config = Configuration.Default.WithCss(); var document = await BrowsingContext.New(config).OpenNewAsync(); var div = document.CreateElement<IHtmlDivElement>(); var clone = div.Clone(true) as IHtmlDivElement; Assert.IsNotNull(clone); Assert.IsNotNull(clone.GetStyle()); } [Test] public void TableWithTableRowThatHasStyle() { var doc = ParseDocument(@"<table><tr style=""display: none;"">"); var dochtml0 = doc.ChildNodes[0] as IElement; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, dochtml0.Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0] as IElement; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, dochtml0head0.Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1] as IElement; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, dochtml0body1.Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1table0 = dochtml0body1.ChildNodes[0] as IElement; Assert.AreEqual(1, dochtml0body1table0.ChildNodes.Length); Assert.AreEqual(0, dochtml0body1table0.Attributes.Length); Assert.AreEqual("table", dochtml0body1table0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1table0.NodeType); var dochtml0body1table0tbody0 = dochtml0body1table0.ChildNodes[0] as IElement; Assert.AreEqual(1, dochtml0body1table0tbody0.ChildNodes.Length); Assert.AreEqual(0, dochtml0body1table0tbody0.Attributes.Length); Assert.AreEqual("tbody", dochtml0body1table0tbody0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1table0tbody0.NodeType); var dochtml0body1table0tbody0tr0 = dochtml0body1table0tbody0.ChildNodes[0] as IElement; Assert.AreEqual(0, dochtml0body1table0tbody0tr0.ChildNodes.Length); Assert.AreEqual(1, dochtml0body1table0tbody0tr0.Attributes.Length); Assert.AreEqual("tr", dochtml0body1table0tbody0tr0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1table0tbody0tr0.NodeType); var styleAttribute = dochtml0body1table0tbody0tr0.Attributes[0]; Assert.AreEqual("style", styleAttribute.Name); Assert.AreEqual("display: none;", styleAttribute.Value); var style = ((IHtmlElement)dochtml0body1table0tbody0tr0).GetStyle(); Assert.AreEqual("none", style.GetDisplay()); } [Test] public void TableWithTableRowThatHasStyleAndChanged() { var doc = ParseDocument(@"<table><tr style=""display: none;"">"); var html = doc.ChildNodes[0] as IElement; Assert.AreEqual(2, html.ChildNodes.Length); Assert.AreEqual(0, html.Attributes.Length); Assert.AreEqual("html", html.GetTagName()); Assert.AreEqual(NodeType.Element, html.NodeType); var body = html.ChildNodes[1] as IElement; Assert.AreEqual(1, body.ChildNodes.Length); Assert.AreEqual(0, body.Attributes.Length); Assert.AreEqual("body", body.GetTagName()); Assert.AreEqual(NodeType.Element, body.NodeType); var table = body.ChildNodes[0] as IElement; Assert.AreEqual(1, table.ChildNodes.Length); Assert.AreEqual(0, table.Attributes.Length); Assert.AreEqual("table", table.GetTagName()); Assert.AreEqual(NodeType.Element, table.NodeType); var tableBody = table.ChildNodes[0] as IElement; Assert.AreEqual(1, tableBody.ChildNodes.Length); Assert.AreEqual(0, tableBody.Attributes.Length); Assert.AreEqual("tbody", tableBody.GetTagName()); Assert.AreEqual(NodeType.Element, tableBody.NodeType); var tableRow = tableBody.ChildNodes[0] as IElement; Assert.AreEqual(0, tableRow.ChildNodes.Length); Assert.AreEqual(1, tableRow.Attributes.Length); Assert.AreEqual("tr", tableRow.GetTagName()); Assert.AreEqual(NodeType.Element, tableRow.NodeType); var tr = (IHtmlElement)tableRow; var style = tr.GetStyle(); Assert.AreEqual("none", style.GetDisplay()); style.SetDisplay("block"); Assert.AreEqual("block", style.GetDisplay()); } [Test] public void TableWithTableRowThatHasNoStyleAndChanged() { var doc = ParseDocument(@"<table><tr>"); var html = doc.ChildNodes[0] as IElement; Assert.AreEqual(2, html.ChildNodes.Length); Assert.AreEqual(0, html.Attributes.Length); Assert.AreEqual("html", html.GetTagName()); Assert.AreEqual(NodeType.Element, html.NodeType); var body = html.ChildNodes[1] as IElement; Assert.AreEqual(1, body.ChildNodes.Length); Assert.AreEqual(0, body.Attributes.Length); Assert.AreEqual("body", body.GetTagName()); Assert.AreEqual(NodeType.Element, body.NodeType); var table = body.ChildNodes[0] as IElement; Assert.AreEqual(1, table.ChildNodes.Length); Assert.AreEqual(0, table.Attributes.Length); Assert.AreEqual("table", table.GetTagName()); Assert.AreEqual(NodeType.Element, table.NodeType); var tableBody = table.ChildNodes[0] as IElement; Assert.AreEqual(1, tableBody.ChildNodes.Length); Assert.AreEqual(0, tableBody.Attributes.Length); Assert.AreEqual("tbody", tableBody.GetTagName()); Assert.AreEqual(NodeType.Element, tableBody.NodeType); var tableRow = tableBody.ChildNodes[0] as IElement; Assert.AreEqual(0, tableRow.ChildNodes.Length); Assert.AreEqual(0, tableRow.Attributes.Length); Assert.AreEqual("tr", tableRow.GetTagName()); Assert.AreEqual(NodeType.Element, tableRow.NodeType); var tr = (IHtmlElement)tableRow; var style = tr.GetStyle(); style.SetDisplay("none"); Assert.AreEqual("none", style.GetDisplay()); } [Test] public void SetStyleAttributeAfterPageLoadWithInvalidColor() { var source = "<Div style=\"background-color: http://www.codeplex.com?url=<SCRIPT>a=/XSS/alert(a.source)</SCRIPT>\">"; var document = ParseDocument(source); var div = (IHtmlElement)document.QuerySelector("div"); var n = div.GetStyle().Length; // hang occurs only if this line is executed prior to setting the attribute // hang occurs when executing next line div.SetAttribute("style", "background-color: http://www.codeplex.com?url=&lt;SCRIPT&gt;a=/XSS/alert(a.source)&lt;/SCRIPT&gt;"); Assert.AreEqual("", div.GetStyle().GetBackgroundColor()); } [Test] public void ExtensionCssWithOneElement() { var document = ParseDocument("<ul><li>First element"); var elements = document.QuerySelectorAll("li").Css("color", "red"); Assert.AreEqual(1, elements.Length); var style = (elements[0] as IHtmlElement).GetStyle(); Assert.AreEqual(1, style.Length); Assert.AreEqual("color", style[0]); Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetColor()); } [Test] public void ExtensionCssWithOneElementButMultipleCssRules() { var document = ParseDocument("<ul><li>First element"); var elements = document.QuerySelectorAll("li").Css(new { color = "red", background = "green", font = "10px 'Tahoma'", opacity = "0.5" }); Assert.AreEqual(1, elements.Length); var style = (elements[0] as IHtmlElement).GetStyle(); Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetColor()); Assert.AreEqual("rgba(0, 128, 0, 1)", style.GetBackgroundColor()); Assert.AreEqual("\"Tahoma\"", style.GetFontFamily()); Assert.AreEqual("10px", style.GetFontSize()); Assert.AreEqual("0.5", style.GetOpacity()); } [Test] public void ExtensionCssWithMultipleElements() { var document = ParseDocument("<ul><li>First element<li>Second element<li>third<li style='background-color:blue'>Last"); var elements = document.QuerySelectorAll("li").Css("color", "red"); Assert.AreEqual(4, elements.Length); var style1 = (elements[0] as IHtmlElement).GetStyle(); Assert.AreEqual(1, style1.Length); var test1 = style1[0]; Assert.AreEqual("color", test1); Assert.AreEqual("rgba(255, 0, 0, 1)", style1.GetPropertyValue(test1)); var style2 = (elements[1] as IHtmlElement).GetStyle(); Assert.AreEqual(1, style2.Length); var test2 = style2[0]; Assert.AreEqual("color", test2); Assert.AreEqual("rgba(255, 0, 0, 1)", style2.GetPropertyValue(test2)); var style3 = (elements[2] as IHtmlElement).GetStyle(); Assert.AreEqual(1, style3.Length); var test3 = style3[0]; Assert.AreEqual("color", test3); Assert.AreEqual("rgba(255, 0, 0, 1)", style3.GetPropertyValue(test3)); var style4 = (elements[3] as IHtmlElement).GetStyle(); Assert.AreEqual(2, style4.Length); var background = style4[0]; Assert.AreEqual("background-color", background); Assert.AreEqual("rgba(0, 0, 255, 1)", style4.GetPropertyValue(background)); var color = style4[1]; Assert.AreEqual("color", color); Assert.AreEqual("rgba(255, 0, 0, 1)", style4.GetPropertyValue(color)); } [Test] public void Background0ShouldSerializeCorrectly_Issue14() { var dom = ParseDocument(@"<html><body><div style=""background: 0;"">Test</div></body></html>"); var div = dom.QuerySelector("div"); var style = div.GetStyle(); Assert.AreEqual("background: left", style.CssText); } [Test] public void RemovingPropertiesShouldNotYieldEmptyStyle_Issue14() { var dom = ParseDocument(@"<html><body><div style=""background: 0;"">Test</div></body></html>"); var div = dom.QuerySelector("div"); var style = div.GetStyle(); style.RemoveProperty("background-position-x"); style.RemoveProperty("background-position-y"); Assert.AreEqual("background-image: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: initial", style.CssText); } [Test] public void RecombinationWorksWithBorder_Issue16() { var expected = "<button style=\"pointer-events: auto; border: 1px solid rgba(0, 0, 0, 1)\"></button>"; var document = ParseDocument(""); var element = document.CreateElement("button"); element.GetStyle().SetPointerEvents("auto"); element.GetStyle().SetBorderWidth("1px"); element.GetStyle().SetBorderStyle("solid"); element.GetStyle().SetBorderColor("black"); Assert.AreEqual(expected, element.ToHtml()); } [Test] public void DefaultStyleSheetTest_Issue21() { var browsingContext = BrowsingContext.New(Configuration.Default.WithCss()); var htmlParser = browsingContext.GetService<IHtmlParser>(); var document = htmlParser.ParseDocument("<html><body><b>Hello, World!</b></body></html>"); var boldStyle = document.Body.FirstElementChild.ComputeCurrentStyle(); Assert.AreEqual("bolder", boldStyle.GetFontWeight()); } [Test] public void MediaRuleCssCausesException_Issue20() { var browsingContext = BrowsingContext.New(Configuration.Default.WithCss()); var htmlParser = browsingContext.GetService<IHtmlParser>(); var document = htmlParser.ParseDocument("<html><head><style>@media screen { }</style></head><body></body></html>"); var style = document.Body.ComputeCurrentStyle(); Assert.IsNotNull(style); } [Test] public void MediaRuleIsCalculatedIfScreenIsOkay() { var config = Configuration.Default .WithCss() .WithRenderDevice(new DefaultRenderDevice { ViewPortWidth = 1000, }); var browsingContext = BrowsingContext.New(config); var htmlParser = browsingContext.GetService<IHtmlParser>(); var document = htmlParser.ParseDocument("<html><head><style>body { color: red } @media only screen and (min-width: 600px) { body { color: green } }</style></head><body></body></html>"); var style = document.Body.ComputeCurrentStyle(); Assert.AreEqual("rgba(0, 128, 0, 1)", style.GetColor()); } [Test] public void MediaRuleIsNotCalculatedIfScreenIsNotWideEnough() { var config = Configuration.Default .WithCss() .WithRenderDevice(new DefaultRenderDevice { ViewPortWidth = 599, }); var browsingContext = BrowsingContext.New(config); var htmlParser = browsingContext.GetService<IHtmlParser>(); var document = htmlParser.ParseDocument("<html><head><style>body { color: red } @media only screen and (min-width: 600px) { body { color: green } }</style></head><body></body></html>"); var style = document.Body.ComputeCurrentStyle(); Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetColor()); } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using MindTouch.Dream; namespace MindTouch.Web { /// <summary> /// Provides a hierarchical <see cref="DreamCookie"/> container. /// </summary> public class DreamCookieJar { //--- Fields --- private List<DreamCookie> _cookies; private Dictionary<string, DreamCookieJar> _jars; //--- Properties --- /// <summary> /// Total cookies in the jar. /// </summary> public int Count { get { int result = 0; if(_jars != null) { foreach(DreamCookieJar jar in _jars.Values) { result += jar.Count; } } if(_cookies != null) { result += _cookies.Count; } return result; } } /// <summary> /// <see langword="True"/> if there are no cookies in the jar. /// </summary> public bool IsEmpty { get { return ((_jars == null) || (_jars.Count == 0)) && ((_cookies == null) || (_cookies.Count == 0)); } } //--- Methods --- /// <summary> /// Clear all cookies from the jar. /// </summary> public void Clear() { _cookies = null; _jars = null; } /// <summary> /// Update the jar with a cookie. /// </summary> /// <param name="cookie">Cookie to store.</param> /// <param name="uri">Uri this cookie applies to.</param> public void Update(DreamCookie cookie, XUri uri) { List<DreamCookie> list = new List<DreamCookie>(); list.Add(cookie); Update(list, uri); } /// <summary> /// Update the jar with a collection cookies. /// </summary> /// <param name="collection">List of cookies to store.</param> /// <param name="uri">Uri cookies apply to.</param> public void Update(List<DreamCookie> collection, XUri uri) { if(collection == null) { throw new ArgumentNullException("collection"); } // process all cookies foreach(DreamCookie c in collection) { DreamCookie cookie = c; if(!string.IsNullOrEmpty(cookie.Name)) { string[] segments = null; if(uri != null) { // set default domain if needed if(string.IsNullOrEmpty(cookie.Domain)) { cookie = cookie.WithHostPort(uri.HostPort); } else if(!StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, uri.HostPort)) { // domain doesn't match, ignore cookie continue; } // set default path if needed if(string.IsNullOrEmpty(cookie.Path)) { cookie = cookie.WithPath(uri.Path); segments = uri.Segments; } else { segments = cookie.Uri == null ? new string[0] : cookie.Uri.Segments; if(!uri.PathStartsWith(segments)) { // path doesn't match ignore cookie continue; } } } if(!string.IsNullOrEmpty(cookie.Path) && !string.IsNullOrEmpty(cookie.Domain)) { if(segments == null) { segments = cookie.Uri == null ? new string[0] : cookie.Uri.Segments; } if(cookie.Expired) { Delete(cookie, segments, 0); } else { Insert(cookie, segments, 0); } } } } } /// <summary> /// Retrieve all cookies that apply to a Uri. /// </summary> /// <param name="uri">Uri to match.</param> /// <returns>List of cookies.</returns> public List<DreamCookie> Fetch(XUri uri) { if(uri == null) { throw new ArgumentNullException("uri"); } List<DreamCookie> result = new List<DreamCookie>(); Fetch(uri, 0, result); XUri localUri = uri.AsLocalUri(); if(localUri != uri) { Fetch(localUri, 0, result); } return result; } private void Insert(DreamCookie updatedCookie, string[] segments, int depth) { // find leaf node if(depth < segments.Length) { if(_jars == null) { _jars = new Dictionary<string, DreamCookieJar>(StringComparer.OrdinalIgnoreCase); } DreamCookieJar subjar; if(!_jars.TryGetValue(segments[depth], out subjar)) { subjar = new DreamCookieJar(); _jars.Add(segments[depth], subjar); } subjar.Insert(updatedCookie, segments, depth + 1); } else { if(_cookies == null) { _cookies = new List<DreamCookie>(); } List<DreamCookie> expired = new List<DreamCookie>(); for(int i = 0; i < _cookies.Count; ++i) { DreamCookie cookie = _cookies[i]; // check if cookie is expired; if so, remove it if(cookie.Expired) { expired.Add(cookie); continue; } // TODO (steveb): we need to add support for '.' prefixes on the domain name // check if cookie matches the expired cookie if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, updatedCookie.Domain) && StringUtil.EqualsInvariantIgnoreCase(cookie.Name, updatedCookie.Name) && (cookie.Secure == updatedCookie.Secure)) { _cookies[i] = updatedCookie; return; } } foreach(DreamCookie cookie in expired) { _cookies.Remove(cookie); } _cookies.Add(updatedCookie); } } private void Delete(DreamCookie expiredCookie, string[] segments, int depth) { // find leaf node if(depth < segments.Length) { if(_jars != null) { DreamCookieJar subjar; if(_jars.TryGetValue(segments[depth], out subjar)) { subjar.Delete(expiredCookie, segments, depth + 1); if(subjar.IsEmpty) { _jars.Remove(segments[depth]); } } } } else if(_cookies != null) { List<DreamCookie> expired = new List<DreamCookie>(); foreach(DreamCookie cookie in _cookies) { // check if cookie is expired; if so, remove it if(cookie.Expired) { expired.Add(cookie); continue; } // TODO (steveb): we need to add support for '.' prefixes on the domain name // check if cookie matches the expired cookie if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, expiredCookie.Domain) && StringUtil.EqualsInvariantIgnoreCase(cookie.Name, expiredCookie.Name) && (cookie.Secure == expiredCookie.Secure)) { expired.Add(cookie); continue; } } foreach(DreamCookie cookie in expired) { _cookies.Remove(cookie); } } } private void Fetch(XUri uri, int depth, List<DreamCookie> result) { // if available, fetch cookies from deeper in the path if((depth < uri.Segments.Length) && (_jars != null)) { DreamCookieJar subjar; if(_jars.TryGetValue(uri.Segments[depth], out subjar)) { subjar.Fetch(uri, depth + 1, result); } } // collect all cookies that are valid and apply to this uri if(_cookies != null) { List<DreamCookie> expired = new List<DreamCookie>(); foreach(DreamCookie cookie in _cookies) { // check if cookie is expired; if so, remove it if(cookie.Expired) { expired.Add(cookie); continue; } // TODO (steveb): we need to add support for '.' prefixes on the domain name // check if cookie matches the host and uri if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, uri.HostPort) && (!cookie.Secure || (cookie.Secure && StringUtil.EqualsInvariantIgnoreCase(uri.Scheme, "https")))) { result.Add(cookie); } } foreach(DreamCookie cookie in expired) { _cookies.Remove(cookie); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; // levels of nesting = 20 class Class1 { private static TestUtil.TestLog testLog; static Class1() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine("in main try"); expectedOut.WriteLine("in foo i = 0"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("in foo i = 1"); expectedOut.WriteLine("-in foo try"); expectedOut.WriteLine("--in foo try"); expectedOut.WriteLine("---in foo try"); expectedOut.WriteLine("----in foo try"); expectedOut.WriteLine("-----in foo try"); expectedOut.WriteLine("------in foo try"); expectedOut.WriteLine("-------in foo try"); expectedOut.WriteLine("--------in foo try"); expectedOut.WriteLine("---------in foo try"); expectedOut.WriteLine("----------in foo try"); expectedOut.WriteLine("-----------in foo try"); expectedOut.WriteLine("------------in foo try"); expectedOut.WriteLine("-------------in foo try"); expectedOut.WriteLine("--------------in foo try"); expectedOut.WriteLine("---------------in foo try"); expectedOut.WriteLine("----------------in foo try"); expectedOut.WriteLine("-----------------in foo try"); expectedOut.WriteLine("------------------in foo try"); expectedOut.WriteLine("-------------------in foo try"); expectedOut.WriteLine("--------------------in foo try"); expectedOut.WriteLine("--------------------in foo finally"); expectedOut.WriteLine("-------------------in foo catch"); expectedOut.WriteLine("-------------------in foo finally"); expectedOut.WriteLine("------------------in foo catch"); expectedOut.WriteLine("------------------in foo finally"); expectedOut.WriteLine("-----------------in foo catch"); expectedOut.WriteLine("-----------------in foo finally"); expectedOut.WriteLine("----------------in foo catch"); expectedOut.WriteLine("----------------in foo finally"); expectedOut.WriteLine("---------------in foo catch"); expectedOut.WriteLine("---------------in foo finally"); expectedOut.WriteLine("--------------in foo catch"); expectedOut.WriteLine("--------------in foo finally"); expectedOut.WriteLine("-------------in foo catch"); expectedOut.WriteLine("-------------in foo finally"); expectedOut.WriteLine("------------in foo catch"); expectedOut.WriteLine("------------in foo finally"); expectedOut.WriteLine("-----------in foo catch"); expectedOut.WriteLine("-----------in foo finally"); expectedOut.WriteLine("----------in foo catch"); expectedOut.WriteLine("----------in foo finally"); expectedOut.WriteLine("---------in foo catch"); expectedOut.WriteLine("---------in foo finally"); expectedOut.WriteLine("--------in foo catch"); expectedOut.WriteLine("--------in foo finally"); expectedOut.WriteLine("-------in foo catch"); expectedOut.WriteLine("-------in foo finally"); expectedOut.WriteLine("------in foo catch"); expectedOut.WriteLine("------in foo finally"); expectedOut.WriteLine("-----in foo catch"); expectedOut.WriteLine("-----in foo finally"); expectedOut.WriteLine("----in foo catch"); expectedOut.WriteLine("----in foo finally"); expectedOut.WriteLine("---in foo catch"); expectedOut.WriteLine("---in foo finally"); expectedOut.WriteLine("--in foo catch"); expectedOut.WriteLine("--in foo finally"); expectedOut.WriteLine("-in foo catch"); expectedOut.WriteLine("-in foo finally"); expectedOut.WriteLine("in main catch"); // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } static public void foo(int i) { if (i > 1) return; Console.WriteLine("in foo i = {0}", i); int j = 0; int k = 0; try { Console.WriteLine("-in foo try"); try { Console.WriteLine("--in foo try"); try { Console.WriteLine("---in foo try"); try { Console.WriteLine("----in foo try"); try { Console.WriteLine("-----in foo try"); try { Console.WriteLine("------in foo try"); try { Console.WriteLine("-------in foo try"); try { Console.WriteLine("--------in foo try"); try { Console.WriteLine("---------in foo try"); try { Console.WriteLine("----------in foo try"); try { Console.WriteLine("-----------in foo try"); try { Console.WriteLine("------------in foo try"); try { Console.WriteLine("-------------in foo try"); try { Console.WriteLine("--------------in foo try"); try { Console.WriteLine("---------------in foo try"); try { Console.WriteLine("----------------in foo try"); try { Console.WriteLine("-----------------in foo try"); try { Console.WriteLine("------------------in foo try"); try { Console.WriteLine("-------------------in foo try"); try { Console.WriteLine("--------------------in foo try"); goto L20; } catch { Console.WriteLine("--------------------in foo catch"); } finally { Console.WriteLine("--------------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L20: goto L19; } catch { Console.WriteLine("-------------------in foo catch"); } finally { Console.WriteLine("-------------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L19: goto L18; } catch { Console.WriteLine("------------------in foo catch"); } finally { Console.WriteLine("------------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L18: goto L17; } catch { Console.WriteLine("-----------------in foo catch"); } finally { Console.WriteLine("-----------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L17: goto L16; } catch { Console.WriteLine("----------------in foo catch"); } finally { Console.WriteLine("----------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L16: goto L15; } catch { Console.WriteLine("---------------in foo catch"); } finally { Console.WriteLine("---------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L15: goto L14; } catch { Console.WriteLine("--------------in foo catch"); } finally { Console.WriteLine("--------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L14: goto L13; } catch { Console.WriteLine("-------------in foo catch"); } finally { Console.WriteLine("-------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L13: goto L12; } catch { Console.WriteLine("------------in foo catch"); } finally { Console.WriteLine("------------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L12: goto L11; } catch { Console.WriteLine("-----------in foo catch"); } finally { Console.WriteLine("-----------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L11: goto L10; } catch { Console.WriteLine("----------in foo catch"); } finally { Console.WriteLine("----------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L10: goto L9; } catch { Console.WriteLine("---------in foo catch"); } finally { Console.WriteLine("---------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L9: goto L8; } catch { Console.WriteLine("--------in foo catch"); } finally { Console.WriteLine("--------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L8: goto L7; } catch { Console.WriteLine("-------in foo catch"); } finally { Console.WriteLine("-------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L7: goto L6; } catch { Console.WriteLine("------in foo catch"); } finally { Console.WriteLine("------in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L6: goto L5; } catch { Console.WriteLine("-----in foo catch"); } finally { Console.WriteLine("-----in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L5: goto L4; } catch { Console.WriteLine("----in foo catch"); } finally { Console.WriteLine("----in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L4: goto L3; } catch { Console.WriteLine("---in foo catch"); } finally { Console.WriteLine("---in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L3: goto L2; } catch { Console.WriteLine("--in foo catch"); } finally { Console.WriteLine("--in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L2: goto L1; } catch { Console.WriteLine("-in foo catch"); } finally { Console.WriteLine("-in foo finally"); foo(i + 1); j = 1 / i; k = 1 / (j - 1); } L1: foo(i + 1); } static public int Main(string[] args) { //Start recording testLog.StartRecording(); int i = Environment.TickCount != 0 ? 0 : 1; try { Console.WriteLine("in main try"); foo(i); } catch { Console.WriteLine("in main catch"); } //Stop recording testLog.StopRecording(); return testLog.VerifyOutput(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebFrontEnd.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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 Microsoft.XmlSerializer.Generator { using System; using System.IO; using System.Collections; using System.ComponentModel; using System.Threading; using System.Reflection; using System.Security; using System.Globalization; using System.Xml; using System.Xml.Serialization; internal class XmlSerializationCodeGen { private IndentedWriter _writer; private int _nextMethodNumber = 0; private Hashtable _methodNames = new Hashtable(); private ReflectionAwareCodeGen _raCodeGen; private TypeScope[] _scopes; private TypeDesc _stringTypeDesc = null; private TypeDesc _qnameTypeDesc = null; private string _access; private string _className; private TypeMapping[] _referencedMethods; private int _references = 0; private Hashtable _generatedMethods = new Hashtable(); internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { _writer = writer; _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareCodeGen(writer); _className = className; _access = access; } internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Hashtable MethodNames { get { return _methodNames; } } internal Hashtable GeneratedMethods { get { return _generatedMethods; } } internal virtual void GenerateMethod(TypeMapping mapping) { } internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods[--_references]; GenerateMethod(mapping); } } internal string ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } } return (string)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, b, index); return b; } internal void WriteQuotedCSharpString(string value) { _raCodeGen.WriteQuotedCSharpString(value); } internal void GenerateHashtableGetBegin(string privateName, string publicName) { _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(privateName); _writer.WriteLine(" = null;"); _writer.Write("public override "); _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(publicName); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine("get {"); _writer.Indent++; _writer.Write("if ("); _writer.Write(privateName); _writer.WriteLine(" == null) {"); _writer.Indent++; _writer.Write(typeof(Hashtable).FullName); _writer.Write(" _tmp = new "); _writer.Write(typeof(Hashtable).FullName); _writer.WriteLine("();"); } internal void GenerateHashtableGetEnd(string privateName) { _writer.Write("if ("); _writer.Write(privateName); _writer.Write(" == null) "); _writer.Write(privateName); _writer.WriteLine(" = _tmp;"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("return "); _writer.Write(privateName); _writer.WriteLine(";"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); } internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; _writer.Write("_tmp["); WriteQuotedCSharpString(xmlMappings[i].Key); _writer.Write("] = "); WriteQuotedCSharpString(methods[i]); _writer.WriteLine(";"); } } GenerateHashtableGetEnd(privateName); } internal void GenerateSupportedTypes(Type[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanSerialize("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (uniqueTypes[type] != null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; uniqueTypes[type] = type; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.WriteLine(")) return true;"); } _writer.WriteLine("return false;"); _writer.Indent--; _writer.WriteLine("}"); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return baseSerializer; } internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); _writer.WriteLine(); _writer.Write("public sealed class "); _writer.Write(CodeIdentifier.GetCSharpName(serializerName)); _writer.Write(" : "); _writer.Write(baseSerializer); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine(); _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanDeserialize("); _writer.Write(typeof(XmlReader).FullName); _writer.WriteLine(" xmlReader) {"); _writer.Indent++; if (mapping.Accessor.Any) { _writer.WriteLine("return true;"); } else { _writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); _writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); _writer.WriteLine(");"); } _writer.Indent--; _writer.WriteLine("}"); if (writeMethod != null) { _writer.WriteLine(); _writer.Write("protected override void Serialize(object objectToSerialize, "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" writer) {"); _writer.Indent++; _writer.Write("(("); _writer.Write(writerClass); _writer.Write(")writer)."); _writer.Write(writeMethod); _writer.Write("("); if (mapping is XmlMembersMapping) { _writer.Write("(object[])"); } _writer.WriteLine("objectToSerialize);"); _writer.Indent--; _writer.WriteLine("}"); } if (readMethod != null) { _writer.WriteLine(); _writer.Write("protected override object Deserialize("); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" reader) {"); _writer.Indent++; _writer.Write("return (("); _writer.Write(readerClass); _writer.Write(")reader)."); _writer.Write(readMethod); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); } _writer.Indent--; _writer.WriteLine("}"); return serializerName; } private void GenerateTypedSerializers(Hashtable serializers) { string privateName = "typedSerializers"; GenerateHashtableGetBegin(privateName, "TypedSerializers"); foreach (string key in serializers.Keys) { _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); _writer.Write((string)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) { _writer.Write("public override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.Write(" GetSerializer("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); _writer.Write((string)serializers[xmlMappings[i].Key]); _writer.WriteLine("();"); } } _writer.WriteLine("return null;"); _writer.Indent--; _writer.WriteLine("}"); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.Write(" Reader { get { return new "); _writer.Write(readerType); _writer.WriteLine("(); } }"); _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.Write(" Writer { get { return new "); _writer.Write(writerType); _writer.WriteLine("(); } }"); GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings); GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings); GenerateTypedSerializers(serializers); GenerateSupportedTypes(types); GenerateGetSerializer(serializers, xmlMappings); _writer.Indent--; _writer.WriteLine("}"); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc.CanBeElementValue; } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Subnet /// </summary> [XmlRootAttribute(IsNullable = false)] public class Subnet { private string subnetIdField; private string subnetStateField; private string vpcIdField; private string cidrBlockField; private Decimal? availableIpAddressCountField; private string availabilityZoneField; private bool? defaultForAzField; private bool? mapPublicIpOnLaunchField; private List<Tag> tagField; /// <summary> /// The subnet's ID /// </summary> [XmlElementAttribute(ElementName = "SubnetId")] public string SubnetId { get { return this.subnetIdField; } set { this.subnetIdField = value; } } /// <summary> /// Sets the subnet's ID /// </summary> /// <param name="subnetId">The subnet's ID</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithSubnetId(string subnetId) { this.subnetIdField = subnetId; return this; } /// <summary> /// Checks if SubnetId property is set /// </summary> /// <returns>true if SubnetId property is set</returns> public bool IsSetSubnetId() { return this.subnetIdField != null; } /// <summary> /// The current state of the subnet (pending or available). /// </summary> [XmlElementAttribute(ElementName = "SubnetState")] public string SubnetState { get { return this.subnetStateField; } set { this.subnetStateField = value; } } /// <summary> /// Sets the current state of the subnet (pending or available). /// </summary> /// <param name="subnetState">The current state of the subnet (pending or /// available).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithSubnetState(string subnetState) { this.subnetStateField = subnetState; return this; } /// <summary> /// Checks if SubnetState property is set /// </summary> /// <returns>true if SubnetState property is set</returns> public bool IsSetSubnetState() { return this.subnetStateField != null; } /// <summary> /// The ID of the VPC the subnet is in /// </summary> [XmlElementAttribute(ElementName = "VpcId")] public string VpcId { get { return this.vpcIdField; } set { this.vpcIdField = value; } } /// <summary> /// Sets the ID of the VPC the subnet is in /// </summary> /// <param name="vpcId">The ID of the VPC the subnet is in</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithVpcId(string vpcId) { this.vpcIdField = vpcId; return this; } /// <summary> /// Checks if VpcId property is set /// </summary> /// <returns>true if VpcId property is set</returns> public bool IsSetVpcId() { return this.vpcIdField != null; } /// <summary> /// The CIDR block assigned to the subnet /// </summary> [XmlElementAttribute(ElementName = "CidrBlock")] public string CidrBlock { get { return this.cidrBlockField; } set { this.cidrBlockField = value; } } /// <summary> /// Sets the CIDR block assigned to the subnet /// </summary> /// <param name="cidrBlock">The CIDR block assigned to the subnet</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithCidrBlock(string cidrBlock) { this.cidrBlockField = cidrBlock; return this; } /// <summary> /// Checks if CidrBlock property is set /// </summary> /// <returns>true if CidrBlock property is set</returns> public bool IsSetCidrBlock() { return this.cidrBlockField != null; } /// <summary> /// The number of unused IP addresses in the subnet. /// </summary> [XmlElementAttribute(ElementName = "AvailableIpAddressCount")] public Decimal AvailableIpAddressCount { get { return this.availableIpAddressCountField.GetValueOrDefault(); } set { this.availableIpAddressCountField = value; } } /// <summary> /// Sets the number of unused IP addresses in the subnet. /// </summary> /// <param name="availableIpAddressCount">The number of unused IP addresses in the /// subnet.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithAvailableIpAddressCount(Decimal availableIpAddressCount) { this.availableIpAddressCountField = availableIpAddressCount; return this; } /// <summary> /// Checks if AvailableIpAddressCount property is set /// </summary> /// <returns>true if AvailableIpAddressCount property is set</returns> public bool IsSetAvailableIpAddressCount() { return this.availableIpAddressCountField.HasValue; } /// <summary> /// The Availability Zone the subnet is in. /// </summary> [XmlElementAttribute(ElementName = "AvailabilityZone")] public string AvailabilityZone { get { return this.availabilityZoneField; } set { this.availabilityZoneField = value; } } /// <summary> /// Sets the Availability Zone the subnet is in. /// </summary> /// <param name="availabilityZone">The Availability Zone the subnet is in.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithAvailabilityZone(string availabilityZone) { this.availabilityZoneField = availabilityZone; return this; } /// <summary> /// Checks if AvailabilityZone property is set /// </summary> /// <returns>true if AvailabilityZone property is set</returns> public bool IsSetAvailabilityZone() { return this.availabilityZoneField != null; } /// <summary> /// Whether the subnet is default for the availability zone. /// </summary> [XmlElementAttribute(ElementName = "DefaultForAz")] public bool DefaultForAz { get { return this.defaultForAzField.GetValueOrDefault(); } set { this.defaultForAzField = value; } } /// <summary> /// Sets whether the subnet is default for the availability zone. /// </summary> /// <param name="defaultForAz">Whether the subnet is default for the availability zone.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithDefaultForAz(bool defaultForAz) { this.defaultForAzField = defaultForAz; return this; } /// <summary> /// Checks if the DefaultForAz property is set /// </summary> /// <returns>true if the DefaultForAz property is set</returns> public bool IsSetDefaultForAz() { return this.defaultForAzField != null; } /// <summary> /// Whether to map the public IP on launch. /// </summary> [XmlElementAttribute(ElementName = "MapPublicIpOnLaunch")] public bool MapPublicIpOnLaunch { get { return this.defaultForAzField.GetValueOrDefault(); } set { this.defaultForAzField = value; } } /// <summary> /// Sets whether to map the public IP on launch. /// </summary> /// <param name="mapPublicIpOnLaunch">Whether to map the public IP on launch.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithMapPublicIpOnLaunch(bool mapPublicIpOnLaunch) { this.mapPublicIpOnLaunchField = mapPublicIpOnLaunch; return this; } /// <summary> /// Checks if the MapPublicIpOnLaunch property is set /// </summary> /// <returns>true if the MapPublicIpOnLaunch property is set</returns> public bool IsSetMapPublicIpOnLaunch() { return this.mapPublicIpOnLaunchField != null; } /// <summary> /// A list of tags for the Subnet. /// </summary> [XmlElementAttribute(ElementName = "Tag")] public List<Tag> Tag { get { if (this.tagField == null) { this.tagField = new List<Tag>(); } return this.tagField; } set { this.tagField = value; } } /// <summary> /// Sets tags for the Subnet. /// </summary> /// <param name="list">A list of tags for the Subnet.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Subnet WithTag(params Tag[] list) { foreach (Tag item in list) { Tag.Add(item); } return this; } /// <summary> /// Checks if Tag property is set /// </summary> /// <returns>true if Tag property is set</returns> public bool IsSetTag() { return (Tag.Count > 0); } } }
using System; using Eto.Drawing; namespace Eto.Forms { /// <summary> /// Event arguments when painting using the <see cref="Drawable.Paint"/> event /// </summary> public class PaintEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.PaintEventArgs"/> class. /// </summary> /// <param name="graphics">Graphics for the paint event</param> /// <param name="clipRectangle">Rectangle of the region being painted</param> public PaintEventArgs(Graphics graphics, RectangleF clipRectangle) { ClipRectangle = clipRectangle; Graphics = graphics; } /// <summary> /// Gets the graphics for the paint operation /// </summary> /// <value>The graphics.</value> public Graphics Graphics { get; private set; } /// <summary> /// Gets the rectangle of the region being painted /// </summary> /// <remarks> /// This should be used to optimize what is drawn by only drawing content that intersects with this rectangle. /// </remarks> /// <value>The clip rectangle for the current paint operation</value> public RectangleF ClipRectangle { get; private set; } } /// <summary> /// Control with a paintable user interface /// </summary> /// <remarks> /// The drawable control is used to perform custom painting. /// </remarks> /// <copyright>(c) 2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> [Handler(typeof(Drawable.IHandler))] public class Drawable : Panel { new IHandler Handler { get { return (IHandler)base.Handler; } } /// <summary> /// Event to handle custom painting on the control /// </summary> public event EventHandler<PaintEventArgs> Paint; /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Drawable"/> class. /// </summary> public Drawable() { Handler.Create(); Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Drawable"/> class with the specified handler /// </summary> /// <param name="handler">Handler interface for the drawable</param> protected Drawable(IHandler handler) : base(handler) { } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.Drawable"/> class with a hint whether it is intended for a large canvas /// </summary> /// <remarks> /// Some platforms can optimize large canvases, such as mobile platforms by tiling the painting of the canvas. /// /// A large canvas is one that is larger than the intended screen size. /// /// Platforms are not required to change the behaviour of the drawable depending on this value. Desktop platforms /// typically do not change their behaviour based on this. /// </remarks> /// <param name="largeCanvas">If set to <c>true</c> the drawable is created to have a large canvas.</param> public Drawable(bool largeCanvas) { Handler.Create(largeCanvas); Initialize(); } /// <summary> /// Raises the <see cref="Paint"/> event /// </summary> /// <param name="e">Paint event arguments</param> protected virtual void OnPaint(PaintEventArgs e) { if (Paint != null) Paint(this, e); } /// <summary> /// Gets a value indicating whether this <see cref="Eto.Forms.Drawable"/> supports the <see cref="CreateGraphics"/> method /// </summary> /// <value><c>true</c> if supports creating graphics; otherwise, <c>false</c>.</value> public bool SupportsCreateGraphics { get { return Handler.SupportsCreateGraphics; } } /// <summary> /// Creates a graphics context for this control /// </summary> /// <remarks> /// This can be used to draw directly onto the control. /// Ensure you dispose the graphics object after performing any painting. /// Note that not all platforms support drawing directly on the control, use <see cref="SupportsCreateGraphics"/>. /// </remarks> /// <returns>A new graphics context that can be used to draw directly onto the control</returns> public Graphics CreateGraphics() { return Handler.CreateGraphics(); } /// <summary> /// Gets or sets a value indicating whether this instance can recieve the input/keyboard focus /// </summary> /// <remarks> /// If this is true, by default all platforms will focus the control automatically when it is clicked. /// </remarks> /// <value><c>true</c> if this instance can be focussed; otherwise, <c>false</c>.</value> public bool CanFocus { get { return Handler.CanFocus; } set { Handler.CanFocus = value; } } /// <summary> /// Update the specified <paramref name="region"/> directly /// </summary> /// <remarks> /// This forces the region to be painted immediately. On some platforms, this will be similar to calling /// <see cref="Control.Invalidate(Rectangle)"/>, and queue the repaint instead of blocking until it is painted. /// </remarks> /// <param name="region">Region to update the control</param> public void Update(Rectangle region) { Handler.Update(region); } static readonly object callback = new Callback(); /// <summary> /// Gets an instance of an object used to perform callbacks to the widget from handler implementations /// </summary> /// <returns>The callback instance to use for this widget</returns> protected override object GetCallback() { return callback; } /// <summary> /// Callback interface for <see cref="Drawable"/> /// </summary> public new interface ICallback : Panel.ICallback { /// <summary> /// Raises the paint event. /// </summary> void OnPaint(Drawable widget, PaintEventArgs e); } /// <summary> /// Callback implementation for handlers of <see cref="Drawable"/> /// </summary> protected new class Callback : Panel.Callback, ICallback { /// <summary> /// Raises the paint event. /// </summary> public void OnPaint(Drawable widget, PaintEventArgs e) { widget.Platform.Invoke(() => widget.OnPaint(e)); } } #region Handler /// <summary> /// Handler interface for the <see cref="Drawable"/> control /// </summary> /// <copyright>(c) 2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> [AutoInitialize(false)] public new interface IHandler : Panel.IHandler { /// <summary> /// Gets a value indicating whether this <see cref="Eto.Forms.Drawable"/> supports the <see cref="CreateGraphics"/> method /// </summary> /// <value><c>true</c> if supports creating graphics; otherwise, <c>false</c>.</value> bool SupportsCreateGraphics { get; } /// <summary> /// Creates a new drawable control without specifying a large canvas or not /// </summary> void Create(); /// <summary> /// Called when creating a drawable control with a hint whether it is intended for a large canvas /// </summary> /// <remarks> /// Some platforms can optimize large canvases, such as mobile platforms by tiling the painting of the canvas. /// /// A large canvas is one that is larger than the intended screen size. /// /// Platforms are not required to change the behaviour of the drawable depending on this value. Desktop platforms /// typically do not change their behaviour based on this. /// </remarks> /// <param name="largeCanvas">If set to <c>true</c> the drawable is created to have a large canvas.</param> void Create(bool largeCanvas); /// <summary> /// Update the specified <paramref name="region"/> directly /// </summary> /// <remarks> /// This forces the region to be painted immediately. On some platforms, this will be similar to calling /// <see cref="Control.Invalidate(Rectangle)"/>, and queue the repaint instead of blocking until it is painted. /// </remarks> /// <param name="region">Region to update the control</param> void Update(Rectangle region); /// <summary> /// Gets or sets a value indicating whether this instance can recieve the input/keyboard focus /// </summary> /// <remarks> /// If this is true, by default all platforms will focus the control automatically when it is clicked. /// </remarks> /// <value><c>true</c> if this instance can be focussed; otherwise, <c>false</c>.</value> bool CanFocus { get; set; } /// <summary> /// Creates a graphics context for this control /// </summary> /// <remarks> /// This can be used to draw directly onto the control. /// Ensure you dispose the graphics object after performing any painting. /// Note that not all platforms support drawing directly on the control, use <see cref="SupportsCreateGraphics"/>. /// </remarks> /// <returns>A new graphics context that can be used to draw directly onto the control</returns> Graphics CreateGraphics(); } #endregion } }
using hw.DebugFormatter; using hw.UnitTest; namespace ReniUI.Test.Formatting; [UnitTest] [TestFixture] [FlatStrings] public sealed class Lists : DependenceProvider { [Test] [UnitTest] public void SimpleLine() { const string text = @"(1,3,4,6)"; var compiler = CompilerBrowser.FromText(text); var span = compiler.Source.All; var trimmed = compiler.Reformat(targetPart: span); (trimmed == "(1, 3, 4, 6)").Assert(trimmed); } [Test] [UnitTest] public void SingleElementList() { const string text = @"((aaaaaddddd))"; const string expectedText = @"(( aaaaaddddd ))"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void SingleElementListFlat() { const string text = @"(aaaaaddddd)"; const string expectedText = @"(aaaaaddddd)"; text.SimpleFormattingTest(expectedText, 14, 1); } [Test] [UnitTest] public void StraightList() { const string text = @"(aaaaa;ccccc)"; const string expectedText = @"( aaaaa; ccccc )"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void StraightList3() { const string text = @"(aaaaa;bbbbb;ccccc)"; const string expectedText = @"( aaaaa; bbbbb; ccccc )"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void StraightListWithMultipleBrackets() { const string text = @"((aaaaa;ccccc))"; const string expectedText = @"(( aaaaa; ccccc ))"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void FlatList2() { const string text = @"aaaaa;ccccc"; const string expectedText = @"aaaaa; ccccc"; text.SimpleFormattingTest(expectedText); } [Test] [UnitTest] public void ListEndsWithListToken() { const string text = @"(aaaaa;bbbbb;ccccc;)"; const string expectedText = @"( aaaaa; bbbbb; ccccc; )"; text.SimpleFormattingTest(expectedText, 19, 1); } [Test] [UnitTest] public void ListSeparatorAtEnd() { const string text = @"aaaaa;"; const string expectedText = @"aaaaa;"; var compiler = CompilerBrowser.FromText(text); var newSource = compiler.FlatFormat(false); (newSource == expectedText).Assert("\n\"" + newSource + "\""); } [Test] [UnitTest] public void ListLineBreakTest2() { const string text = @"aaaaa;bbbbb"; const string expectedText = @"aaaaa; bbbbb"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListLineBreakTest3() { const string text = @"aaaaa;bbbbb;ccccc"; const string expectedText = @"aaaaa; bbbbb; ccccc"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListTest1() { const string text = @"aaaaa"; const string expectedText = @"aaaaa"; text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListTest2() { const string text = @"aaaaa;bbbbb"; const string expectedText = @"aaaaa; bbbbb"; text.SimpleFormattingTest(expectedText, 20, 1); } [Test] [UnitTest] public void MultilineBreakTest() { const string text = @"(ccccc,aaaaa bbbbb, )"; var expectedText = @"( ccccc, aaaaa bbbbb, )".Replace("\r\n", "\n"); text.SimpleFormattingTest(expectedText, 10, 1); } [Test] [UnitTest] public void MultilineBreakTest1() { const string text = @"(ccccc,aaaaa bbbbb)"; var expectedText = @"( ccccc, aaaaa bbbbb )".Replace("\r\n", "\n"); text.SimpleFormattingTest(expectedText, 10, 1); } [UnitTest] public void ListOfLists() { // ReSharper disable once StringLiteralTypo const string text = "Auswahl: @{ Ja: (Type: ^^, Value: \"Ja\"), " + "Nein: (Type: ^^, Value: \"Nein\"), " + "Vielleicht: (Type: ^^, Value: \"Vielleicht\")}"; const string expected = @"Auswahl: @ { Ja: (Type: ^^, Value: ""Ja""), Nein: (Type: ^^, Value: ""Nein""), Vielleicht: (Type: ^^, Value: ""Vielleicht"") }"; text.SimpleFormattingTest(expected, indentCount: 2, lineBreaksAtComplexDeclaration: true); } }
/* * Copyright (C) 2009 The Android Open Source 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. */ using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using System; using System.Collections.Generic; namespace Xamarians.CropImage.Droid { public class CropImageView : ImageViewTouchBase { #region Private members private List<HighlightView> hightlightViews = new List<HighlightView>(); private HighlightView mMotionHighlightView = null; private float mLastX; private float mLastY; private global::Xamarians.CropImage.Droid.HighlightView.HitPosition motionEdge; private Context context; #endregion #region Constructor public CropImageView(Context context, IAttributeSet attrs) : base(context, attrs) { SetLayerType(Android.Views.LayerType.Software, null); this.context = context; } #endregion #region Public methods public void ClearHighlightViews() { this.hightlightViews.Clear(); } public void AddHighlightView(HighlightView hv) { hightlightViews.Add(hv); Invalidate(); } #endregion #region Overrides protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); for (int i = 0; i < hightlightViews.Count; i++) { hightlightViews[i].Draw(canvas); } } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); if (bitmapDisplayed.Bitmap != null) { foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); if (hv.Focused) { centerBasedOnHighlightView(hv); } } } } protected override void ZoomTo(float scale, float centerX, float centerY) { base.ZoomTo(scale, centerX, centerY); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomIn() { base.ZoomIn(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomOut() { base.ZoomOut(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void PostTranslate(float deltaX, float deltaY) { base.PostTranslate(deltaX, deltaY); for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; hv.matrix.PostTranslate(deltaX, deltaY); hv.Invalidate(); } } public override bool OnTouchEvent(MotionEvent ev) { CropImageActivity cropImage = (CropImageActivity)context; if (cropImage.Saving) { return false; } switch (ev.Action) { case MotionEventActions.Down: for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; var edge = hv.GetHit(ev.GetX(), ev.GetY()); if (edge != HighlightView.HitPosition.None) { motionEdge = edge; mMotionHighlightView = hv; mLastX = ev.GetX(); mLastY = ev.GetY(); mMotionHighlightView.Mode = (edge == HighlightView.HitPosition.Move) ? HighlightView.ModifyMode.Move : HighlightView.ModifyMode.Grow; break; } } break; case MotionEventActions.Up: if (mMotionHighlightView != null) { centerBasedOnHighlightView(mMotionHighlightView); mMotionHighlightView.Mode = HighlightView.ModifyMode.None; } mMotionHighlightView = null; break; case MotionEventActions.Move: if (mMotionHighlightView != null) { mMotionHighlightView.HandleMotion(motionEdge, ev.GetX() - mLastX, ev.GetY() - mLastY); mLastX = ev.GetX(); mLastY = ev.GetY(); if (true) { // This section of code is optional. It has some user // benefit in that moving the crop rectangle against // the edge of the screen causes scrolling but it means // that the crop rectangle is no longer fixed under // the user's finger. ensureVisible(mMotionHighlightView); } } break; } switch (ev.Action) { case MotionEventActions.Up: Center(true, true); break; case MotionEventActions.Move: // if we're not zoomed then there's no point in even allowing // the user to move the image around. This call to center puts // it back to the normalized location (with false meaning don't // animate). if (GetScale() == 1F) { Center(true, true); } break; } return true; } #endregion #region Private helpers // Pan the displayed image to make sure the cropping rectangle is visible. private void ensureVisible(HighlightView hv) { Rect r = hv.DrawRect; int panDeltaX1 = Math.Max(0, IvLeft - r.Left); int panDeltaX2 = Math.Min(0, IvRight - r.Right); int panDeltaY1 = Math.Max(0, IvTop - r.Top); int panDeltaY2 = Math.Min(0, IvBottom - r.Bottom); int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2; if (panDeltaX != 0 || panDeltaY != 0) { PanBy(panDeltaX, panDeltaY); } } // If the cropping rectangle's size changed significantly, change the // view's center and scale according to the cropping rectangle. private void centerBasedOnHighlightView(HighlightView hv) { Rect drawRect = hv.DrawRect; float width = drawRect.Width(); float height = drawRect.Height(); float thisWidth = Width; float thisHeight = Height; float z1 = thisWidth / width * .6F; float z2 = thisHeight / height * .6F; float zoom = Math.Min(z1, z2); zoom = zoom * this.GetScale(); zoom = Math.Max(1F, zoom); if ((Math.Abs(zoom - GetScale()) / zoom) > .1) { float[] coordinates = new float[] { hv.CropRect.CenterX(), hv.CropRect.CenterY() }; ImageMatrix.MapPoints(coordinates); ZoomTo(zoom, coordinates[0], coordinates[1], 300F); } ensureVisible(hv); } #endregion } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace MindTouch.Xml { /// <summary> /// Provides a facility for comparing <see cref="XDoc"/> instances. /// </summary> public static class XDocDiff { //--- Constants --- private const string DELETED = "del"; private const string INSERTED = "ins"; private const int MAX_SAME_COUNTER = 3; //--- Types --- /// <summary> /// Provides a xml node token. /// </summary> public class Token { //--- Class Methods --- /// <summary> /// Compare two Token to determine whether they represent the same value. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool Equal(Token left, Token right) { return (left.Type == right.Type) && (left.Value == right.Value); } //--- Fields --- /// <summary> /// Type of node. /// </summary> public readonly XmlNodeType Type; /// <summary> /// String value of Xml node. /// </summary> public readonly string Value; /// <summary> /// Unique key to identify token by. /// </summary> public readonly object Key; //--- Constructors --- /// <summary> /// Create a new node token. /// </summary> /// <param name="type">Type of node.</param> /// <param name="value">String value of node.</param> /// <param name="key">Unique key to identify token by.</param> public Token(XmlNodeType type, string value, object key) { this.Type = type; this.Value = value; this.Key = key; } //--- Methods --- /// <summary> /// Return a string representation of the the Token's value. /// </summary> /// <returns>A string instance.</returns> public override string ToString() { return Type + "(" + Value + ")"; } } //--- Class Methods --- /// <summary> /// Diff two documents. /// </summary> /// <param name="left">Left hand document.</param> /// <param name="right">Right hand document.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <returns>Array of difference tuples.</returns> public static Tuple<ArrayDiffKind, Token>[] Diff(XDoc left, XDoc right, int maxsize) { if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return Diff(Tokenize(left), Tokenize(right), maxsize); } /// <summary> /// Diff two token sets. /// </summary> /// <param name="left">Left hand token set.</param> /// <param name="right">Right hand token set.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <returns>Array of difference tuples.</returns> public static Tuple<ArrayDiffKind, Token>[] Diff(Token[] left, Token[] right, int maxsize) { if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return ArrayUtil.Diff(left, right, maxsize, Token.Equal); } /// <summary> /// Perform a three-way merge of documents. /// </summary> /// <param name="original">Original document.</param> /// <param name="left">Left hand modification of document.</param> /// <param name="right">Right hand modification of document.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <param name="priority">Merge priority.</param> /// <param name="conflict">Output of conflict flag.</param> /// <returns>Merged document.</returns> public static XDoc Merge(XDoc original, XDoc left, XDoc right, int maxsize, ArrayMergeDiffPriority priority, out bool conflict) { if(original == null) { throw new ArgumentNullException("original"); } if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return Merge(Tokenize(original), Tokenize(left), Tokenize(right), maxsize, priority, out conflict); } /// <summary> /// Perform a three-way merge between token sets resulting in a document. /// </summary> /// <param name="original">Original Token set.</param> /// <param name="left">Left hand token set.</param> /// <param name="right">Right hand token set.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <param name="priority">Merge priority.</param> /// <param name="conflict">Output of conflict flag.</param> /// <returns>Merged document.</returns> public static XDoc Merge(Token[] original, Token[] left, Token[] right, int maxsize, ArrayMergeDiffPriority priority, out bool conflict) { if(original == null) { throw new ArgumentNullException("original"); } if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } // create left diff var leftDiff = Diff(original, left, maxsize); if(leftDiff == null) { conflict = false; return null; } // create right diff var rightDiff = Diff(original, right, maxsize); if(rightDiff == null) { conflict = false; return null; } // merge changes var mergeDiff = ArrayUtil.MergeDiff(leftDiff, rightDiff, priority, Token.Equal, x => x.Key, out conflict); return Detokenize(mergeDiff); } /// <summary> /// Create a highlight document from a set of differences. /// </summary> /// <param name="diff">Difference set.</param> /// <returns>Highlight document.</returns> public static XDoc Highlight(Tuple<ArrayDiffKind, Token>[] diff) { XDoc combined; List<Tuple<string, string, string>> invisibleChanges; XDoc before; XDoc after; Highlight(diff, out combined, out invisibleChanges, out before, out after); return combined; } /// <summary> /// Create before, after and combined highlight documents for a set of differences. /// </summary> /// <param name="diff">Difference set.</param> /// <param name="combined">Output of combined highlight document.</param> /// <param name="combinedInvisible">Output of the combined invisible differences.</param> /// <param name="before">Output of before difference highlight document.</param> /// <param name="after">Output of after difference highlight document.</param> public static void Highlight(Tuple<ArrayDiffKind, Token>[] diff, out XDoc combined, out List<Tuple<string, string, string>> combinedInvisible /* tuple(xpath, before, after) */, out XDoc before, out XDoc after) { if(diff == null) { throw new ArgumentNullException("diff"); } combinedInvisible = new List<Tuple<string, string, string>>(); var combinedChanges = new List<Tuple<ArrayDiffKind, Token>>(diff.Length); var beforeChanges = new List<Tuple<ArrayDiffKind, Token>>(diff.Length); var afterChanges = new List<Tuple<ArrayDiffKind, Token>>(diff.Length); bool changedElement = false; Stack<List<string>> path = new Stack<List<string>>(); var invisibleChangesLookup = new Dictionary<string, Tuple<string, string, string>>(); path.Push(new List<string>()); for(int i = 0; i < diff.Length; ++i) { var item = diff[i]; Token token = item.Item2; switch(item.Item1) { case ArrayDiffKind.Added: switch(token.Type) { case XmlNodeType.Text: if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { Highlight_InlineTextChanges(diff, i, combinedChanges, beforeChanges, afterChanges, out i); // adjust iterator since it will be immediately increased again --i; continue; } break; case XmlNodeType.Attribute: if(!changedElement) { string[] parts = token.Value.Split(new char[] { '=' }, 2); string xpath = ComputeXPath(path, "@" + parts[0]); Tuple<string, string, string> beforeAfter; if(invisibleChangesLookup.TryGetValue(xpath, out beforeAfter)) { invisibleChangesLookup[xpath] = new Tuple<string, string, string>(beforeAfter.Item1, beforeAfter.Item2, parts[1]); } else { beforeAfter = new Tuple<string, string, string>(xpath, null, parts[1]); invisibleChangesLookup[xpath] = beforeAfter; } } break; case XmlNodeType.Element: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Peek().Add(token.Value); } path.Push(new List<string>()); changedElement = true; break; case XmlNodeType.None: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Pop(); } break; } item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, token); afterChanges.Add(item); combinedChanges.Add(item); break; case ArrayDiffKind.Removed: switch(token.Type) { case XmlNodeType.Text: if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { Highlight_InlineTextChanges(diff, i, combinedChanges, beforeChanges, afterChanges, out i); // adjust iterator since it will be immediately increased again --i; continue; } else { // keep whitespace text combinedChanges.Add(new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); } break; case XmlNodeType.Attribute: if(!changedElement) { string[] parts = token.Value.Split(new char[] { '=' }, 2); string xpath = ComputeXPath(path, "@" + parts[0]); Tuple<string, string, string> beforeAfter; if(invisibleChangesLookup.TryGetValue(xpath, out beforeAfter)) { invisibleChangesLookup[xpath] = new Tuple<string, string, string>(beforeAfter.Item1, parts[1], beforeAfter.Item3); } else { beforeAfter = new Tuple<string, string, string>(xpath, parts[1], null); invisibleChangesLookup[xpath] = beforeAfter; } } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: // keep whitespace text combinedChanges.Add(new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); break; case XmlNodeType.Element: changedElement = true; break; } beforeChanges.Add(new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); break; case ArrayDiffKind.Same: switch(token.Type) { case XmlNodeType.Element: changedElement = false; // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Peek().Add(token.Value); } path.Push(new List<string>()); break; case XmlNodeType.None: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Pop(); } break; } combinedChanges.Add(item); beforeChanges.Add(item); afterChanges.Add(item); break; case ArrayDiffKind.AddedLeft: case ArrayDiffKind.AddedRight: case ArrayDiffKind.RemovedLeft: case ArrayDiffKind.RemovedRight: // TODO (steveb): process conflicting changes throw new NotImplementedException("cannot highlight changes for a diff with conflicts"); } } before = Detokenize(beforeChanges.ToArray()); after = Detokenize(afterChanges.ToArray()); combined = Detokenize(combinedChanges.ToArray()); combinedInvisible.AddRange(invisibleChangesLookup.Values); } private static void Highlight_InlineTextChanges(Tuple<ArrayDiffKind, Token>[] diff, int index, List<Tuple<ArrayDiffKind, Token>> combinedChanges, List<Tuple<ArrayDiffKind, Token>> beforeChanges, List<Tuple<ArrayDiffKind, Token>> afterChanges, out int next) { int lastAdded = index; int lastRemoved = index; int firstAdded = -1; int firstRemoved = -1; Tuple<ArrayDiffKind, Token> item; // determine how long the chain of intermingled changes is for(int i = index, sameCounter = 0; (i < diff.Length) && ((diff[i].Item2.Type == XmlNodeType.Text) || (diff[i].Item2.Type == XmlNodeType.Whitespace) || diff[i].Item2.Type == XmlNodeType.SignificantWhitespace) && (sameCounter <= MAX_SAME_COUNTER); ++i) { item = diff[i]; Token token = item.Item2; if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { if(item.Item1 == ArrayDiffKind.Added) { sameCounter = 0; if(firstAdded == -1) { firstAdded = i; } lastAdded = i; } else if(item.Item1 == ArrayDiffKind.Removed) { sameCounter = 0; if(firstRemoved == -1) { firstRemoved = i; } lastRemoved = i; } else { // we count the number of non-changed elements to break-up long runs with no changes ++sameCounter; } } } // set index of next element next = Math.Max(lastAdded, lastRemoved) + 1; // check if any text was added if(firstAdded != -1) { // add all unchanged text before the first added text for(int i = index; i < firstAdded; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } // add all text nodes that were added in a row object key = new object(); item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.Element, INSERTED, key)); combinedChanges.Add(item); afterChanges.Add(item); item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.EndElement, string.Empty, null)); combinedChanges.Add(item); afterChanges.Add(item); for(int i = firstAdded; i <= lastAdded; ++i) { if(diff[i].Item1 != ArrayDiffKind.Removed) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.None, INSERTED, key)); combinedChanges.Add(item); afterChanges.Add(item); // add all unchanged text after the last added text for(int i = lastAdded + 1; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } } else { // add all unchanged text before the first added text for(int i = index; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } } // check if any text was removed if(firstRemoved != -1) { // add all unchanged text before the first removed text for(int i = index; i < firstRemoved; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); if((item.Item2.Value.Length > 0) && !char.IsWhiteSpace(item.Item2.Value[0])) { combinedChanges.Add(item); } beforeChanges.Add(item); } } // add all text nodes that were removed in a row object key = new object(); item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.Element, DELETED, key)); combinedChanges.Add(item); beforeChanges.Add(item); item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.EndElement, string.Empty, null)); combinedChanges.Add(item); beforeChanges.Add(item); for(int i = firstRemoved; i <= lastRemoved; ++i) { if(diff[i].Item1 != ArrayDiffKind.Added) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); beforeChanges.Add(item); } } item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.None, DELETED, key)); combinedChanges.Add(item); beforeChanges.Add(item); // add all unchanged text after the last removed text for(int i = lastRemoved + 1; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); beforeChanges.Add(item); } } } else { // add all unchanged text before the first removed text for(int i = index; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuple<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); if((item.Item2.Value.Length > 0) && !char.IsWhiteSpace(item.Item2.Value[0])) { combinedChanges.Add(item); } beforeChanges.Add(item); } } } } /// <summary> /// Create a document from a difference set. /// </summary> /// <param name="tokens">Difference set.</param> /// <returns>Detokenized document.</returns> public static XDoc Detokenize(Tuple<ArrayDiffKind, Token>[] tokens) { XmlDocument doc = XDoc.NewXmlDocument(); Detokenize(tokens, 0, null, doc); return new XDoc(doc); } /// <summary> /// Convert a document to a token set. /// </summary> /// <param name="doc"></param> /// <returns>Set of tokens.</returns> public static Token[] Tokenize(XDoc doc) { if(doc.IsEmpty) { throw new ArgumentException("XML document is empty", "doc"); } List<Token> result = new List<Token>(); XmlNode start = doc.AsXmlNode; if(start is XmlDocument) { start = start.OwnerDocument.DocumentElement; } Tokenize(start, result); return result.ToArray(); } /// <summary> /// Write a difference set. /// </summary> /// <param name="diffset">Difference set.</param> /// <param name="writer">TextWriter to write the set to.</param> public static void Write(Tuple<ArrayDiffKind, Token>[] diffset, TextWriter writer) { foreach(var entry in diffset) { switch(entry.Item1) { case ArrayDiffKind.Same: writer.WriteLine(" " + entry.Item2); break; case ArrayDiffKind.Removed: writer.WriteLine("-" + entry.Item2); break; case ArrayDiffKind.Added: writer.WriteLine("+" + entry.Item2); break; case ArrayDiffKind.AddedLeft: writer.WriteLine("+<" + entry.Item2); break; case ArrayDiffKind.AddedRight: writer.WriteLine("+>" + entry.Item2); break; case ArrayDiffKind.RemovedLeft: writer.WriteLine("-<" + entry.Item2); break; case ArrayDiffKind.RemovedRight: writer.WriteLine("->" + entry.Item2); break; } } } private static int Detokenize(Tuple<ArrayDiffKind, Token>[] tokens, int index, XmlElement current, XmlDocument doc) { for(; index < tokens.Length; ++index) { var token = tokens[index]; switch(token.Item1) { case ArrayDiffKind.Same: case ArrayDiffKind.Added: switch(token.Item2.Type) { case XmlNodeType.CDATA: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateCDataSection(token.Item2.Value)); break; case XmlNodeType.Comment: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateComment(token.Item2.Value)); break; case XmlNodeType.SignificantWhitespace: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateSignificantWhitespace(token.Item2.Value)); break; case XmlNodeType.Text: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateTextNode(token.Item2.Value)); break; case XmlNodeType.Whitespace: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateWhitespace(token.Item2.Value)); break; case XmlNodeType.Element: XmlElement next = doc.CreateElement(token.Item2.Value); if(current == null) { doc.AppendChild(next); } else { current.AppendChild(next); } index = Detokenize(tokens, index + 1, next, doc); break; case XmlNodeType.Attribute: if(current == null) { throw new ArgumentNullException("current"); } string[] parts = token.Item2.Value.Split(new char[] { '=' }, 2); current.SetAttribute(parts[0], parts[1]); break; case XmlNodeType.EndElement: // nothing to do break; case XmlNodeType.None: if(current == null) { throw new ArgumentNullException("current"); } // ensure we're closing the intended element if(token.Item2.Value != current.Name) { throw new InvalidOperationException(string.Format("mismatched element ending; found </{0}>, expected </{1}>", token.Item2.Value, current.Name)); } // we're done with this sequence return index; default: throw new InvalidOperationException("unhandled node type: " + token.Item2.Type); } break; case ArrayDiffKind.Removed: // ignore removed nodes break; default: throw new InvalidOperationException("invalid diff kind: " + token.Item1); } } if(current != null) { throw new InvalidOperationException("unexpected end of tokens"); } return index; } private static void Tokenize(XmlNode node, List<Token> tokens) { switch(node.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: tokens.Add(new Token(node.NodeType, node.Value, null)); break; case XmlNodeType.Text: { // split text nodes string text = node.Value; int start = 0; int end = text.Length; while(start < end) { // check if first character is a whitespace int index = start + 1; if(char.IsWhiteSpace(text[start])) { // skip whitespace while((index < end) && char.IsWhiteSpace(text[index])) { ++index; } } else if(char.IsLetterOrDigit(text[start]) || (text[start] == '_')) { // skip alphanumeric, underscore (_), and dot (.)/comma (,) if preceded by a digit while(index < end) { char c = text[index]; if(char.IsLetterOrDigit(c) || (c == '_') || (((c == '.') || (c == ',')) && (index > start) && char.IsDigit(text[index-1]))) { ++index; } else { break; } } } else { // skip non-whitespace & non-alphanumeric while((index < end) && !char.IsWhiteSpace(text[index]) && !char.IsLetterOrDigit(text[index])) { ++index; } } if((start == 0) && (index == end)) { tokens.Add(new Token(XmlNodeType.Text, text, null)); } else { tokens.Add(new Token(XmlNodeType.Text, text.Substring(start, index - start), null)); } start = index; } } break; case XmlNodeType.Element: object key = new object(); tokens.Add(new Token(XmlNodeType.Element, node.Name, key)); // enumerate attribute in sorted order if(node.Attributes.Count > 0) { List<XmlAttribute> attributes = new List<XmlAttribute>(); foreach(XmlAttribute attribute in node.Attributes) { attributes.Add(attribute); } attributes.Sort((left, right) => StringUtil.CompareInvariant(left.Name, right.Name)); foreach(XmlAttribute attribute in attributes) { tokens.Add(new Token(XmlNodeType.Attribute, attribute.Name + "=" + attribute.Value, null)); } } tokens.Add(new Token(XmlNodeType.EndElement, string.Empty, null)); if(node.HasChildNodes) { foreach(XmlNode child in node.ChildNodes) { Tokenize(child, tokens); } } tokens.Add(new Token(XmlNodeType.None, node.Name, key)); break; } } private static string ComputeXPath(Stack<List<string>> path, string last) { StringBuilder result = new StringBuilder(); List<string>[] levels = path.ToArray(); Array.Reverse(levels); foreach(List<string> level in levels) { if(level.Count > 0) { string current = level[level.Count - 1]; int count = 1; for(int i = 0; i < level.Count - 1; ++i) { if(StringUtil.EqualsInvariant(current, level[i])) { ++count; } } result.Append('/').Append(current); if(count > 1) { result.Append('[').Append(count).Append(']'); } } } if(!string.IsNullOrEmpty(last)) { result.Append('/').Append(last); } return result.ToString(); } } /// <summary> /// Provides a utility for extracting and replacing words from an xml document. /// </summary> public class XDocWord { //--- Types --- /// <summary> /// Delegate for replacing and <see cref="XDocWord"/> instance in a document with a new XmlNode. /// </summary> /// <param name="doc">Parent document node of the word.</param> /// <param name="word">Word to replace.</param> /// <returns>Replacement Xml node.</returns> public delegate XmlNode ReplacementHandler(XmlDocument doc, XDocWord word); //--- Class Methods --- /// <summary> /// Create a word list from an <see cref="XDoc"/> instance. /// </summary> /// <param name="doc">Document to extract words from.</param> /// <returns>Array of word instances.</returns> public static XDocWord[] ConvertToWordList(XDoc doc) { List<XDocWord> result = new List<XDocWord>(); if(!doc.IsEmpty) { ConvertToWordList(doc.AsXmlNode, result); } return result.ToArray(); } /// <summary> /// Replace words in a document. /// </summary> /// <param name="wordlist">List of words to run replacement function for.</param> /// <param name="handler">Word replacement delegate.</param> public static void ReplaceText(XDocWord[] wordlist, ReplacementHandler handler) { if(wordlist == null) { throw new ArgumentNullException("wordlist"); } if(handler == null) { throw new ArgumentNullException("handler"); } // loop through words backwards for(int i = wordlist.Length - 1; i >= 0; --i) { XDocWord word = wordlist[i]; if(word.IsText) { XmlNode replacement = handler(word.Node.OwnerDocument, word); if(replacement != null) { // split the node XmlText node = (XmlText)word.Node; // split off the part after the text if(node.Value.Length > (word.Offset + word.Value.Length)) { node.SplitText(word.Offset + word.Value.Length); } // split off the part before the text if(word.Offset > 0) { node = node.SplitText(word.Offset); } // replace text with new result node.ParentNode.InsertAfter(replacement, node); node.ParentNode.RemoveChild(node); } } } } private static void ConvertElementToWord(XmlNode node, string[] attributes, List<XDocWord> words) { StringBuilder tag = new StringBuilder(); tag.Append("<"); tag.Append(node.Name); foreach(string attribute in attributes) { XmlAttribute attr = node.Attributes[attribute]; if(attr != null) { tag.AppendFormat(" {0}=\"{1}\"", attr.Name, attr.Value); } } tag.Append(">"); words.Add(new XDocWord(tag.ToString(), 0, node)); } private static void ConvertToWordList(XmlNode node, List<XDocWord> words) { switch(node.NodeType) { case XmlNodeType.Document: ConvertToWordList(((XmlDocument)node).DocumentElement, words); break; case XmlNodeType.Element: switch(node.Name) { case "img": ConvertElementToWord(node, new string[] { "src" }, words); break; default: if(node.HasChildNodes) { foreach(XmlNode child in node.ChildNodes) { ConvertToWordList(child, words); } } break; } break; case XmlNodeType.Text: { // split text nodes string text = node.Value; if((text.Length == 0) && (words.Count == 0)) { // NOTE (steveb): we add the empty text node at the beginning of each document as a reference point words.Add(new XDocWord(text, 0, node)); } else { int start = 0; int end = text.Length; while(start < end) { // check if first character is a whitespace int index = start + 1; if(char.IsWhiteSpace(text[start])) { // skip whitespace while((index < end) && char.IsWhiteSpace(text[index])) { ++index; } } else if(char.IsLetterOrDigit(text[start])) { // skip alphanumeric, underscore (_), and dot (.)/comma (,) if preceded by a digit while(index < end) { char c = text[index]; if(char.IsLetterOrDigit(c) || (c == '_') || (((c == '.') || (c == ',')) && (index > start) && char.IsDigit(text[index - 1]))) { ++index; } else { break; } } } else { // skip non-whitespace & non-alphanumeric while((index < end) && !char.IsWhiteSpace(text[index]) && !char.IsLetterOrDigit(text[index])) { ++index; } } // only add non-whitespace nodes if(!char.IsWhiteSpace(text[start])) { if((start == 0) && (index == end)) { words.Add(new XDocWord(text, 0, node)); } else { words.Add(new XDocWord(text.Substring(start, index - start), start, node)); } } start = index; } } } break; } } //--- Fields --- /// <summary> /// The word. /// </summary> public readonly string Value; /// <summary> /// Word count offset into document. /// </summary> public readonly int Offset; /// <summary> /// The Xml node containing the word. /// </summary> public readonly XmlNode Node; //--- Constructors --- private XDocWord(string value, int offset, XmlNode node) { this.Value = value; this.Offset = offset; this.Node = node; } //--- Properties --- /// <summary> /// <see langword="True"/> if the node is a text node. /// </summary> public bool IsText { get { return Node is XmlText; } } /// <summary> /// <see langword="True"/> if the parsed contents are an alphanumeric sequence. /// </summary> public bool IsWord { get { return IsText && (Value.Length > 0) && char.IsLetterOrDigit(Value[0]); } } /// <summary> /// XPath to the Node. /// </summary> public string Path { get { List<string> parents = new List<string>(); XmlNode current = Node; switch(Node.NodeType) { case XmlNodeType.Text: parents.Add("#"); current = Node.ParentNode; break; } for(; current != null; current = current.ParentNode) { parents.Add(current.Name); } parents.Reverse(); return string.Join("/", parents.ToArray()); } } //--- Methods --- /// <summary> /// Create a string represenation of the instance. /// </summary> /// <returns></returns> public override string ToString() { switch(Node.NodeType) { case XmlNodeType.Element: if(Value != null) { return Path + ": " + Value; } else { return Path + ": </ " + Node.Name + ">"; } case XmlNodeType.Text: return Path + ": '" + Value + "'"; default: throw new InvalidDataException("unknown node type"); } } } }
// 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. // Do not remove this, it is needed to retain calls to these conditional methods in release builds #define DEBUG using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Diagnostics { /// <summary> /// Provides a set of properties and methods for debugging code. /// </summary> public static partial class Debug { private static readonly object s_lock = new object(); public static bool AutoFlush { get { return true; } set { } } [ThreadStatic] private static int s_indentLevel; public static int IndentLevel { get { return s_indentLevel; } set { s_indentLevel = value < 0 ? 0 : value; } } private static int s_indentSize = 4; public static int IndentSize { get { return s_indentSize; } set { s_indentSize = value < 0 ? 0 : value; } } [System.Diagnostics.Conditional("DEBUG")] public static void Close() { } [System.Diagnostics.Conditional("DEBUG")] public static void Flush() { } [System.Diagnostics.Conditional("DEBUG")] public static void Indent() { IndentLevel++; } [System.Diagnostics.Conditional("DEBUG")] public static void Unindent() { IndentLevel--; } [System.Diagnostics.Conditional("DEBUG")] public static void Print(string message) { Write(message); } [System.Diagnostics.Conditional("DEBUG")] public static void Print(string format, params object[] args) { Write(string.Format(null, format, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition) { Assert(condition, string.Empty, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message) { Assert(condition, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessage) { if (!condition) { string stackTrace; try { stackTrace = new StackTrace(0, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } catch { stackTrace = ""; } WriteLine(FormatAssert(stackTrace, message, detailMessage)); s_ShowDialog(stackTrace, message, detailMessage, "Assertion Failed"); } } internal static void ContractFailure(bool condition, string message, string detailMessage, string failureKindMessage) { if (!condition) { string stackTrace; try { stackTrace = new StackTrace(2, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } catch { stackTrace = ""; } WriteLine(FormatAssert(stackTrace, message, detailMessage)); s_ShowDialog(stackTrace, message, detailMessage, SR.GetResourceString(failureKindMessage)); } } [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message) { Assert(false, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message, string detailMessage) { Assert(false, message, detailMessage); } private static string FormatAssert(string stackTrace, string message, string detailMessage) { string newLine = GetIndentString() + Environment.NewLine; return SR.DebugAssertBanner + newLine + SR.DebugAssertShortMessage + newLine + message + newLine + SR.DebugAssertLongMessage + newLine + detailMessage + newLine + stackTrace; } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args) { Assert(condition, message, string.Format(detailMessageFormat, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message) { Write(message + Environment.NewLine); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message) { lock (s_lock) { if (message == null) { s_WriteCore(string.Empty); return; } if (s_needIndent) { message = GetIndentString() + message; s_needIndent = false; } s_WriteCore(message); if (message.EndsWith(Environment.NewLine)) { s_needIndent = true; } } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value) { WriteLine(value?.ToString()); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value, string category) { WriteLine(value?.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string format, params object[] args) { WriteLine(string.Format(null, format, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message, string category) { if (category == null) { WriteLine(message); } else { WriteLine(category + ":" + message); } } [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value) { Write(value?.ToString()); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message, string category) { if (category == null) { Write(message); } else { Write(category + ":" + message); } } [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value, string category) { Write(value?.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message) { if (condition) { Write(message); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value) { if (condition) { Write(value); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message, string category) { if (condition) { Write(message, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value, string category) { if (condition) { Write(value, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value) { if (condition) { WriteLine(value); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value, string category) { if (condition) { WriteLine(value, category); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string message) { if (condition) { WriteLine(message); } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string message, string category) { if (condition) { WriteLine(message, category); } } private static bool s_needIndent; private static string s_indentString; private static string GetIndentString() { int indentCount = IndentSize * IndentLevel; if (s_indentString?.Length == indentCount) { return s_indentString; } return s_indentString = new string(' ', indentCount); } private sealed class DebugAssertException : Exception { internal DebugAssertException(string stackTrace) : base(Environment.NewLine + stackTrace) { } internal DebugAssertException(string message, string stackTrace) : base(message + Environment.NewLine + Environment.NewLine + stackTrace) { } internal DebugAssertException(string message, string detailMessage, string stackTrace) : base(message + Environment.NewLine + detailMessage + Environment.NewLine + Environment.NewLine + stackTrace) { } } // internal and not readonly so that the tests can swap this out. internal static Action<string, string, string, string> s_ShowDialog = ShowDialog; internal static Action<string> s_WriteCore = WriteCore; } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.IO; namespace Contoso.Compression.Lzma { using RangeCoder; public partial class Decoder : ICoder, ISetDecoderProperties //, Stream { private LZ.OutWindow m_OutWindow = new LZ.OutWindow(); private RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); private BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; private BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; private BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; private BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; private BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; private BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; private BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; private BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); private LenDecoder m_LenDecoder = new LenDecoder(); private LenDecoder m_RepLenDecoder = new LenDecoder(); private LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); private uint m_DictionarySize; private uint m_DictionarySizeCheck; private uint m_PosStateMask; private bool _solid = false; /// <summary> /// Initializes a new instance of the <see cref="Decoder"/> class. /// </summary> public Decoder() { m_DictionarySize = 0xFFFFFFFF; for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } private void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); m_OutWindow.Create(blockSize); } } private void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new ArgumentOutOfRangeException("lp"); if (lc > 8) throw new ArgumentOutOfRangeException("lc"); m_LiteralDecoder.Create(lp, lc); } private void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new ArgumentOutOfRangeException("pb"); uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } private void Init(System.IO.Stream inStream, System.IO.Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= m_PosStateMask; j++) { uint index = (i << Base.kNumPosStatesBitsMax) + j; m_IsMatchDecoders[index].Init(); m_IsRep0LongDecoders[index].Init(); } m_IsRepDecoders[i].Init(); m_IsRepG0Decoders[i].Init(); m_IsRepG1Decoders[i].Init(); m_IsRepG2Decoders[i].Init(); } m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) m_PosDecoders[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); } /// <summary> /// Codes streams. /// </summary> /// <param name="inStream">input Stream.</param> /// <param name="outStream">output Stream.</param> /// <param name="inSize">input Size. -1 if unknown.</param> /// <param name="outSize">output Size. -1 if unknown.</param> /// <param name="progress">callback progress reference.</param> public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress) { Init(inStream, outStream); Base.State state = new Base.State(); state.Init(); uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; ulong nowPos64 = 0; ulong outSize64 = (ulong)outSize; if (nowPos64 < outSize64) { if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) throw new DataErrorException(); state.UpdateChar(); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); m_OutWindow.PutByte(b); nowPos64++; } while (nowPos64 < outSize64) { // ulong next = Math.Min(nowPos64 + (1 << 18), outSize64); // while(nowPos64 < next) { uint posState = (uint)nowPos64 & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { byte prevByte = m_OutWindow.GetByte(0); byte b; if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); else b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); m_OutWindow.PutByte(b); state.UpdateChar(); nowPos64++; } else { uint len; if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) { if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) { if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { state.UpdateShortRep(); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); nowPos64++; continue; } } else { uint distance; if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep1; else { if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state.UpdateRep(); } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state.UpdateMatch(); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } else rep0 = posSlot; } if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) break; throw new DataErrorException(); } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; } } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); } /// <summary> /// Sets the decoder properties. /// </summary> /// <param name="properties">The properties.</param> public void SetDecoderProperties(byte[] properties) { if (properties.Length < 5) throw new InvalidParamException(); int lc = properties[0] % 9; int remainder = properties[0] / 9; int lp = remainder % 5; int pb = remainder / 5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); uint dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((uint)(properties[1 + i])) << (i * 8); SetDictionarySize(dictionarySize); SetLiteralProperties(lp, lc); SetPosBitsProperties(pb); } /// <summary> /// Trains the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns></returns> public bool Train(System.IO.Stream stream) { _solid = true; return m_OutWindow.Train(stream); } //public override bool CanRead { get { return true; }} //public override bool CanWrite { get { return true; }} //public override bool CanSeek { get { return true; }} //public override long Length { get { return 0; }} //public override long Position //{ // get { return 0; } // set { } //} //public override void Flush() { } //public override int Read(byte[] buffer, int offset, int count) //{ // return 0; //} //public override void Write(byte[] buffer, int offset, int count) //{ //} //public override long Seek(long offset, System.IO.SeekOrigin origin) //{ // return 0; //} //public override void SetLength(long value) {} } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using NUnit.Framework; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Positions; namespace QuantConnect.Tests.Common.Securities { /// <summary> /// Provides an implementation of <see cref="IBuyingPowerModel"/> that verifies consistency with /// the <see cref="SecurityPositionGroupBuyingPowerModel"/> /// </summary> public class BuyingPowerModelComparator : IBuyingPowerModel { public SecurityPortfolioManager Portfolio { get; } public IBuyingPowerModel SecurityModel { get; } public IPositionGroupBuyingPowerModel PositionGroupModel { get; } private bool reentry; public BuyingPowerModelComparator( IBuyingPowerModel securityModel, IPositionGroupBuyingPowerModel positionGroupModel, SecurityPortfolioManager portfolio = null, ITimeKeeper timeKeeper = null, IOrderProcessor orderProcessor = null ) { Portfolio = portfolio; SecurityModel = securityModel; PositionGroupModel = positionGroupModel; if (portfolio == null) { var securities = new SecurityManager(timeKeeper ?? new TimeKeeper(DateTime.UtcNow)); Portfolio = new SecurityPortfolioManager(securities, new SecurityTransactionManager(null, securities)); } if (orderProcessor != null) { Portfolio.Transactions.SetOrderProcessor(orderProcessor); } } public decimal GetLeverage(Security security) { return SecurityModel.GetLeverage(security); } public void SetLeverage(Security security, decimal leverage) { SecurityModel.SetLeverage(security, leverage); } public MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetMaintenanceMargin(parameters); if (reentry) { return expected; } reentry = true; var actual = PositionGroupModel.GetMaintenanceMargin(new PositionGroupMaintenanceMarginParameters( Portfolio, new PositionGroup(PositionGroupModel, new Position(parameters.Security, parameters.Quantity)) )); Assert.AreEqual(expected.Value, actual.Value, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaintenanceMargin)}" ); reentry = false; return expected; } public InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetInitialMarginRequirement(parameters); if (reentry) { return expected; } reentry = true; var actual = PositionGroupModel.GetInitialMarginRequirement(new PositionGroupInitialMarginParameters( Portfolio, new PositionGroup(PositionGroupModel, new Position(parameters.Security, parameters.Quantity)) )); Assert.AreEqual(expected.Value, actual.Value, $"{PositionGroupModel.GetType().Name}:{nameof(GetInitialMarginRequirement)}" ); reentry = false; return expected; } public InitialMargin GetInitialMarginRequiredForOrder(InitialMarginRequiredForOrderParameters parameters) { reentry = true; EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetInitialMarginRequiredForOrder(parameters); if (reentry) { return expected; } var actual = PositionGroupModel.GetInitialMarginRequiredForOrder(new PositionGroupInitialMarginForOrderParameters( Portfolio, new PositionGroup(PositionGroupModel, new Position(parameters.Security, parameters.Order.Quantity)), parameters.Order )); Assert.AreEqual(expected.Value, actual.Value, $"{PositionGroupModel.GetType().Name}:{nameof(GetInitialMarginRequiredForOrder)}" ); reentry = false; return expected; } public HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder( HasSufficientBuyingPowerForOrderParameters parameters ) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.HasSufficientBuyingPowerForOrder(parameters); if (reentry) { return expected; } reentry = true; var actual = PositionGroupModel.HasSufficientBuyingPowerForOrder( new HasSufficientPositionGroupBuyingPowerForOrderParameters( Portfolio, new PositionGroup(PositionGroupModel, new Position(parameters.Security, parameters.Order.Quantity)), parameters.Order ) ); Assert.AreEqual(expected.IsSufficient, actual.IsSufficient, $"{PositionGroupModel.GetType().Name}:{nameof(HasSufficientBuyingPowerForOrder)}: " + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); Assert.AreEqual(expected.Reason, actual.Reason, $"{PositionGroupModel.GetType().Name}:{nameof(HasSufficientBuyingPowerForOrder)}" ); reentry = false; return expected; } public GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters ) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetMaximumOrderQuantityForTargetBuyingPower(parameters); if (reentry) { return expected; } reentry = true; var security = parameters.Security; var positionGroup = Portfolio.Positions[new PositionGroupKey(PositionGroupModel, security)]; var actual = PositionGroupModel.GetMaximumLotsForTargetBuyingPower( new GetMaximumLotsForTargetBuyingPowerParameters( parameters.Portfolio, positionGroup, parameters.TargetBuyingPower, parameters.MinimumOrderMarginPortfolioPercentage, parameters.SilenceNonErrorReasons ) ); var lotSize = security.SymbolProperties.LotSize; Assert.AreEqual(expected.IsError, actual.IsError, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForTargetBuyingPower)}: " + $"ExpectedQuantity: {expected.Quantity} ActualQuantity: {actual.NumberOfLots * lotSize} {Environment.NewLine}" + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); // we're not comparing group quantities, which is the number of position lots, but rather the implied // position quantities resulting from having that many lots. var resizedPositionGroup = positionGroup.WithQuantity(actual.NumberOfLots); var position = resizedPositionGroup.GetPosition(security.Symbol); var bpmOrder = new MarketOrder(security.Symbol, expected.Quantity, parameters.Portfolio.Securities.UtcTime); var pgbpmOrder = new MarketOrder(security.Symbol, position.Quantity, parameters.Portfolio.Securities.UtcTime); var bpmOrderValue = bpmOrder.GetValue(security); var pgbpmOrderValue = pgbpmOrder.GetValue(security); var bpmOrderFees = security.FeeModel.GetOrderFee(new OrderFeeParameters(security, bpmOrder)).Value.Amount; var pgbpmOrderFees = security.FeeModel.GetOrderFee(new OrderFeeParameters(security, pgbpmOrder)).Value.Amount; var bpmMarginRequired = bpmOrderValue + bpmOrderFees; var pgbpmMarginRequired = pgbpmOrderValue + pgbpmOrderFees; Assert.AreEqual(expected.Quantity, position.Quantity, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForTargetBuyingPower)}: " + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); Assert.AreEqual(expected.Reason, actual.Reason, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForTargetBuyingPower)}: " + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); reentry = false; return expected; } public GetMaximumOrderQuantityResult GetMaximumOrderQuantityForDeltaBuyingPower( GetMaximumOrderQuantityForDeltaBuyingPowerParameters parameters ) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetMaximumOrderQuantityForDeltaBuyingPower(parameters); if (reentry) { return expected; } reentry = true; var security = parameters.Security; var positionGroup = Portfolio.Positions[new PositionGroupKey(PositionGroupModel, security)]; var actual = PositionGroupModel.GetMaximumLotsForDeltaBuyingPower( new GetMaximumLotsForDeltaBuyingPowerParameters( parameters.Portfolio, positionGroup, parameters.DeltaBuyingPower, parameters.MinimumOrderMarginPortfolioPercentage, parameters.SilenceNonErrorReasons ) ); var lotSize = security.SymbolProperties.LotSize; Assert.AreEqual(expected.IsError, actual.IsError, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForDeltaBuyingPower)}: " + $"ExpectedQuantity: {expected.Quantity} ActualQuantity: {actual.NumberOfLots * lotSize} {Environment.NewLine}" + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); // we're not comparing group quantities, which is the number of position lots, but rather the implied // position quantities resulting from having that many lots. var resizedPositionGroup = positionGroup.WithQuantity(actual.NumberOfLots); var position = resizedPositionGroup.GetPosition(security.Symbol); var bpmOrder = new MarketOrder(security.Symbol, expected.Quantity, parameters.Portfolio.Securities.UtcTime); var pgbpmOrder = new MarketOrder(security.Symbol, position.Quantity, parameters.Portfolio.Securities.UtcTime); var bpmMarginRequired = security.BuyingPowerModel.GetInitialMarginRequirement(security, bpmOrder.Quantity); var pgbpmMarginRequired = PositionGroupModel.GetInitialMarginRequiredForOrder(Portfolio, resizedPositionGroup, pgbpmOrder); var availableBuyingPower = security.BuyingPowerModel.GetBuyingPower(parameters.Portfolio, security, bpmOrder.Direction); Assert.AreEqual(expected.Quantity, position.Quantity, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForDeltaBuyingPower)}: " + $"ExpectedReason: {expected.Reason}{Environment.NewLine}" + $"ActualReason: {actual.Reason}" ); Assert.AreEqual(expected.Reason, actual.Reason, $"{PositionGroupModel.GetType().Name}:{nameof(GetMaximumOrderQuantityForDeltaBuyingPower)}" ); reentry = false; return expected; } public ReservedBuyingPowerForPosition GetReservedBuyingPowerForPosition(ReservedBuyingPowerForPositionParameters parameters) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetReservedBuyingPowerForPosition(parameters); if (reentry) { return expected; } reentry = true; reentry = false; return expected; } public BuyingPower GetBuyingPower(BuyingPowerParameters parameters) { EnsureSecurityExists(parameters.Security); var expected = SecurityModel.GetBuyingPower(parameters); if (reentry) { return expected; } reentry = false; return expected; } private void EnsureSecurityExists(Security security) { if (!Portfolio.Securities.ContainsKey(security.Symbol)) { var timeKeeper = (LocalTimeKeeper) typeof(Security).GetField("_localTimeKeeper", BindingFlags.NonPublic|BindingFlags.Instance).GetValue(security); Portfolio.Securities[security.Symbol] = security; security.SetLocalTimeKeeper(timeKeeper); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using DiagnosticId = String; using LanguageKind = String; [Export(typeof(ICodeFixService))] internal partial class CodeFixService : ICodeFixService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap; private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap; // Shared by project fixers and workspace fixers. private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider; private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap; private ImmutableDictionary<CodeFixProvider, FixAllProviderInfo> _fixAllProviderMap; [ImportingConstructor] public CodeFixService( IDiagnosticAnalyzerService service, [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers, [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders) { _diagnosticService = service; var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages(); var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages(); _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap); _suppressionProvidersMap = GetSupressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap); // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable. _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap); // Per-project fixers _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>(); _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>(); _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r)); _fixAllProviderMap = ImmutableDictionary<CodeFixProvider, FixAllProviderInfo>.Empty; } public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, CancellationToken cancellationToken) { if (document == null || !document.IsOpen()) { return default(FirstDiagnosticResult); } using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { var fullResult = await _diagnosticService.TryGetDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics.Object) { cancellationToken.ThrowIfCancellationRequested(); if (!range.IntersectsWith(diagnostic.TextSpan)) { continue; } // REVIEW: 2 possible designs. // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes. // // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then // I will try the second approach which will be more complex but quicker var hasFix = await ContainsAnyFix(document, diagnostic, cancellationToken).ConfigureAwait(false); if (hasFix) { return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic); } } return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData)); } } public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null; foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic); } var result = new List<CodeFixCollection>(); if (aggregatedDiagnostics != null) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } if (result.Any()) { // sort the result to the order defined by the fixers var priorityMap = _fixerPriorityMap[document.Project.Language].Value; result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1); } if (aggregatedDiagnostics != null) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } return result; } private async Task<List<CodeFixCollection>> AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return result; } ImmutableArray<CodeFixProvider> workspaceFixers; List<CodeFixProvider> projectFixers; var allFixers = new List<CodeFixProvider>(); foreach (var diagnosticId in diagnosticDataCollection.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers)) { allFixers.AddRange(workspaceFixers); } if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers)) { allFixers.AddRange(projectFixers); } } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)).ToImmutableArray(); foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer).Contains(d.Id); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = async (dxs) => { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, span, dxs, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask; await task.ConfigureAwait(false); return fixes; }; await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer, extensionManager, hasFix, getFixes, cancellationToken).ConfigureAwait(false); } return result; } private async Task<List<CodeFixCollection>> AppendSuppressionsAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ISuppressionFixProvider> lazySuppressionProvider; if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null) { return result; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)); Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressed(d); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken); await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, extensionManager, hasFix, getFixes, cancellationToken).ConfigureAwait(false); return result; } private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnosticsWithSameSpan, List<CodeFixCollection> result, object fixer, IExtensionManager extensionManager, Func<Diagnostic, bool> hasFix, Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes, CancellationToken cancellationToken) { var diagnostics = diagnosticsWithSameSpan.Where(d => hasFix(d)).OrderByDescending(d => d.Severity).ToImmutableArray(); if (diagnostics.Length <= 0) { // this can happen for suppression case where all diagnostics can't be suppressed return result; } var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics)).ConfigureAwait(false); if (fixes != null && fixes.Any()) { FixAllCodeActionContext fixAllContext = null; var codeFixProvider = fixer as CodeFixProvider; if (codeFixProvider != null) { // If the codeFixProvider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context. var fixAllProviderInfo = ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, codeFixProvider, FixAllProviderInfo.Create); if (fixAllProviderInfo != null) { fixAllContext = new FixAllCodeActionContext(document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken); } } result = result ?? new List<CodeFixCollection>(); var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext); result.Add(codeFix); } return result; } private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return diagnostics.Select(d => d.ToDiagnostic(tree)); } private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(project); var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); var dxs = diagnostics.Select(d => d.ToDiagnostic(null)); if (includeAllDocumentDiagnostics) { var list = new List<Diagnostic>(); list.AddRange(dxs); foreach (var document in project.Documents) { var docDiagnsotics = await GetDocumentDiagnosticsAsync(document, diagnosticIds, cancellationToken).ConfigureAwait(false); list.AddRange(docDiagnsotics); } return list; } else { return dxs; } } private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, CancellationToken cancellationToken) { // TODO: We don't return true here if the only available fixes are suppressions. // This is to avoid the problem where lightbulb would show up for every green warning // squiggle in the editor thereby diluting the promise of the light bulb from // "I have a fix" to "I have some action". This is temporary until the editor team exposes // some mechanism (e.g. a faded out lightbulb) that would allow us to say "I have an action // but not a fix". ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; List<CodeFixProvider> projectFixers = null; Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers); } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var dx = diagnostic.ToDiagnostic(tree); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false); if (!fixes.Any()) { continue; } return true; } return false; } private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>(); private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer) { return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds); } private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage) { var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>(); foreach (var languageKindAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() => { var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>(); foreach (var fixer in languageKindAndFixers.Value) { foreach (var id in this.GetFixableDiagnosticIds(fixer.Value)) { if (string.IsNullOrWhiteSpace(id)) { continue; } var list = mutableMap.GetOrAdd(id, s_createList); list.Add(fixer.Value); } } var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>(); foreach (var diagnosticIdAndFixers in mutableMap) { immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty()); } return immutableMap.ToImmutable(); }, isThreadSafe: true); fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap); } return fixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSupressionProvidersPerLanguageMap( Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage) { var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>(); foreach (var languageKindAndFixers in suppressionProvidersPerLanguage) { var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value); suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap); } return suppressionFixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage) { var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>(); foreach (var languageAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() => { var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>(); var fixers = ExtensionOrderer.Order(languageAndFixers.Value); for (var i = 0; i < fixers.Count; i++) { priorityMap.Add(fixers[i].Value, i); } return priorityMap.ToImmutable(); }, isThreadSafe: true); languageMap.Add(languageAndFixers.Key, lazyMap); } return languageMap.ToImmutable(); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project) { return _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project)); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project) { ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null; foreach (var reference in project.AnalyzerReferences) { var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider); foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language)) { var fixableIds = this.GetFixableDiagnosticIds(fixer); foreach (var id in fixableIds) { if (string.IsNullOrWhiteSpace(id)) { continue; } builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>(); var list = builder.GetOrAdd(id, s_createList); list.Add(fixer); } } } if (builder == null) { return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty; } return builder.ToImmutable(); } } }
// 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.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { // System.Globalization.ThaiBuddhistCalendar.GetWeekOfYear(DateTime,CalendarWeekRule,DayOfWeek) public class ThaiBuddhistCalendarGetWeekOfYear { private readonly int[] _DAYS_PER_MONTHS_IN_LEAP_YEAR = new int[13] { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private readonly int[] _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR = new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive Tests // PosTest1: Verify the DateTime is a random Date [Fact] public void PosTest1() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); Random rand = new Random(-55); int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year); int month = rand.Next(1, 12); int day; if (IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); for (int i = 0; i < 7; i++) { for (int j = 0; j < 3; j++) { int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); Assert.Equal(actualWeek, resultWeek); } } } // PosTest2: Verify the DateTime is ThaiBuddhistCalendar MaxSupportDateTime [Fact] public void PosTest2() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); DateTime dt = tbc.MaxSupportedDateTime; for (int i = 0; i < 7; i++) { for (int j = 0; j < 3; j++) { int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); Assert.Equal(actualWeek, resultWeek); } } } // PosTest3: Verify the DateTime is ThaiBuddhistCalendar MinSupportedDateTime [Fact] public void PosTest3() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); DateTime dt = tbc.MinSupportedDateTime; dt = dt.AddYears(543); for (int i = 0; i < 7; i++) { for (int j = 0; j < 3; j++) { int actualWeek = getWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); int resultWeek = tbc.GetWeekOfYear(dt, (CalendarWeekRule)j, (DayOfWeek)i); Assert.Equal(actualWeek, resultWeek); } } } // PosTest4: Verify the DateTime is the last day of the year [Fact] public void PosTest4() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); System.Globalization.Calendar gc = new GregorianCalendar(); Random rand = new Random(-55); int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year); int month = 12; int day = 31; int actualWeek = 53; DateTime dt = new DateTime(year, month, day); CultureInfo myCI = new CultureInfo("th-TH"); int resultWeek = tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek); Assert.Equal(actualWeek, resultWeek); } #endregion #region Negative Tests // NegTest1: firstDayOfWeek is outside the range supported by the calendar [Fact] public void NegTest1() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); Random rand = new Random(-55); int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year); int month = rand.Next(1, 12); int day; if (IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); CultureInfo myCI = new CultureInfo("th-TH"); Assert.Throws<ArgumentOutOfRangeException>(() => { tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, (DayOfWeek)7); }); Assert.Throws<ArgumentOutOfRangeException>(() => { tbc.GetWeekOfYear(dt, myCI.DateTimeFormat.CalendarWeekRule, (DayOfWeek)(-1)); }); } // NegTest2: CalendarWeekRule is outside the range supported by the calendar [Fact] public void NegTest2() { System.Globalization.Calendar tbc = new ThaiBuddhistCalendar(); Random rand = new Random(-55); int year = rand.Next(tbc.MinSupportedDateTime.Year, tbc.MaxSupportedDateTime.Year); int month = rand.Next(1, 12); int day; if (IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); CultureInfo myCI = new CultureInfo("th-TH"); Assert.Throws<ArgumentOutOfRangeException>(() => { tbc.GetWeekOfYear(dt, (CalendarWeekRule)3, myCI.DateTimeFormat.FirstDayOfWeek); }); Assert.Throws<ArgumentOutOfRangeException>(() => { tbc.GetWeekOfYear(dt, (CalendarWeekRule)(-1), myCI.DateTimeFormat.FirstDayOfWeek); }); } #endregion #region Helper Methods internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { System.Globalization.Calendar gc = new GregorianCalendar(); int dayOfYear = gc.GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)gc.GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; //BCLDebug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } internal int GetWeekOfYearFullDays(DateTime time, CalendarWeekRule rule, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; System.Globalization.Calendar gc = new GregorianCalendar(); int dayOfYear = gc.GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)gc.GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Substract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. offset -= 7; } // Calculate the day of year for specified time by taking offset into account. day = dayOfYear - offset; if (day >= 0) { // If the day of year value is greater than zero, get the week of year. return (day / 7 + 1); } // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), rule, firstDayOfWeek, fullDays)); } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. private int getWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException(); } switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, rule, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, rule, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException(); } private bool IsLeapYear(int year) { return ((year % 4) == 0) && !(((year % 100) == 0) || ((year % 400) == 0)); } #endregion } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.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 Manos.Http; using Manos.Http.Testing; using Manos.Routing.Testing; using Manos.ShouldExt; using NUnit.Framework; namespace Manos.Routing.Tests { [TestFixture] public class RouteHandlerTest { public class TestApp : ManosApp { public TestApp() { Route("/TESTING", new TestModule()); Get("", ctx => { }); } #region Nested type: TestModule public class TestModule : ManosModule { [Get("/Route1", "/Route1/")] public void Route1(IManosContext ctx) { ctx.Response.Write("Route1"); ctx.Response.End(); } [Get("/Route2a/{age}/{name}")] public void Route2a(IManosContext ctx, String name, int age) { ctx.Response.Write("(R2a) Hello '{0}', you are '{1}'", name, age); ctx.Response.End(); } [Get("/Route2b/{name}/{age}")] public void Route2b(IManosContext ctx, String name, int age) { ctx.Response.Write("(R2b) Hello '{0}', you are '{1}'", name, age); ctx.Response.End(); } [Get("/Route3/(?<name>.+?)/(?<age>.+?)")] public void Route3(IManosContext ctx, String name, int age) { ctx.Response.Write("'{0}', you are '{1}'", name, age); ctx.Response.End(); } } #endregion } private static void FakeAction(IManosContext ctx) { } private static void FakeAction2(IManosContext ctx) { } [Test] public void Find_PartialMatchAtBeginningOfChildlessHandler_ReturnsProperRoute() { IMatchOperation fooOp = MatchOperationFactory.Create("foo", MatchType.String); IMatchOperation foobarOp = MatchOperationFactory.Create("foobar", MatchType.String); var rh_bad = new RouteHandler(fooOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction)); var rh_good = new RouteHandler(foobarOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction2)); var rh = new RouteHandler(); rh.Add(rh_bad); rh.Add(rh_good); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foobar"); IManosTarget res = rh.Find(request); Assert.AreEqual(rh_good.Target, res); } [Test] public void Find_PartialMatchAtBeginningOfHandlerWithChildren_ReturnsProperRoute() { IMatchOperation fooOp = MatchOperationFactory.Create("foo", MatchType.String); IMatchOperation foobarOp = MatchOperationFactory.Create("foobar", MatchType.String); IMatchOperation blahOp = MatchOperationFactory.Create("blah", MatchType.String); var rh_bad = new RouteHandler(fooOp, HttpMethod.HTTP_GET); var rh_good = new RouteHandler(foobarOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction2)); var rh = new RouteHandler(); rh_bad.Children.Add(new RouteHandler(blahOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction))); rh.Add(rh_bad); rh.Add(rh_good); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foobar"); IManosTarget res = rh.Find(request); Assert.AreEqual(rh_good.Target, res); } [Test] public void HasPatternsTest() { IMatchOperation fooOp = MatchOperationFactory.Create("foo", MatchType.Regex); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET); Assert.IsTrue(rh.HasPatterns, "a1"); //var request = new MockHttpRequest (HttpMethod.HTTP_GET, "foo"); //Assert.IsNull (rh.Find (request), "a2"); IMatchOperation foobarOp = MatchOperationFactory.Create("foobar", MatchType.String); rh.Add(new RouteHandler(foobarOp, HttpMethod.HTTP_GET)); Assert.IsTrue(rh.HasPatterns, "a3"); rh.MatchOps = null; Assert.IsFalse(rh.HasPatterns, "a4"); } [Test] public void ImplicitRouteWorksWithModuleOnCustomApp() { var t = new TestApp(); var req = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route1"); //var res = new MockHttpResponse (); var txn = new MockHttpTransaction(req, new MockHttpResponse()); t.HandleTransaction(t, txn); Assert.AreEqual("Route1", txn.ResponseString); // var t2 = new TestApp (); req = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route1/"); // var res2 = new MockHttpResponse (); txn = new MockHttpTransaction(req, new MockHttpResponse()); t.HandleTransaction(t, txn); // Assert.AreEqual("Route1", txn.ResponseString); } [Test] public void RouteWorksWithNamedParametersInModuleOnCustomApp() { var t = new TestApp(); var req = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route2a/29/Andrew"); var txn = new MockHttpTransaction(req, new MockHttpResponse()); t.HandleTransaction(t, txn); Assert.AreEqual("(R2a) Hello 'Andrew', you are '29'", txn.ResponseString); req = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route2b/Andrew/29"); txn = new MockHttpTransaction(req, new MockHttpResponse()); t.HandleTransaction(t, txn); Assert.AreEqual("(R2b) Hello 'Andrew', you are '29'", txn.ResponseString); } [Test] public void RouteWorksWithRegexParamsInModuleOnCustomApp() { var t = new TestApp(); var req = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route3/Andrew/29"); var res = new MockHttpResponse(); var txn = new MockHttpTransaction(req, new MockHttpResponse()); t.HandleTransaction(t, txn); Assert.AreEqual("'Andrew', you are '29'", txn.ResponseString); var t2 = new TestApp(); var req2 = new MockHttpRequest(HttpMethod.HTTP_GET, "/TESTING/Route3/Andrew/29/"); var res2 = new MockHttpResponse(); var txn2 = new MockHttpTransaction(req2, res2); t2.HandleTransaction(t2, txn2); Assert.AreEqual("'Andrew', you are '29'", txn2.ResponseString); } [Test] public void TestChangePatterns() { // // Ensure that changing the patterns property works. // This is a bit of an edge case because internally // the patterns strings are cached as an array of // regexes. // IMatchOperation fooOp = MatchOperationFactory.Create("^foo", MatchType.Regex); var target = new MockManosTarget(); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET, target); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo"); Assert.AreEqual(target, rh.Find(request), "sanity-1"); rh.MatchOps[0] = MatchOperationFactory.Create("baz", MatchType.Regex); Assert.IsNull(rh.Find(request), "sanity-2"); request = new MockHttpRequest(HttpMethod.HTTP_GET, "baz"); Assert.AreEqual(target, rh.Find(request), "changed"); } [Test] public void TestNoChildrenOfTarget() { IMatchOperation fooOp = MatchOperationFactory.Create("foo", MatchType.String); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction)); Should.Throw<InvalidOperationException>(() => rh.Children.Add(new RouteHandler(fooOp, HttpMethod.HTTP_POST))); } [Test] public void TestSetPatternsNull() { IMatchOperation fooOp = MatchOperationFactory.Create("^foo", MatchType.Regex); var target = new MockManosTarget(); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET, target); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo"); Assert.AreEqual(target, rh.Find(request), "sanity-1"); rh.MatchOps = null; Assert.IsNull(rh.Find(request), "is null"); } [Test] public void TestStrMatch() { IMatchOperation op = MatchOperationFactory.Create("^foo", MatchType.Regex); var target = new MockManosTarget(); var rh = new RouteHandler(op, HttpMethod.HTTP_GET, target); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo"); Assert.AreEqual(target, rh.Find(request), "should-match"); request = new MockHttpRequest(HttpMethod.HTTP_GET, "garbage-foo"); Assert.IsNull(rh.Find(request), "garbage-input"); } [Test] public void TestStrMatchDeep() { IMatchOperation fooOp = MatchOperationFactory.Create("foo/", MatchType.String); IMatchOperation barOp = MatchOperationFactory.Create("bar", MatchType.String); var target = new MockManosTarget(); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET) { new RouteHandler(barOp, HttpMethod.HTTP_GET, target), }; var request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo/bar"); Assert.AreEqual(target, rh.Find(request)); request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo/foo"); Assert.IsNull(rh.Find(request), "repeate-input"); request = new MockHttpRequest(HttpMethod.HTTP_GET, "foo/badbar"); Assert.IsNull(rh.Find(request), "matched-input"); } [Test] public void UriParamsTest() { IMatchOperation fooOp = MatchOperationFactory.Create("(?<name>.+)", MatchType.Regex); var rh = new RouteHandler(fooOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction)); var request = new MockHttpRequest(HttpMethod.HTTP_GET, "hello"); Should.NotBeNull(rh.Find(request), "target"); Should.NotBeNull(request.UriData, "uri-data"); Assert.AreEqual("hello", request.UriData["name"]); } [Test] public void UriParamsTestDeep() { IMatchOperation animalOp = MatchOperationFactory.Create("(?<animal>.+)/", MatchType.Regex); IMatchOperation nameOp = MatchOperationFactory.Create("(?<name>.+)", MatchType.Regex); var rh = new RouteHandler(animalOp, HttpMethod.HTTP_GET) { new RouteHandler(nameOp, HttpMethod.HTTP_GET, new ActionTarget(FakeAction)), }; var request = new MockHttpRequest(HttpMethod.HTTP_GET, "dog/roxy"); Should.NotBeNull(rh.Find(request), "target"); Should.NotBeNull(request.UriData, "uri-data"); Assert.AreEqual("dog", request.UriData["animal"]); Assert.AreEqual("roxy", request.UriData["name"]); } } }
#if UNITY_EDITOR using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using System; using System.IO; using System.Reflection; namespace TNRD.Automatron.Editor.Serialization { public class Deserializer { public static T Deserialize<T>( string b64 ) { var buffer = Convert.FromBase64String( b64 ); return Deserialize<T>( buffer ); } public static T Deserialize<T>( byte[] buffer ) { var stream = new MemoryStream( buffer ); var reader = new BinaryReader( stream ); var deserializer = new Deserializer(); var deserializedObject = deserializer.DeserializeClass( reader ); var value = deserializer.ReadClass( deserializedObject ); return (T)value; } public static object Deserialize( string b64, Type type ) { var buffer = Convert.FromBase64String( b64 ); return Deserialize( buffer, type ); } public static object Deserialize( byte[] buffer, Type type ) { var stream = new MemoryStream( buffer ); var reader = new BinaryReader( stream ); var deserializer = new Deserializer(); var deserializedObject = deserializer.DeserializeClass( reader ); var value = deserializer.ReadClass( deserializedObject ); return Convert.ChangeType( value, type ); } #region Reading private Dictionary<int, object> deserializedObjects = new Dictionary<int, object>(); private object ReadClass( SerializedClass value ) { if ( value.IsNull ) return null; var type = Type.GetType( value.Type ); object instance = null; if ( value.IsReference ) { if ( deserializedObjects.ContainsKey( value.ID ) ) { return deserializedObjects[value.ID]; } } try { instance = Activator.CreateInstance( type, true ); } catch ( MissingMethodException ) { // No constructor deserializedObjects.Add( value.ID, null ); return null; } var fields = SerializationHelper.GetFields( type, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic ) .Where( f => ( f.IsPublic && f.GetCustomAttributes( typeof( IgnoreSerializationAttribute ), false ).Length == 0 ) || ( f.IsPrivate && f.GetCustomAttributes( typeof( RequireSerializationAttribute ), false ).Length == 1 ) ) .OrderBy( f => f.Name ).ToList(); var properties = SerializationHelper.GetProperties( type, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic ) .Where( p => p.CanRead && p.CanWrite ) .Where( p => p.GetCustomAttributes( typeof( IgnoreSerializationAttribute ), false ).Length == 0 ) .OrderBy( p => p.Name ).ToList(); foreach ( var item in value.Values ) { var name = item.Key.Substring( 0, item.Key.IndexOf( '|' ) ); object tValue = Read( item.Value ); var field = fields.Where( f => f.Name == name ).FirstOrDefault(); if ( field != null ) { fields.Remove( field ); try { field.SetValue( instance, tValue ); } catch ( Exception e ) { Debug.LogException( e ); } continue; } var property = properties.Where( p => p.Name == name ).FirstOrDefault(); if ( property != null ) { properties.Remove( property ); try { property.SetValue( instance, tValue, null ); } catch ( Exception e ) { Debug.LogException( e ); } continue; } } if ( instance is FakeType ) { var ft = (FakeType)instance; var v = ft.GetValue(); deserializedObjects.Add( value.ID, v ); instance = v; } else if ( instance is FakeAsset ) { var fa = (FakeAsset)instance; var v = fa.GetValue(); deserializedObjects.Add( value.ID, v ); instance = v; } else { deserializedObjects.Add( value.ID, instance ); } return instance; } private object ReadEnum( SerializedEnum value ) { return value.Value; } private object ReadList( SerializedList value ) { var type = Type.GetType( value.Type ); IList instance = null; if ( type.IsArray() ) { instance = Array.CreateInstance( type.GetElementType() ?? typeof( object ), value.Values.Count ); for ( int i = 0; i < value.Values.Count; i++ ) { var item = value.Values[i]; instance[i] = Read( item ); } } else { instance = (IList)Activator.CreateInstance( type ); foreach ( var item in value.Values ) { instance.Add( Read( item ) ); } } return instance; } private object ReadPrimitive( SerializedPrimitive value ) { return value.Value; } private object Read( SerializedBase item ) { switch ( item.Mode ) { case ESerializableMode.Primitive: return ReadPrimitive( (SerializedPrimitive)item ); case ESerializableMode.Enum: return ReadEnum( (SerializedEnum)item ); case ESerializableMode.List: return ReadList( (SerializedList)item ); case ESerializableMode.Class: return ReadClass( (SerializedClass)item ); default: return null; } } #endregion #region Deserializing private SerializedBase DeserializeDefaults( BinaryReader reader ) { var s = new SerializedBase( 0, "" ); s.ID = reader.ReadInt32(); s.IsNull = reader.ReadBoolean(); s.IsReference = reader.ReadBoolean(); s.Mode = (ESerializableMode)reader.ReadInt32(); s.Type = reader.ReadString(); return s; } private SerializedClass DeserializeClass( BinaryReader reader ) { var value = new SerializedClass( DeserializeDefaults( reader ) ); var count = reader.ReadInt32(); for ( int i = 0; i < count; i++ ) { var name = reader.ReadString(); var mode = (ESerializableMode)reader.ReadInt32(); switch ( mode ) { case ESerializableMode.Primitive: value.Add( name, DeserializePrimitive( reader ) ); break; case ESerializableMode.Enum: value.Add( name, DeserializeEnum( reader ) ); break; case ESerializableMode.List: value.Add( name, DeserializeList( reader ) ); break; case ESerializableMode.Class: value.Add( name, DeserializeClass( reader ) ); break; default: break; } } return value; } private SerializedEnum DeserializeEnum( BinaryReader reader ) { var value = new SerializedEnum( DeserializeDefaults( reader ) ); value.Value = reader.ReadInt32(); return value; } private SerializedList DeserializeList( BinaryReader reader ) { var value = new SerializedList( DeserializeDefaults( reader ) ); var count = reader.ReadInt32(); for ( int i = 0; i < count; i++ ) { var mode = (ESerializableMode)reader.ReadInt32(); switch ( mode ) { case ESerializableMode.Primitive: value.Add( DeserializePrimitive( reader ) ); break; case ESerializableMode.Enum: value.Add( DeserializeEnum( reader ) ); break; case ESerializableMode.List: value.Add( DeserializeList( reader ) ); break; case ESerializableMode.Class: value.Add( DeserializeClass( reader ) ); break; default: break; } } return value; } private SerializedPrimitive DeserializePrimitive( BinaryReader reader ) { var value = new SerializedPrimitive( DeserializeDefaults( reader ) ); var type = Type.GetType( value.Type ); if ( type == typeof( bool ) ) { value.Value = reader.ReadBoolean(); } else if ( type == typeof( byte ) ) { value.Value = reader.ReadByte(); } else if ( type == typeof( char ) ) { value.Value = reader.ReadChar(); } else if ( type == typeof( decimal ) ) { value.Value = reader.ReadDecimal(); } else if ( type == typeof( double ) ) { value.Value = reader.ReadDouble(); } else if ( type == typeof( float ) ) { value.Value = reader.ReadSingle(); } else if ( type == typeof( int ) ) { value.Value = reader.ReadInt32(); } else if ( type == typeof( long ) ) { value.Value = reader.ReadInt64(); } else if ( type == typeof( sbyte ) ) { value.Value = reader.ReadSByte(); } else if ( type == typeof( short ) ) { value.Value = reader.ReadInt16(); } else if ( type == typeof( string ) ) { value.Value = reader.ReadString(); } else if ( type == typeof( uint ) ) { value.Value = reader.ReadUInt32(); } else if ( type == typeof( ulong ) ) { value.Value = reader.ReadUInt64(); } else if ( type == typeof( ushort ) ) { value.Value = reader.ReadUInt16(); } else { Debug.LogErrorFormat( "Found an unknown primitive: {0}", type.Name ); } return value; } #endregion } } #endif
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- if ( isObject( moveMap ) ) moveMap.delete(); new ActionMap(moveMap); //------------------------------------------------------------------------------ // Non-remapable binds //------------------------------------------------------------------------------ function escapeFromGame() { if ( $Server::ServerType $= "SinglePlayer" ) MessageBoxYesNo( "Exit", "Exit from this Mission?", "disconnect();", ""); else MessageBoxYesNo( "Disconnect", "Disconnect from the server?", "disconnect();", ""); } moveMap.bindCmd(keyboard, "escape", "", "handleEscape();"); //------------------------------------------------------------------------------ // Movement Keys //------------------------------------------------------------------------------ $movementSpeed = 1; // m/s function setSpeed(%speed) { if(%speed) $movementSpeed = %speed; } function moveleft(%val) { $mvLeftAction = %val * $movementSpeed; } function moveright(%val) { $mvRightAction = %val * $movementSpeed; } function moveforward(%val) { $mvForwardAction = %val * $movementSpeed; } function movebackward(%val) { $mvBackwardAction = %val * $movementSpeed; } function moveup(%val) { %object = ServerConnection.getControlObject(); if(%object.isInNamespaceHierarchy("Camera")) $mvUpAction = %val * $movementSpeed; } function movedown(%val) { %object = ServerConnection.getControlObject(); if(%object.isInNamespaceHierarchy("Camera")) $mvDownAction = %val * $movementSpeed; } function turnLeft( %val ) { $mvYawRightSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function turnRight( %val ) { $mvYawLeftSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function panUp( %val ) { $mvPitchDownSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function panDown( %val ) { $mvPitchUpSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function getMouseAdjustAmount(%val) { // based on a default camera FOV of 90' return(%val * ($cameraFov / 90) * 0.01) * $pref::Input::LinkMouseSensitivity; } function getGamepadAdjustAmount(%val) { // based on a default camera FOV of 90' return(%val * ($cameraFov / 90) * 0.01) * 10.0; } function yaw(%val) { %yawAdj = getMouseAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01); %yawAdj *= 0.5; } $mvYaw += %yawAdj; } function pitch(%val) { %pitchAdj = getMouseAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01); %pitchAdj *= 0.5; } $mvPitch += %pitchAdj; } function jump(%val) { $mvTriggerCount2++; } function gamePadMoveX( %val ) { $mvXAxis_L = %val; } function gamePadMoveY( %val ) { $mvYAxis_L = %val; } function gamepadYaw(%val) { %yawAdj = getGamepadAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01); %yawAdj *= 0.5; } if(%yawAdj > 0) { $mvYawLeftSpeed = %yawAdj; $mvYawRightSpeed = 0; } else { $mvYawLeftSpeed = 0; $mvYawRightSpeed = -%yawAdj; } } function gamepadPitch(%val) { %pitchAdj = getGamepadAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01); %pitchAdj *= 0.5; } if(%pitchAdj > 0) { $mvPitchDownSpeed = %pitchAdj; $mvPitchUpSpeed = 0; } else { $mvPitchDownSpeed = 0; $mvPitchUpSpeed = -%pitchAdj; } } moveMap.bind( keyboard, a, moveleft ); moveMap.bind( keyboard, d, moveright ); moveMap.bind( keyboard, left, moveleft ); moveMap.bind( keyboard, right, moveright ); moveMap.bind( keyboard, w, moveforward ); moveMap.bind( keyboard, s, movebackward ); moveMap.bind( keyboard, up, moveforward ); moveMap.bind( keyboard, down, movebackward ); moveMap.bind( keyboard, e, moveup ); moveMap.bind( keyboard, c, movedown ); moveMap.bind( keyboard, space, jump ); moveMap.bind( mouse, xaxis, yaw ); moveMap.bind( mouse, yaxis, pitch ); moveMap.bind( gamepad, thumbrx, "D", "-0.23 0.23", gamepadYaw ); moveMap.bind( gamepad, thumbry, "D", "-0.23 0.23", gamepadPitch ); moveMap.bind( gamepad, thumblx, "D", "-0.23 0.23", gamePadMoveX ); moveMap.bind( gamepad, thumbly, "D", "-0.23 0.23", gamePadMoveY ); moveMap.bind( gamepad, btn_a, jump ); moveMap.bindCmd( gamepad, btn_back, "disconnect();", "" ); moveMap.bindCmd(gamepad, dpadl, "toggleLightColorViz();", ""); moveMap.bindCmd(gamepad, dpadu, "toggleDepthViz();", ""); moveMap.bindCmd(gamepad, dpadd, "toggleNormalsViz();", ""); moveMap.bindCmd(gamepad, dpadr, "toggleLightSpecularViz();", ""); //------------------------------------------------------------------------------ // Mouse Trigger //------------------------------------------------------------------------------ function mouseFire(%val) { $mvTriggerCount0++; } function altTrigger(%val) { $mvTriggerCount1++; } moveMap.bind( mouse, button0, mouseFire ); moveMap.bind( mouse, button1, altTrigger ); //------------------------------------------------------------------------------ // Gamepad Trigger //------------------------------------------------------------------------------ function gamepadFire(%val) { if(%val > 0.1 && !$gamepadFireTriggered) { $gamepadFireTriggered = true; $mvTriggerCount0++; } else if(%val <= 0.1 && $gamepadFireTriggered) { $gamepadFireTriggered = false; $mvTriggerCount0++; } } function gamepadAltTrigger(%val) { if(%val > 0.1 && !$gamepadAltTriggerTriggered) { $gamepadAltTriggerTriggered = true; $mvTriggerCount1++; } else if(%val <= 0.1 && $gamepadAltTriggerTriggered) { $gamepadAltTriggerTriggered = false; $mvTriggerCount1++; } } moveMap.bind(gamepad, triggerr, gamepadFire); moveMap.bind(gamepad, triggerl, gamepadAltTrigger); //------------------------------------------------------------------------------ // Zoom and FOV functions //------------------------------------------------------------------------------ if($Player::CurrentFOV $= "") $Player::CurrentFOV = $pref::Player::DefaultFOV / 2; // toggleZoomFOV() works by dividing the CurrentFOV by 2. Each time that this // toggle is hit it simply divides the CurrentFOV by 2 once again. If the // FOV is reduced below a certain threshold then it resets to equal half of the // DefaultFOV value. This gives us 4 zoom levels to cycle through. function toggleZoomFOV() { $Player::CurrentFOV = $Player::CurrentFOV / 2; if($Player::CurrentFOV < 5) resetCurrentFOV(); if(ServerConnection.zoomed) setFOV($Player::CurrentFOV); else { setFov(ServerConnection.getControlCameraDefaultFov()); } } function resetCurrentFOV() { $Player::CurrentFOV = ServerConnection.getControlCameraDefaultFov() / 2; } function turnOffZoom() { ServerConnection.zoomed = false; setFov(ServerConnection.getControlCameraDefaultFov()); // Rather than just disable the DOF effect, we want to set it to the level's // preset values. //DOFPostEffect.disable(); ppOptionsUpdateDOFSettings(); } function setZoomFOV(%val) { if(%val) toggleZoomFOV(); } function toggleZoom(%val) { if (%val) { ServerConnection.zoomed = true; setFov($Player::CurrentFOV); DOFPostEffect.setAutoFocus( true ); DOFPostEffect.setFocusParams( 0.5, 0.5, 50, 500, -5, 5 ); DOFPostEffect.enable(); } else { turnOffZoom(); } } moveMap.bind(keyboard, f, setZoomFOV); moveMap.bind(keyboard, r, toggleZoom); moveMap.bind( gamepad, btn_b, toggleZoom ); //------------------------------------------------------------------------------ // Camera & View functions //------------------------------------------------------------------------------ function toggleFreeLook( %val ) { if ( %val ) $mvFreeLook = true; else $mvFreeLook = false; } function toggleFirstPerson(%val) { if (%val) { ServerConnection.setFirstPerson(!ServerConnection.isFirstPerson()); } } function toggleCamera(%val) { if (%val) commandToServer('ToggleCamera'); } moveMap.bind( keyboard, z, toggleFreeLook ); moveMap.bind(keyboard, tab, toggleFirstPerson ); moveMap.bind(keyboard, "alt c", toggleCamera); moveMap.bind( gamepad, btn_back, toggleCamera ); //------------------------------------------------------------------------------ // Demo recording functions //------------------------------------------------------------------------------ function startRecordingDemo( %val ) { if ( %val ) startDemoRecord(); } function stopRecordingDemo( %val ) { if ( %val ) stopDemoRecord(); } moveMap.bind( keyboard, F3, startRecordingDemo ); moveMap.bind( keyboard, F4, stopRecordingDemo ); //------------------------------------------------------------------------------ // Theora Video Capture (Records a movie file) //------------------------------------------------------------------------------ function toggleMovieRecording(%val) { if (!%val) return; %movieEncodingType = "THEORA"; // Valid encoder values are "PNG" and "THEORA" (default). %movieFPS = 30; // video capture frame rate. if (!$RecordingMovie) { // locate a non-existent filename to use for(%i = 0; %i < 1000; %i++) { %num = %i; if(%num < 10) %num = "0" @ %num; if(%num < 100) %num = "0" @ %num; %filePath = "movies/movie" @ %num; if(!isfile(%filePath)) break; } if(%i == 1000) return; // Start the movie recording recordMovie(%filePath, %movieFPS, %movieEncodingType); } else { // Stop the current recording stopMovie(); } } // Key binding works at any time and not just while in a game. GlobalActionMap.bind(keyboard, "alt m", toggleMovieRecording); //------------------------------------------------------------------------------ // Helper Functions //------------------------------------------------------------------------------ function dropCameraAtPlayer(%val) { if (%val) commandToServer('dropCameraAtPlayer'); } function dropPlayerAtCamera(%val) { if (%val) commandToServer('DropPlayerAtCamera'); } moveMap.bind(keyboard, "F8", dropCameraAtPlayer); moveMap.bind(keyboard, "F7", dropPlayerAtCamera); function bringUpOptions(%val) { if (%val) Canvas.pushDialog(OptionsDlg); } GlobalActionMap.bind(keyboard, "ctrl o", bringUpOptions); //------------------------------------------------------------------------------ // Debugging Functions //------------------------------------------------------------------------------ function showMetrics(%val) { if(%val) metrics("fps gfx shadow sfx terrain groundcover forest net"); } GlobalActionMap.bind(keyboard, "ctrl F2", showMetrics); //------------------------------------------------------------------------------ // // Start profiler by pressing ctrl f3 // ctrl f3 - starts profile that will dump to console and file // function doProfile(%val) { if (%val) { // key down -- start profile echo("Starting profile session..."); profilerReset(); profilerEnable(true); } else { // key up -- finish off profile echo("Ending profile session..."); profilerDumpToFile("profilerDumpToFile" @ getSimTime() @ ".txt"); profilerEnable(false); } } GlobalActionMap.bind(keyboard, "ctrl F3", doProfile); //------------------------------------------------------------------------------ // Misc. //------------------------------------------------------------------------------ GlobalActionMap.bind(keyboard, "tilde", toggleConsole); GlobalActionMap.bindCmd(keyboard, "alt k", "cls();",""); GlobalActionMap.bindCmd(keyboard, "alt enter", "", "Canvas.attemptFullscreenToggle();");
// GameFont.cs using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; namespace GameFonts { public class GameFont { // useful constants //protected static readonly uint ROW_COLUMN_MASK = 0xFF000000; ////protected static readonly uint CHAR_MASK = 0x0000FFFF; //protected static readonly uint CHAR_MASK = 0x00FFFF00; ////protected static readonly uint MAGIC_MASK = 0xFFFF0000; ////protected static readonly uint MAGIC_NUMBER = 0xC0DE0000; //protected static readonly uint MAGIC_MASK = 0xFF0000FF; //protected static readonly uint MAGIC_NUMBER = 0xC00000DE; protected static readonly char INVALID_CHAR = '\xFFFF'; // don't allow creating an instance with the new operator private GameFont() { } // the height of the text, in pixels protected int _fontHeight = 0; public int FontHeight { get { return _fontHeight; } } // the ascent of the font, in pixels. // difference in y location between top of glyph and the // baseline of the glyph protected int _fontAscent = 0; public int FontAscent { get { return _fontAscent; } } // useful in debugger to see why the font didn't initialize private List<string> _messages = new List<string>(); public string[] ErrorMessages { get { return _messages.ToArray(); } } protected void AddMessage(string msg) { _messages.Add(msg); } // the texture that holds the glyphs private Texture2D _texture = null; public Texture2D Texture { get { return _texture; } set { _texture = value; } } // a collection of glyph descriptors, indexed by unicode char private Dictionary<char, GlyphDescriptor> _descriptors = new Dictionary<char, GlyphDescriptor>(); // given a texture with encoded glyphs, return a BitmapFont object public static GameFont FromTexture2D(Texture2D texture) { // new instance placeholder GameFont font = null; // first, make sure it's a valid texture if (texture == null) { throw new GameFontException("Texture2D cannot be null."); } else { // try to extract the glyphs from the texture font = new GameFont(); font.Texture = texture; font.ExtractGlyphDescriptors(); } // return the fruits of our labor return font; } // interpret the encoded data to determine the individual // glyph boundries protected void ExtractGlyphDescriptors() { // save some typing int w = Texture.Width; int h = Texture.Height; // grab the pixels of the texture so we can inspect them Color[] data = new Color[w * h]; Texture.GetData<Color>(data); // check for magic numbers bool valid = w > 0 && h > 1 && //valid = valid && ((data[0] & MAGIC_MASK) == MAGIC_NUMBER); //valid = valid && ((data[w] & MAGIC_MASK) == MAGIC_NUMBER); data[0].A == 0xC0 && data[0].R == 0xDE && data[w].A == 0xC0 && data[w].R == 0xDE; // is this a valid font texture if (valid) { // record the height and ascent of this font _fontHeight = (int)(data[0].G * 256 + data[0].B); _fontAscent = (int)(data[w].G * 256 + data[w].B); // scan the image for our glyph markers for (int y = 0; y < h; y += _fontHeight + 1) { // we encode the height and ascent in the first column of // the first row, so it cannot be a valid glyph. skip it. int nFirstColumn = (y == 0 ? 1 : 0); // if there's no glyph marker here (in the first column), // there's no point in looking at the rest of the row if ((data[y * w + nFirstColumn].A) == 0xFF) { // found a marker, scan the row for glyphs for (int x = nFirstColumn; x < w; x++) { // is this a glyph? if (data[y * w + x].A == 0xFF) { // yes. record the details and ... char key = (char)(data[y * w + x].G * 256 + data[y * w + x].B); int top = y + 1; int left = x; int width = 1; // ... keep scanning to determine the width while ((x + width < w - 1) && (data[y * w + x + width].A != 0xFF)) { width++; } // record this glyph in our master list AddGlyph(key, left, top, width, _fontHeight); // make sure the scan catches the next glyph x += width - 1; } } } } } else { // this may be a texture, but it's no gamefont! AddMessage("ERROR: Invalid texture. Bad MAGIC_NUMBER."); } } // add glyph to our list of recognized characters // top, left, right, and bottom define the texture coordinates protected void AddGlyph(char key, int left, int top, int width, int height) { // make sure we haven't already seen this character if (!_descriptors.ContainsKey(key)) { // perform some simple validation if (left < 0 || top < 0 || width < 1 || height < 1) { // texture bounds specified can't be drawn AddMessage(string.Format( "WARNING: Invalid glyph bounds. [{0},{1},{2},{3}]", left, top, width, height)); } else { // looks good. add it to our list. _descriptors.Add( key, new GlyphDescriptor(left, top, width, height)); } } } // draw each character of the string and return the width // and height drawn public Vector2 DrawString(SpriteBatch batch, string text, int x, int y, Color color, bool draw) { // keep track of what's been drawn Vector2 v2 = Vector2.Zero; // make sure the glyph texture is still there if (_texture != null) { // init return value, assume at least one char was drawn v2.Y = _fontHeight; v2.X = 0.0f; // the location to draw the next character Vector2 dest = Vector2.Zero; dest.X = x; dest.Y = y; // break string into characters and process each foreach (char c in text.ToCharArray()) { // make sure this is a recognized glyph if (_descriptors.ContainsKey(c)) { // don't actually draw glyph if we're just measuring if (draw) { batch.Draw( _texture, dest, _descriptors[c].GetRectangle(), color); } // increment next location and total width dest.X += _descriptors[c].Width; v2.X += _descriptors[c].Width; } } } // return the bounds of the rendered string return v2; } // overload to draw text in specified color public Vector2 DrawString(SpriteBatch batch, string text, int x, int y, Color color) { return DrawString(batch, text, x, y, color, true); } // overload to draw white text (default color) public Vector2 DrawString(SpriteBatch batch, string text, int x, int y) { return DrawString(batch, text, x, y, Color.White, true); } // usefull overload for character-based animated effects public Vector2 DrawString(SpriteBatch batch, char c, int x, int y, Color color, bool draw) { // report size of glyph, if valid Vector2 v2 = Vector2.Zero; // make sure we have a valid texture if (_texture != null) { // make sure this is a valid glyph if (_descriptors.ContainsKey(c)) { // don't draw if we're just measuring if (draw) { batch.Draw( _texture, new Vector2(x,y), _descriptors[c].GetRectangle(), color); } // glyph was valid, return its measurements v2.Y = _fontHeight; v2.X = _descriptors[c].Width; } } return v2; } // usefull overload for character-based animated effects public Vector2 DrawString(SpriteBatch batch, char c, int x, int y, Color color) { return DrawString(batch, c, x, y, color, true); } // usefull overload for character-based animated effects public Vector2 DrawString(SpriteBatch batch, char c, int x, int y) { return DrawString(batch, c, x, y, Color.White, true); } // go through the motion of drawing the string, without actually // rendering it to the batch. other than blitting the pixels to // the screen, these two methods do pretty much the same tasks, // so why not combine them? public Vector2 MeasureString(string text) { return DrawString(null, text, 0, 0, Color.White, false); } // usefull overload for character-based animated effects public Vector2 MeasureString(char c) { return DrawString(null, c, 0, 0, Color.White, false); } } // simple class to store individual glyph bounds public class GlyphDescriptor { // left bounds of glyph public int Left { get { return Rect.Left; } } // top bounds of glyph public int Top { get { return Rect.Top; } } // width of glyph bounds public int Width { get { return Rect.Width; } } // height of glyph bounds public int Height { get { return Rect.Height; } } // most APIs will want a Rect to define bounds private Rectangle _rect = new Rectangle(); protected Rectangle Rect { get { return _rect; } } public Rectangle GetRectangle() { return Rect; } // only way to set properties is via the constructor public GlyphDescriptor(int left, int top, int width, int height) { _rect = new Rectangle(left, top, width, height); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BroadcastScalarToVector128Int64() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector128Int64 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static SimpleUnaryOpTest__BroadcastScalarToVector128Int64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__BroadcastScalarToVector128Int64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.BroadcastScalarToVector128<Int64>( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.BroadcastScalarToVector128<Int64>( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.BroadcastScalarToVector128<Int64>( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Int64) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Int64) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Int64) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.BroadcastScalarToVector128<Int64>( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Avx2.BroadcastScalarToVector128<Int64>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Int64>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Int64>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int64(); var result = Avx2.BroadcastScalarToVector128<Int64>(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.BroadcastScalarToVector128<Int64>(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (firstOp[0] != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((firstOp[0] != result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Int64>(Vector128<Int64>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kodestruct.Common.Entities; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.CalculationLogger.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Steel.AISC.Exceptions; using Kodestruct.Steel.AISC.SteelEntities; using Kodestruct.Steel.AISC.SteelEntities.Sections; using Kodestruct.Common.Mathematics; using Kodestruct.Steel.AISC.AISC360v10.K_HSS.TrussConnections; using Kodestruct.Steel.AISC.Steel.Entities.Sections; namespace Kodestruct.Steel.AISC.AISC360v10.HSS.TrussConnections { public abstract partial class RhsTrussBranchConnection: HssTrussConnection, IHssTrussBranchConnection { private double _theta; public double theta { get { _theta = thetaMain; return _theta; } set { _theta = value; } } private double _sin_theta; public double sin_theta { get { _sin_theta = Math.Sin(theta.ToRadians()); return _sin_theta; } set { _sin_theta = value; } } /// <summary> /// Width ratio B_b/B /// </summary> private double _beta; protected double beta { get { _beta = Get_beta(); return _beta; } set { _beta = value; } } private double Get_beta() { return B_b / B; } private double _gamma; /// <summary> /// Chord slenderness ratio /// </summary> protected double gamma { get { _gamma = Get_gamma(); return _gamma; } set { _gamma = value; } } private double Get_gamma() { return B / (2.0 * t); } /// <summary> /// Load length parameter /// </summary> private double _eta; protected double eta { get { _beta = Get_eta(); return _eta; } set { _eta = value; } } private double Get_eta() { return l_b / B; } private double _B; protected double B { get { _B = Chord.Section.B; return _B; } set { _B = value; } } private double _H; protected double H { get { _H = Chord.Section.H; return _H; } set { _H = value; } } private double _t; protected double t { get { _t = Chord.Section.t_des; return _t; } set { _t = value; } } protected override double GetF_y() { return Chord.Material.YieldStress; } protected override double GetF_yb() { return MainBranch.Material.YieldStress; } private double _B_b; protected double B_b { get { SteelRhsSection br = getBranch(); _B_b = br.Section.B; return _B_b; } set { _B = value; } } private double _H_b; public double H_b { get { SteelRhsSection br = getBranch(); _H_b = br.Section.H; return _H_b; } set { _H_b = value; } } private double _t_b; public double t_b { get { SteelRhsSection br = getBranch(); _t_b = br.Section.t_des; return _t_b; } set { _t_b = value; } } private double _beta_eop; public double beta_eop { get { _beta_eop = Get_beta_eop(); return _beta_eop; } set { _beta_eop = value; } } public double Get_beta_eop() { double beta_eop = ((5 * beta) / (gamma)); beta_eop = beta_eop > beta ? beta : beta_eop; return beta_eop; } private double _E; public double E { get { _E = SteelConstants.ModulusOfElasticity; return _E; } set { _E = value; } } private double _l_b; public double l_b { get { _l_b = H_b / sin_theta; return _l_b; } set { _l_b = value; } } /// <summary> /// outside corner radius of HSS /// is 1.5t /// </summary> private double _k; public double k { get { return 1.5 * t; return _k; } set { _k = value; } } protected abstract SteelRhsSection getBranch(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventGrid { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Azure EventGrid Management Client /// </summary> public partial class EventGridManagementClient : ServiceClient<EventGridManagementClient>, IEventGridManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription credentials that uniquely identify a Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Version of the API to be used with the client request. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IEventSubscriptionsOperations. /// </summary> public virtual IEventSubscriptionsOperations EventSubscriptions { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the ITopicsOperations. /// </summary> public virtual ITopicsOperations Topics { get; private set; } /// <summary> /// Gets the ITopicTypesOperations. /// </summary> public virtual ITopicTypesOperations TopicTypes { get; private set; } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected EventGridManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected EventGridManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected EventGridManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected EventGridManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventGridManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventGridManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventGridManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventGridManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventGridManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { EventSubscriptions = new EventSubscriptionsOperations(this); Operations = new Operations(this); Topics = new TopicsOperations(this); TopicTypes = new TopicTypesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-09-15-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<EventSubscriptionDestination>("endpointType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<EventSubscriptionDestination>("endpointType")); CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fsrvp; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace Microsoft.Protocols.TestSuites.FileSharing.FSRVP.TestSuite { /// <summary> /// This test class is for VSS test case. /// </summary> [TestClass] public partial class VSSOperateShadowCopySet : SMB2TestBase { #region Variables /// <summary> /// FSRVP client for creating shadow copy. /// </summary> private FsrvpClient fsrvpClientForCreation; /// <summary> /// The id of shadow copy set. /// </summary> private Guid shadowCopySetId; /// <summary> /// The list of shadow copy. /// </summary> private List<FsrvpClientShadowCopy> shadowCopyList = new List<FsrvpClientShadowCopy>(); /// <summary> /// Indicates the status of the shadow copy set. /// </summary> private FsrvpStatus fsrvpStatus; #endregion #region Test Suite Initialization // Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } // Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Case Initialization // Use TestInitialize to run code before running every test in the class protected override void TestInitialize() { base.TestInitialize(); fsrvpStatus = FsrvpStatus.None; shadowCopySetId = Guid.Empty; shadowCopyList.Clear(); } // Use TestCleanup to run code after every test in a class have run protected override void TestCleanup() { if (fsrvpClientForCreation != null) { try { if (fsrvpStatus == FsrvpStatus.Started || fsrvpStatus == FsrvpStatus.Added) { fsrvpClientForCreation.AbortShadowCopySet(shadowCopySetId); } if (fsrvpStatus == FsrvpStatus.CreateInProgress) { fsrvpClientForCreation.CommitShadowCopySet(shadowCopySetId, (uint)FsrvpUtility.FSRVPCommitTimeoutInSeconds * 1000); fsrvpStatus = FsrvpStatus.Committed; } if (fsrvpStatus == FsrvpStatus.Committed) { fsrvpClientForCreation.ExposeShadowCopySet(shadowCopySetId, (uint)FsrvpUtility.FSRVPExposeTimeoutInSeconds * 1000); fsrvpStatus = FsrvpStatus.Exposed; #region GetShareMapping for (int i = 0; i < shadowCopyList.Count; i++) { FsrvpClientShadowCopy shadowCopy = shadowCopyList[i]; FSSAGENT_SHARE_MAPPING mapping; int ret = fsrvpClientForCreation.GetShareMapping(shadowCopy.serverShadowCopyId, shadowCopySetId, shadowCopy.shareName, (uint)FsrvpLevel.FSRVP_LEVEL_1, out mapping); if ((FsrvpErrorCode)ret == FsrvpErrorCode.FSRVP_SUCCESS) { shadowCopy.exposedName = mapping.ShareMapping1.ShadowCopyShareName; shadowCopy.CreationTimestamp = mapping.ShareMapping1.CreationTimestamp; shadowCopyList[i] = shadowCopy; } } #endregion } if (fsrvpStatus == FsrvpStatus.Exposed) { fsrvpClientForCreation.RecoveryCompleteShadowCopySet(shadowCopySetId); fsrvpStatus = FsrvpStatus.Recovered; foreach (FsrvpClientShadowCopy shadowCopy in shadowCopyList) { fsrvpClientForCreation.DeleteShareMapping(shadowCopySetId, shadowCopy.serverShadowCopyId, shadowCopy.shareName); } } } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup at status {0} got an unexpected Exception: {1}", (uint)fsrvpStatus, ex.Message); } DisconnectServer(ref fsrvpClientForCreation); } shadowCopyList.Clear(); fsrvpStatus = FsrvpStatus.None; base.TestCleanup(); } #endregion #region Test Cases for VSSOperateShadowCopySet [TestMethod] [TestCategory(TestCategories.Bvt)] [TestCategory(TestCategories.Fsrvp)] [Description("Check if the server supports the VSS provider to create a writable snapshot for remote files.")] public void BVT_VSSOperateShadowCopySet_WritableSnapshot_SingleNode() { List<string> shareUncPaths = new List<string>(); shareUncPaths.Add(@"\\" + TestConfig.SutComputerName + @"\" + TestConfig.BasicFileShare); TestShadowCopySet((ulong)FsrvpContextValues.FSRVP_CTX_BACKUP | (ulong)FsrvpShadowCopyAttributes.FSRVP_ATTR_AUTO_RECOVERY, shareUncPaths, FsrvpStatus.None, FsrvpSharePathsType.None); } #endregion #region Utilites /// <summary> /// Connect to server. /// </summary> /// <param name="client">Fsrvp client.</param> /// <param name="server">The name of server.</param> /// <returns>Return true if success, otherwise return false.</returns> private bool ConnectServer(ref FsrvpClient client, string server) { AccountCredential accountCredential = new AccountCredential(TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword); ClientSecurityContext securityContext = new SspiClientSecurityContext( TestConfig.DefaultSecurityPackage, accountCredential, Smb2Utility.GetCifsServicePrincipalName(server), ClientSecurityContextAttribute.Connection | ClientSecurityContextAttribute.DceStyle | ClientSecurityContextAttribute.Integrity | ClientSecurityContextAttribute.ReplayDetect | ClientSecurityContextAttribute.SequenceDetect | ClientSecurityContextAttribute.UseSessionKey, SecurityTargetDataRepresentation.SecurityNativeDrep); // This indicates that the RPC message is just integrity-protected. client.Context.AuthenticationLevel = TestConfig.DefaultRpceAuthenticationLevel; try { BaseTestSite.Log.Add(LogEntryKind.Debug, "Connect to server {0}.", server); client.BindOverNamedPipe(server, accountCredential, securityContext, new TimeSpan(0, 0, (int)FsrvpUtility.FSRVPTimeoutInSeconds)); } catch (InvalidOperationException ex) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Connect to server {0} failed. Exception: {1}", server, ex.Message); client.Unbind(TestConfig.Timeout); return false; } BaseTestSite.Log.Add(LogEntryKind.Debug, "Connect to server {0} successfully.", server); return true; } /// <summary> /// Disconnect from server. /// </summary> /// <param name="client">Fsrvp client.</param> private void DisconnectServer(ref FsrvpClient client) { if (client != null) { try { BaseTestSite.Log.Add(LogEntryKind.Debug, "Disconnect from server."); client.Unbind(TestConfig.Timeout); client = null; } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup: Unexpected Exception:", ex); } } } /// <summary> /// Get the hostname which the shareUncPath belongs to. /// </summary> /// <param name="shareUncPath">The full path of the share in UNC format.</param> /// <returns>The hostname which the shareUncPath belongs to.</returns> private string GetHostname(string shareUncPath) { BaseTestSite.Assume.IsFalse(string.IsNullOrEmpty(shareUncPath), "shareUncPath is not null or empty"); BaseTestSite.Assume.IsTrue(shareUncPath.Length > 3, "The length of shareUncPath is bigger than 3."); int i = shareUncPath.IndexOf('\\', 2); return shareUncPath.Substring(2, i - 2); } /// <summary> /// Get the name of exposed share according to TD. /// </summary> /// <param name="shareUncPath">The full path of the share in UNC format.</param> /// <param name="shadowCopyId">The GUID of the shadow copy associated with the share.</param> /// <returns>The name of exposed share</returns> private string GetExposedShareName(string shareUncPath, Guid shadowCopyId) { BaseTestSite.Assume.IsFalse(string.IsNullOrEmpty(shareUncPath), "shareUncPath is not null or empty"); int i = shareUncPath.IndexOf('\\', 2); return shareUncPath.Substring(i + 1) + "@{" + shadowCopyId.ToString() + "}"; ; } #endregion #region Test Methods /// <summary> /// Get the name of FSRVP server which the client MUST connect to create shadow copies of the specified shareName. /// </summary> /// <param name="shareName">The full path of the share in UNC format.</param> /// <returns>The name of FSRVP server.</returns> private string GetFsrvpServerName(string shareName) { int ret; string FsrvpServerName = ""; string serverName; FsrvpClient fsrvpClientForQuery = new FsrvpClient(); serverName = GetHostname(shareName); BaseTestSite.Assume.IsFalse(string.IsNullOrEmpty(serverName), "serverName is valid. The actual value is {0}.", serverName); try { DoUntilSucceed(() => ConnectServer(ref fsrvpClientForQuery, serverName), TestConfig.LongerTimeout, "Retry ConnectServer until succeed within timeout span"); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call IsPathSupported({0}, out SupportedByThisProvider, out OwnerMachineName)", shareName); bool SupportedByThisProvider; ret = fsrvpClientForQuery.IsPathSupported(shareName, out SupportedByThisProvider, out FsrvpServerName); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.IsTrue(SupportedByThisProvider, "Expect that shadow copies of this share are supported by the server."); BaseTestSite.Assert.IsFalse(string.IsNullOrEmpty(FsrvpServerName), "Expect that OwnerMachineName is not null or empty. The server actually returns {0}.", FsrvpServerName); } finally { DisconnectServer(ref fsrvpClientForQuery); } return FsrvpServerName; } /// <summary> /// Test set context with invalid parameter. /// </summary> /// <param name="context">The context to be used for the shadow copy operations.</param> /// <param name="shareUncPaths">The full path list of the shares in UNC format.</param> private void TestInvalidSetContext(ulong context, List<string> shareUncPaths) { int ret; string FsrvpServerName; #region Query FSRVP Server Name BaseTestSite.Log.Add(LogEntryKind.TestStep, "Query FSRVP Server Name."); FsrvpServerName = GetFsrvpServerName(shareUncPaths[0]); #endregion #region Connect to FSRVP server BaseTestSite.Log.Add(LogEntryKind.TestStep, "Connect to FSRVP server."); fsrvpClientForCreation = new FsrvpClient(); DoUntilSucceed(() => ConnectServer(ref fsrvpClientForCreation, FsrvpServerName), TestConfig.LongerTimeout, "Retry ConnectServer until succeed within timeout span"); #endregion #region GetSupportedVersion BaseTestSite.Log.Add(LogEntryKind.TestStep, "Get supported FSRVP versions."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call GetSupportedVersion(out MinVersion, out MaxVersion)"); uint MinVersion; uint MaxVersion; ret = fsrvpClientForCreation.GetSupportedVersion(out MinVersion, out MaxVersion); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.AreEqual<uint>((uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MinVersion, "Expect that the minimum version of the protocol supported by the server is 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MinVersion); BaseTestSite.Assert.AreEqual<uint>((uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MaxVersion, "Expect that the maximum version of the protocol supported by the server is 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MaxVersion); #endregion #region SetContext BaseTestSite.Log.Add(LogEntryKind.TestStep, "Send SetContext request with invalid context and expect failure."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call SetContext(0x{0:x8}).", context); ret = fsrvpClientForCreation.SetContext(context); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_E_UNSUPPORTED_CONTEXT, (FsrvpErrorCode)ret, "The server is expected to return 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpErrorCode.FSRVP_E_UNSUPPORTED_CONTEXT, ret); #endregion } /// <summary> /// Test the operation of shadow copy set. /// </summary> /// <param name="context">The context to be used for the shadow copy operations.</param> /// <param name="shareUncPaths">The full path list of the shares in UNC format.</param> /// <param name="statusToAbort">Indicates which status the server is in, the creation process will be aborted and exit. /// FsrvpStatus.None indicates that AbortShadowCopySet will not be called and all operations will be executed.</param> /// <param name="sharePathsType">Indicates the type of share paths.</param> private void TestShadowCopySet(ulong context, List<string> shareUncPaths, FsrvpStatus statusToAbort, FsrvpSharePathsType sharePathsType) { int ret; string FsrvpServerName; #region Query FSRVP Server Name BaseTestSite.Log.Add(LogEntryKind.TestStep, "Query FSRVP Server Name."); FsrvpServerName = GetFsrvpServerName(shareUncPaths[0]); #endregion #region Connect to FSRVP server BaseTestSite.Log.Add(LogEntryKind.TestStep, "Connect to FSRVP server."); fsrvpClientForCreation = new FsrvpClient(); DoUntilSucceed(() => ConnectServer(ref fsrvpClientForCreation, FsrvpServerName), TestConfig.LongerTimeout, "Retry ConnectServer until succeed within timeout span"); #endregion #region GetSupportedVersion BaseTestSite.Log.Add(LogEntryKind.TestStep, "Get supported FSRVP versions."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call GetSupportedVersion(out MinVersion, out MaxVersion)"); uint MinVersion; uint MaxVersion; ret = fsrvpClientForCreation.GetSupportedVersion(out MinVersion, out MaxVersion); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.AreEqual<uint>((uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MinVersion, "Expect that the minimum version of the protocol supported by the server is 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MinVersion); BaseTestSite.Assert.AreEqual<uint>((uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MaxVersion, "Expect that the maximum version of the protocol supported by the server is 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpVersionValues.FSRVP_RPC_VERSION_1, MaxVersion); #endregion #region SetContext BaseTestSite.Log.Add(LogEntryKind.TestStep, "SetContext."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call SetContext(0x{0:x8}).", context); ret = fsrvpClientForCreation.SetContext(context); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); #endregion #region StartShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "StartShadowCopySet."); Guid clientShadowCopySetId = Guid.NewGuid(); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call StartShadowCopySet({0}, out pShadowCopySetId)", clientShadowCopySetId); ret = fsrvpClientForCreation.StartShadowCopySet(clientShadowCopySetId, out shadowCopySetId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.AreNotEqual<Guid>(Guid.Empty, shadowCopySetId, "The server is expected to return a valid shadowCopySetId. But the shadowCopySetId which the server returns is empty."); fsrvpStatus = FsrvpStatus.Started; #endregion if (statusToAbort == FsrvpStatus.Started) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Abort StartShadowCopySet reqeust."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AbortShadowCopySet({0})", shadowCopySetId); ret = fsrvpClientForCreation.AbortShadowCopySet(shadowCopySetId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); return; } #region AddToShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "AddToShadowCopySet."); if (sharePathsType == FsrvpSharePathsType.OnClusterAndNonOwnerNode || sharePathsType == FsrvpSharePathsType.OnDifferentNode) { // Negative test cases BaseTestSite.Assume.IsTrue(shareUncPaths.Count == 2, "shareUncPaths should contains two paths."); #region Valid ShareName FsrvpClientShadowCopy shadowCopy = new FsrvpClientShadowCopy(); shadowCopy.shareName = shareUncPaths[0]; shadowCopy.clientShadowCopyId = Guid.NewGuid(); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AddToShadowCopySet({0},{1},{2},out pShadowCopyId)", shadowCopy.clientShadowCopyId, shadowCopySetId, shadowCopy.shareName); ret = fsrvpClientForCreation.AddToShadowCopySet(shadowCopy.clientShadowCopyId, shadowCopySetId, shadowCopy.shareName, out shadowCopy.serverShadowCopyId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.AreNotEqual<Guid>(Guid.Empty, shadowCopy.serverShadowCopyId, "The server is expected to send a valid shadowCopyId. But the shadowCopyId which the server returns is empty."); shadowCopyList.Add(shadowCopy); fsrvpStatus = FsrvpStatus.Added; #endregion #region Invalid ShareName shadowCopy = new FsrvpClientShadowCopy(); shadowCopy.shareName = shareUncPaths[1]; shadowCopy.clientShadowCopyId = Guid.NewGuid(); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AddToShadowCopySet({0},{1},{2},out pShadowCopyId)", shadowCopy.clientShadowCopyId, shadowCopySetId, shadowCopy.shareName); ret = fsrvpClientForCreation.AddToShadowCopySet(shadowCopy.clientShadowCopyId, shadowCopySetId, shadowCopy.shareName, out shadowCopy.serverShadowCopyId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_E_INVALIDARG, (FsrvpErrorCode)ret, "The server is expected to return 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpErrorCode.FSRVP_E_INVALIDARG, ret); BaseTestSite.Assert.AreEqual<Guid>(Guid.Empty, shadowCopy.serverShadowCopyId, "The server is expected to send an empty shadowCopyId. The actual shadowCopyId which the server returns is {0}.", shadowCopy.serverShadowCopyId.ToString()); return; #endregion } else { foreach (string shareUncPath in shareUncPaths) { FsrvpClientShadowCopy shadowCopy = new FsrvpClientShadowCopy(); shadowCopy.shareName = shareUncPath; shadowCopy.clientShadowCopyId = Guid.NewGuid(); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AddToShadowCopySet({0},{1},{2},out pShadowCopyId)", shadowCopy.clientShadowCopyId, shadowCopySetId, shareUncPath); ret = fsrvpClientForCreation.AddToShadowCopySet(shadowCopy.clientShadowCopyId, shadowCopySetId, shareUncPath, out shadowCopy.serverShadowCopyId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.AreNotEqual<Guid>(Guid.Empty, shadowCopy.serverShadowCopyId, "The server is expected to send a valid shadowCopyId. But the shadowCopyId which the server returns is empty."); shadowCopyList.Add(shadowCopy); fsrvpStatus = FsrvpStatus.Added; } } #endregion if (statusToAbort == FsrvpStatus.Added) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Abort AddToShadowCopySet request."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AbortShadowCopySet({0})", shadowCopySetId); ret = fsrvpClientForCreation.AbortShadowCopySet(shadowCopySetId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); return; } #region PrepareShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "PrepareShadowCopySet."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call PrepareShadowCopySet({0}, {1})", shadowCopySetId, FsrvpUtility.FSRVPPrepareTimeoutInSeconds * 1000); ret = fsrvpClientForCreation.PrepareShadowCopySet(shadowCopySetId, (uint)FsrvpUtility.FSRVPPrepareTimeoutInSeconds * 1000); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); fsrvpStatus = FsrvpStatus.CreateInProgress; #endregion #region CommitShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "CommitShadowCopySet."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call CommitShadowCopySet({0},{1})", shadowCopySetId, FsrvpUtility.FSRVPCommitTimeoutInSeconds * 1000); ret = fsrvpClientForCreation.CommitShadowCopySet(shadowCopySetId, (uint)FsrvpUtility.FSRVPCommitTimeoutInSeconds * 1000); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); fsrvpStatus = FsrvpStatus.Committed; #endregion #region ExposeShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "ExposeShadowCopySet."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call ExposeShadowCopySet({0}, {1})", shadowCopySetId, FsrvpUtility.FSRVPExposeTimeoutInSeconds * 1000); ret = fsrvpClientForCreation.ExposeShadowCopySet(shadowCopySetId, (uint)FsrvpUtility.FSRVPExposeTimeoutInSeconds * 1000); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); fsrvpStatus = FsrvpStatus.Exposed; #endregion #region GetShareMapping BaseTestSite.Log.Add(LogEntryKind.TestStep, "GetShareMapping."); for (int i = 0; i < shadowCopyList.Count; i++) { FsrvpClientShadowCopy shadowCopy = shadowCopyList[i]; FSSAGENT_SHARE_MAPPING mapping; BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call GetShareMapping({0}, {1}, {2}, {3}, out ShareMapping)", shadowCopy.serverShadowCopyId, shadowCopySetId, shadowCopy.shareName, FsrvpLevel.FSRVP_LEVEL_1); ret = fsrvpClientForCreation.GetShareMapping(shadowCopy.serverShadowCopyId, shadowCopySetId, shadowCopy.shareName, (uint)FsrvpLevel.FSRVP_LEVEL_1, out mapping); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.IsFalse(mapping.ShareMapping1IsNull, "Expect ShareMapping.ShareMapping1 the server returns is not null."); string exposedName = GetExposedShareName(shadowCopy.shareName, shadowCopy.serverShadowCopyId); BaseTestSite.Assert.IsTrue( mapping.ShareMapping1.ShadowCopyShareName.Equals(exposedName, StringComparison.InvariantCultureIgnoreCase), "Expect the exposed sharename returns by server is valid."); BaseTestSite.Assert.IsTrue( mapping.ShareMapping1.CreationTimestamp > 0, "Expect the CreationTimestamp returns by server is valid."); shadowCopy.exposedName = mapping.ShareMapping1.ShadowCopyShareName; shadowCopy.CreationTimestamp = mapping.ShareMapping1.CreationTimestamp; shadowCopyList[i] = shadowCopy; } #endregion #region Create a file in the exposed share and expect the failure. BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create a file in the exposed share and expect the failure."); foreach (FsrvpClientShadowCopy shadowCopy in shadowCopyList) { string exposedSharePath = @"\\" + FsrvpServerName + @"\" + shadowCopy.exposedName; BaseTestSite.Log.Add(LogEntryKind.Debug, "Create a file {0} in the share: {1}.", CurrentTestCaseName, exposedSharePath); bool result = sutProtocolController.CreateFile(exposedSharePath, CurrentTestCaseName, string.Empty); if ((context & (ulong)FsrvpShadowCopyAttributes.FSRVP_ATTR_AUTO_RECOVERY) != 0) { // Test writable snapshot BaseTestSite.Assert.IsTrue(result, "Expect that creating the file in the share succeeds."); } else { // Test readonly snapshot BaseTestSite.Assert.IsFalse(result, "Expect that creating the file in the share fails."); } } #endregion #region RecoveryCompleteShadowCopySet BaseTestSite.Log.Add(LogEntryKind.TestStep, "RecoveryCompleteShadowCopySet."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call RecoveryCompleteShadowCopySet({0})", shadowCopySetId); ret = fsrvpClientForCreation.RecoveryCompleteShadowCopySet(shadowCopySetId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); fsrvpStatus = FsrvpStatus.Recovered; #endregion if (statusToAbort == FsrvpStatus.Recovered) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Abort RecoveryCompleteShadowCopySet request."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call AbortShadowCopySet({0})", shadowCopySetId); ret = fsrvpClientForCreation.AbortShadowCopySet(shadowCopySetId); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_E_BAD_STATE, (FsrvpErrorCode)ret, "The server is expected to return 0x{0:x8}. The server actually returns 0x{1:x8}.", (uint)FsrvpErrorCode.FSRVP_E_BAD_STATE, ret); } #region IsPathShadowCopied BaseTestSite.Log.Add(LogEntryKind.TestStep, "Check if the share paths are shadow copied."); foreach (string shareName in shareUncPaths) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call IsPathShadowCopied({0}, out ShadowCopyPresent, out ShadowCopyCompatibility)", shareName); bool ShadowCopyPresent = false; long ShadowCopyCompatibility = 0; ret = fsrvpClientForCreation.IsPathShadowCopied(shareName, out ShadowCopyPresent, out ShadowCopyCompatibility); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); BaseTestSite.Assert.IsTrue(ShadowCopyPresent, "Expect that ShadowCopyPresent returned by the server is true."); BaseTestSite.Assert.IsTrue((ShadowCopyCompatibility == 0) || (ShadowCopyCompatibility == (long)FsrvpShadowCopyCompatibilityValues.FSRVP_DISABLE_CONTENTINDEX) || (ShadowCopyCompatibility == (long)FsrvpShadowCopyCompatibilityValues.FSRVP_DISABLE_DEFRAG) || (ShadowCopyCompatibility == (long)(FsrvpShadowCopyCompatibilityValues.FSRVP_DISABLE_CONTENTINDEX | FsrvpShadowCopyCompatibilityValues.FSRVP_DISABLE_DEFRAG)), "Expect that ShadowCopyCompatibility returned by the server is valid. The server actually returns 0x{0:x8}.", ShadowCopyCompatibility); } #endregion #region DeleteShareMapping BaseTestSite.Log.Add(LogEntryKind.TestStep, "DeleteShareMapping."); foreach (FsrvpClientShadowCopy shadowCopy in shadowCopyList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to call DeleteShareMapping({0}, {1}, {2})", shadowCopySetId, shadowCopy.serverShadowCopyId, shadowCopy.shareName); ret = fsrvpClientForCreation.DeleteShareMapping(shadowCopySetId, shadowCopy.serverShadowCopyId, shadowCopy.shareName); BaseTestSite.Assert.AreEqual<FsrvpErrorCode>(FsrvpErrorCode.FSRVP_SUCCESS, (FsrvpErrorCode)ret, "The server is expected to return 0x00000000. The server actually returns 0x{0:x8}.", ret); } shadowCopyList.Clear(); #endregion } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Imms.Abstract; namespace Imms { /// <summary> /// Extensions for IEnumerable and collection classes. /// </summary> static class CollectionExt { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> seq, IEqualityComparer<T> eq ) { eq = eq ?? FastEquality<T>.Default; return new HashSet<T>(seq, eq); } public static SortedSet<T> ToSortedSet<T>(this IEnumerable<T> seq, IComparer<T> comparer) { comparer = comparer ?? FastComparer<T>.Default; return new SortedSet<T>(seq, comparer); } /// <summary> /// Tries the guess the length of the sequence by checking if it's a known collection type, WITHOUT iterating over it. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items">The items.</param> /// <returns>The length of the sequence, or None if the guess didn't work.</returns> internal static Optional<int> TryGuessLength<T>(this IEnumerable<T> items) { if (items == null) throw Errors.Argument_null("items"); var iCollection = items as ICollection<T>; if (iCollection != null) { return iCollection.Count; } var icollectionLegacy = items as ICollection; if (icollectionLegacy != null) { return icollectionLegacy.Count; } var ianyIterable = items as IAnyIterable<T>; if (ianyIterable != null) { return ianyIterable.Length; } return Optional.None; } /// <summary> /// Converts a sequence to an array efficiently. The array may be longer than the sequence. The final elements will be /// their defualt values.<br /> /// The length of the sequence is returned in the output parameter. <br /> /// It is extremely unsafe to modify the array!!!! /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="items"> The sequence. </param> /// <param name="length"> The length of the sequence, computed while converting it to an array. </param> /// <returns> </returns> internal static T[] ToArrayFast<T>(this IEnumerable<T> items, out int length) { //There are several main reasons why this method is faster than other ways of converting sequences to arrays. //1. It intelligently calls the right method if the sequence is really a concrete collection. //2. It cheats using type checking and reflection. //3. If all else fails and the input isn't a known collection, it uses the classical conversion algorithm, // but doesn't need to resize the array to the size of the sequence. This saves a lot of time, because // this last resize operation is the longest of all them all. // That said, it can be slow for small collections. if (items == null) throw Errors.Argument_null("items"); T[] arr; var array = items as T[]; if (array != null) { arr = array; length = array.Length; goto exit; } var iCollection = items as ICollection<T>; if (iCollection != null) { arr = new T[iCollection.Count]; iCollection.CopyTo(arr, 0); length = arr.Length; goto exit; } var iCollectionLegacy = items as ICollection; if (iCollectionLegacy != null) { arr = new T[iCollectionLegacy.Count]; iCollectionLegacy.CopyTo(arr, 0); length = arr.Length; goto exit; } length = 4; arr = items.ToArrayWithLengthHint(ref length); exit: return arr; } /// <summary> /// Constructs an array from a sequence using a length hint.. <br /> /// The length hint parameter also returns the number of items in the sequence. The array is returned not truncated /// (e.g. it can have uninitialized elements in the end). /// </summary> /// <param name="o"></param> /// <param name="length"></param> /// <returns></returns> private static T[] ToArrayWithLengthHint<T>(this IEnumerable<T> o, ref int length) { var arr = new T[length]; using (var iterator = o.GetEnumerator()) { int i; for (i = 0; iterator.MoveNext(); i++) { if (i >= arr.Length) { var newArr = new T[arr.Length << 1]; arr.CopyTo(newArr, 0); arr = newArr; } arr[i] = iterator.Current; } length = i; return arr; } } internal static void ForEach<TElem>(this IEnumerable<TElem> seq, Action<TElem> act) { IAnyIterable<TElem> elems = seq as IAnyIterable<TElem>; if (elems != null) { elems.ForEachWhile(item => { act(item); return true; }); } else if (seq is TElem[]) { var arr = (TElem[]) seq; for (var i = 0; i < arr.Length; i++) act(arr[i]); } else { var list = seq as List<TElem>; if (list != null) list.ForEach(act); else { ForEachWhile(seq, x => { act(x); return true; }); } } } internal static IEnumerable<TOut> Cross<T, TOther, TOut>(this IEnumerable<T> self, IEnumerable<TOther> other, Func<T, TOther, TOut> selector) { var arrOther = other.ToArray(); return from x in self from y in arrOther select selector(x, y); } internal static bool HasEfficientForEach<T>(this IEnumerable<T> seq) { return seq is IAnyIterable<T> || seq is T[] || seq is List<T>; } internal static bool IsEmpty<T>(this IAnyIterable<T> seq) { return seq.Length == 0; } internal static bool ForEachWhile<TElem>(this IEnumerable<TElem> seq, Func<TElem, bool> act) { var elems = seq as IAnyIterable<TElem>; if (elems != null) { return elems.ForEachWhile(act); } var arr = seq as TElem[]; if (arr != null) { for (var i = 0; i < arr.Length; i++) { if (!act(arr[i])) { return false; } } } var list = seq as List<TElem>; if (list != null) { for (var i = 0; i < list.Count; i++) { if (!act(list[i])) { return false; } } } return seq.All(act); } class LambdaEnumerable<T> : IEnumerable<T> { readonly Func<IEnumerator<T>> _getIterator; public LambdaEnumerable(Func<IEnumerator<T>> getIterator) { _getIterator = getIterator; } public IEnumerator<T> GetEnumerator() { return _getIterator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
// // TrackInfoDisplay.cs // // Author: // Aaron Bockover <abockover@novell.com> // Larry Ewing <lewing@novell.com> (Is my hero) // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Gtk; using Cairo; using Hyena; using Hyena.Gui; using Hyena.Gui.Theatrics; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.ServiceStack; using Banshee.MediaEngine; namespace Banshee.Gui.Widgets { public abstract class TrackInfoDisplay : Widget { private ArtworkManager artwork_manager; protected ArtworkManager ArtworkManager { get { return artwork_manager; } } private ImageSurface current_image; protected ImageSurface CurrentImage { get { return current_image; } } private ImageSurface incoming_image; protected ImageSurface IncomingImage { get { return incoming_image; } } private ImageSurface missing_audio_image; protected ImageSurface MissingAudioImage { get { return missing_audio_image ?? (missing_audio_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, "audio-x-generic"), true)); } } private ImageSurface missing_video_image; protected ImageSurface MissingVideoImage { get { return missing_video_image ?? (missing_video_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, "video-x-generic"), true)); } } private Cairo.Color background_color; protected virtual Cairo.Color BackgroundColor { get { return background_color; } } private Cairo.Color text_color; protected virtual Cairo.Color TextColor { get { return text_color; } } private Cairo.Color text_light_color; protected virtual Cairo.Color TextLightColor { get { return text_light_color; } } private TrackInfo current_track; protected TrackInfo CurrentTrack { get { return current_track; } } private TrackInfo incoming_track; protected TrackInfo IncomingTrack { get { return incoming_track; } } private uint idle_timeout_id = 0; private SingleActorStage stage = new SingleActorStage (); protected TrackInfoDisplay (IntPtr native) : base (native) { } public TrackInfoDisplay () { stage.Iteration += OnStageIteration; if (ServiceManager.Contains<ArtworkManager> ()) { artwork_manager = ServiceManager.Get<ArtworkManager> (); } ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated | PlayerEvent.StateChange); WidgetFlags |= WidgetFlags.NoWindow; } public override void Dispose () { if (idle_timeout_id > 0) { GLib.Source.Remove (idle_timeout_id); } if (ServiceManager.PlayerEngine != null) { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); } stage.Iteration -= OnStageIteration; stage = null; InvalidateCache (); base.Dispose (); } protected override void OnRealized () { GdkWindow = Parent.GdkWindow; base.OnRealized (); } protected override void OnUnrealized () { base.OnUnrealized (); InvalidateCache (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); if (current_track == null) { LoadCurrentTrack (); } else { LoadImage (current_track); } } protected override void OnStyleSet (Style previous) { base.OnStyleSet (previous); text_color = CairoExtensions.GdkColorToCairoColor (Style.Foreground (StateType.Normal)); background_color = CairoExtensions.GdkColorToCairoColor (Style.Background (StateType.Normal)); text_light_color = Hyena.Gui.Theming.GtkTheme.GetCairoTextMidColor (this); if (missing_audio_image != null) { ((IDisposable)missing_audio_image).Dispose (); missing_audio_image = null; } if (missing_video_image != null) { ((IDisposable)missing_video_image).Dispose (); missing_video_image = null; } OnThemeChanged (); } protected virtual void OnThemeChanged () { } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { bool idle = incoming_track == null && current_track == null; if (!Visible || !IsMapped || (idle && !CanRenderIdle)) { return true; } Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window); foreach (Gdk.Rectangle damage in evnt.Region.GetRectangles ()) { cr.Rectangle (damage.X, damage.Y, damage.Width, damage.Height); cr.Clip (); if (idle) { RenderIdle (cr); } else { RenderAnimation (cr); } cr.ResetClip (); } CairoExtensions.DisposeContext (cr); return true; } protected virtual bool CanRenderIdle { get { return false; } } protected virtual void RenderIdle (Cairo.Context cr) { } private void RenderAnimation (Cairo.Context cr) { if (stage.Actor == null) { // We are not in a transition, just render RenderStage (cr, current_track, current_image); return; } if (current_track == null) { // Fade in the whole stage, nothing to fade out CairoExtensions.PushGroup (cr); RenderStage (cr, incoming_track, incoming_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (stage.Actor.Percent); return; } // XFade only the cover art RenderCoverArt (cr, incoming_image); CairoExtensions.PushGroup (cr); RenderCoverArt (cr, current_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - stage.Actor.Percent); // Fade in/out the text bool same_artist_album = incoming_track != null ? incoming_track.ArtistAlbumEqual (current_track) : false; bool same_track = incoming_track != null ? incoming_track.Equals (current_track) : false; if (same_artist_album) { RenderTrackInfo (cr, incoming_track, same_track, true); } if (stage.Actor.Percent <= 0.5) { // Fade out old text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, current_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - (stage.Actor.Percent * 2.0)); } else { // Fade in new text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, incoming_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha ((stage.Actor.Percent - 0.5) * 2.0); } } private void RenderStage (Cairo.Context cr, TrackInfo track, ImageSurface image) { RenderCoverArt (cr, image); RenderTrackInfo (cr, track, true, true); } protected virtual void RenderCoverArt (Cairo.Context cr, ImageSurface image) { ArtworkRenderer.RenderThumbnail (cr, image, false, Allocation.X, Allocation.Y, ArtworkSizeRequest, ArtworkSizeRequest, !IsMissingImage (image), 0, IsMissingImage (image), BackgroundColor); } protected bool IsMissingImage (ImageSurface pb) { return pb == missing_audio_image || pb == missing_video_image; } protected virtual void InvalidateCache () { } protected abstract void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum); protected virtual int ArtworkSizeRequest { get { return Allocation.Height; } } protected virtual int MissingIconSizeRequest { get { return 32; } } private void OnPlayerEvent (PlayerEventArgs args) { if (args.Event == PlayerEvent.StartOfStream) { LoadCurrentTrack (); } else if (args.Event == PlayerEvent.TrackInfoUpdated) { LoadCurrentTrack (true); } else if (args.Event == PlayerEvent.StateChange && (incoming_track != null || incoming_image != null)) { PlayerEventStateChangeArgs state = (PlayerEventStateChangeArgs)args; if (state.Current == PlayerState.Idle) { if (idle_timeout_id > 0) { GLib.Source.Remove (idle_timeout_id); } else { GLib.Timeout.Add (100, IdleTimeout); } } } } private bool IdleTimeout () { if (ServiceManager.PlayerEngine.CurrentTrack == null || ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle) { incoming_track = null; incoming_image = null; if (stage != null && stage.Actor == null) { stage.Reset (); } } idle_timeout_id = 0; return false; } private void LoadCurrentTrack () { LoadCurrentTrack (false); } private void LoadCurrentTrack (bool force_reload) { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track == current_track && !IsMissingImage (current_image) && !force_reload) { return; } else if (track == null) { incoming_track = null; incoming_image = null; return; } incoming_track = track; LoadImage (track); if (stage.Actor == null) { stage.Reset (); } } private void LoadImage (TrackInfo track) { ImageSurface image = artwork_manager.LookupScaleSurface (track.ArtworkId, ArtworkSizeRequest); if (image == null) { LoadMissingImage ((track.MediaAttributes & TrackMediaAttributes.VideoStream) != 0); } else { incoming_image = image; } if (track == current_track) { current_image = incoming_image; } } private void LoadMissingImage (bool is_video) { incoming_image = is_video ? MissingVideoImage : MissingAudioImage; } private double last_fps = 0.0; private void OnStageIteration (object o, EventArgs args) { Invalidate (); if (stage.Actor != null) { last_fps = stage.Actor.FramesPerSecond; return; } InvalidateCache (); if (ApplicationContext.Debugging) { Log.DebugFormat ("TrackInfoDisplay RenderAnimation: {0:0.00} FPS", last_fps); } if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) { ((IDisposable)current_image).Dispose (); } current_image = incoming_image; current_track = incoming_track; incoming_track = null; OnArtworkChanged (); } protected virtual void Invalidate () { QueueDraw (); } protected virtual void OnArtworkChanged () { } protected virtual string GetFirstLineText (TrackInfo track) { return String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (track.DisplayTrackTitle)); } protected virtual string GetSecondLineText (TrackInfo track) { string markup = null; Banshee.Streaming.RadioTrackInfo radio_track = track as Banshee.Streaming.RadioTrackInfo; if ((track.MediaAttributes & TrackMediaAttributes.Podcast) != 0) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Podcast Name and Published Date, respectively; // e.g. 'from BBtv published 7/26/2007' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2} {0}published{1} {3}"), track.DisplayAlbumTitle, track.ReleaseDate.ToShortDateString ()); } else if (radio_track != null && radio_track.ParentTrack != null) { // This is complicated because some radio streams send tags when the song changes, and we // want to display them if they do. But if they don't, we want it to look good too, so we just // display the station name for the second line. string by_from = GetByFrom ( track.ArtistName == radio_track.ParentTrack.ArtistName ? null : track.ArtistName, track.DisplayArtistName, track.AlbumTitle == radio_track.ParentTrack.AlbumTitle ? null : track.AlbumTitle, track.DisplayAlbumTitle, false ); if (String.IsNullOrEmpty (by_from)) { // simply: "Chicago Public Radio" or whatever the artist name is markup = GLib.Markup.EscapeText (radio_track.ParentTrack.ArtistName ?? Catalog.GetString ("Unknown Stream")); } else { // Translators: {0} and {1} are markup so ignore them, {2} is the name of the radio station string on = MarkupFormat (Catalog.GetString ("{0}on{1} {2}"), radio_track.ParentTrack.TrackTitle); // Translators: {0} is the "from {album} by {artist}" type string, and {1} is the "on {radio station name}" string markup = String.Format (Catalog.GetString ("{0} {1}"), by_from, on); } } else { markup = GetByFrom (track.ArtistName, track.DisplayArtistName, track.AlbumTitle, track.DisplayAlbumTitle, true); } return String.Format ("<span color=\"{0}\">{1}</span>", CairoExtensions.ColorGetHex (TextColor, false), markup); } private string MarkupFormat (string fmt, params string [] args) { string [] new_args = new string [args.Length + 2]; new_args[0] = String.Format ("<span color=\"{0}\" size=\"small\">", CairoExtensions.ColorGetHex (TextLightColor, false)); new_args[1] = "</span>"; for (int i = 0; i < args.Length; i++) { new_args[i + 2] = GLib.Markup.EscapeText (args[i]); } return String.Format (fmt, new_args); } private string GetByFrom (string artist, string display_artist, string album, string display_album, bool unknown_ok) { bool has_artist = !String.IsNullOrEmpty (artist); bool has_album = !String.IsNullOrEmpty (album); string markup = null; if (has_artist && has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Artist Name and Album Title, respectively; // e.g. 'by Parkway Drive from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2} {0}from{1} {3}"), display_artist, display_album); } else if (has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Album Title; // e.g. 'from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2}"), display_album); } else if (has_artist || unknown_ok) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Artist Name; // e.g. 'by Parkway Drive' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2}"), display_artist); } return markup; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Web; using Moq; using NUnit.Framework; using SquishIt.Framework.CSS; using SquishIt.Framework.Minifiers.CSS; using SquishIt.Framework.Files; using SquishIt.Framework.Renderers; using SquishIt.Framework.Resolvers; using SquishIt.Framework.Utilities; using SquishIt.Tests.Helpers; using SquishIt.Tests.Stubs; using HttpContext = SquishIt.Framework.HttpContext; namespace SquishIt.Tests { [TestFixture] public class CSSBundleTests { string css = TestUtilities.NormalizeLineEndings(@" li { margin-bottom:0.1em; margin-left:0; margin-top:0.1em; } th { font-weight:normal; vertical-align:bottom; } .FloatRight { float:right; } .FloatLeft { float:left; }"); string minifiedCss = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}"; string css2 = TestUtilities.NormalizeLineEndings(@" li { margin-bottom:0.1em; margin-left:0; margin-top:0.1em; } th { font-weight:normal; vertical-align:bottom; }"); string minifiedCss2 = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}"; CSSBundleFactory cssBundleFactory; IHasher stubHasher; [SetUp] public void Setup() { stubHasher = new StubHasher("hash"); cssBundleFactory = new CSSBundleFactory() .WithHasher(stubHasher); } [Test] public void CanRenderEmptyBundle_WithHashInFilename() { cssBundleFactory.Create().Render("~/css/output_#.css"); } [Test] public void CanBundleCss() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); } [Test] public void CanBundleCssWithMinifiedFiles() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .AddMinified(secondPath) .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); var output = TestUtilities.NormalizeLineEndings(cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); Assert.IsTrue(output.StartsWith(minifiedCss)); Assert.IsTrue(output.EndsWith(css2)); } [Test] public void CanBundleCssWithMinifiedStrings() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); string tag = cssBundle .AddString(css) .AddMinifiedString(css2) .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); var output = TestUtilities.NormalizeLineEndings(cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); Assert.IsTrue(output.StartsWith(minifiedCss)); Assert.IsTrue(output.EndsWith(css2)); } [Test] public void CanBundleCssWithMinifiedDirectories() { var path = Guid.NewGuid().ToString(); var path2 = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css"); var file2 = TestUtilities.PrepareRelativePath(path2 + "\\file2.css"); var resolver = new Mock<IResolver>(MockBehavior.Strict); resolver.Setup(r => r.IsDirectory(It.IsAny<string>())).Returns(true); resolver.Setup(r => r.ResolveFolder(TestUtilities.PrepareRelativePath(path), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>())) .Returns(new[] { file1 }); resolver.Setup(r => r.ResolveFolder(TestUtilities.PrepareRelativePath(path2), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>())) .Returns(new[] { file2 }); using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, resolver.Object)) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, css2); frf.SetContentsForFile(file2, css); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(false) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .WithHasher(new StubHasher("hashy")) .Create() .AddDirectory(path) .AddMinifiedDirectory(path2) .Render("~/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hashy\" />", tag); var content = writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")]; Assert.True(content.StartsWith(minifiedCss2)); Assert.True(content.EndsWith(css)); } } [Test] public void CanBundleCssSpecifyingOutputLinkPath() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithOutputBaseHref("http//subdomain.domain.com") .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http//subdomain.domain.com/css/output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); } [Test] public void CanBundleCssVaryingOutputBaseHrefRendersIndependentUrl() { //Verify that depending on basehref, we get independently cached and returned URLs CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithOutputBaseHref("http://subdomain.domain.com") .Render("/css/output.css"); CSSBundle cssBundleNoBaseHref = cssBundleFactory .WithDebuggingEnabled(false) .Create(); string tagNoBaseHref = cssBundleNoBaseHref .Add(firstPath) .Add(secondPath) .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://subdomain.domain.com/css/output.css?r=hash\" />", tag); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output.css?r=hash\" />", tagNoBaseHref); } [Test] public void RenderNamedUsesOutputBaseHref() { //Verify that depending on basehref, we get independantly cached and returned URLs CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); cssBundleFactory.FileReaderFactory.SetContents(css); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); cssBundle .Add(firstPath) .Add(secondPath) .WithOutputBaseHref("http://subdomain.domain.com") .AsNamed("leBundle", "/css/output.css"); var tag = cssBundleFactory .WithDebuggingEnabled(false) .Create() .WithOutputBaseHref("http://subdomain.domain.com") .RenderNamed("leBundle"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://subdomain.domain.com/css/output.css?r=hash\" />", tag); } [Test] public void CanBundleCssWithQueryStringParameter() { CSSBundle cssBundle = cssBundleFactory .WithContents(css) .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .Render("/css/output_querystring.css?v=1"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_querystring.css?v=1&r=hash\" />", tag); } [Test] public void CanBundleCssWithoutRevisionHash() { CSSBundle cssBundle = cssBundleFactory .WithContents(css) .WithDebuggingEnabled(false) .Create(); string tag = cssBundle .Add("/css/first.css") .Add("/css/second.css") .WithoutRevisionHash() .Render("/css/output_querystring.css?v=1"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_querystring.css?v=1\" />", tag); } [Test] public void CanBundleCssWithMediaAttribute() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithAttribute("media", "screen") .Render("/css/css_with_media_output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/css_with_media_output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}" , cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_media_output.css")]); } [Test] public void CanBundleCssWithRemote() { //this is rendering tag correctly but incorrectly(?) merging both files using(new ResolverFactoryScope(typeof(HttpResolver).FullName, StubResolver.ForFile("http://www.someurl.com/css/first.css"))) { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); string tag = cssBundle .AddRemote("/css/first.css", "http://www.someurl.com/css/first.css") .Add("/css/second.css") .Render("/css/output_remote.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.someurl.com/css/first.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_remote.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_remote.css")]); } } [Test] public void CanBundleCssWithEmbeddedResource() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); string tag = cssBundle .AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css") .Render("/css/output_embedded.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_embedded.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_embedded.css")]); } [Test] public void CanBundleCssWithEmbeddedResourceAndPathRewrites() { var cssWithRelativePath = @".lightbox { background:url(images/button-loader.gif) #ccc; }"; var expectedCss = @".lightbox{background:url(css/images/button-loader.gif) #ccc}"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(cssWithRelativePath) .Create(); string tag = cssBundle .AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css") .Render("/output_embedded.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/output_embedded.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(expectedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"output_embedded.css")]); } [Test] public void CanBundleCssWithRootEmbeddedResource() { //this only tests that the resource can be resolved CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); string tag = cssBundle .AddRootEmbeddedResource("~/css/test.css", "SquishIt.Tests://RootEmbedded.css") .Render("/css/output_embedded.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_embedded.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_embedded.css")]); } [Test] public void CanDebugBundleCssWithEmbedded() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .AddEmbeddedResource("/css/first.css", "SquishIt.Tests://EmbeddedResource.Embedded.css") .Render("/css/output_embedded.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); } [Test] public void CanCreateNamedBundle() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundle .Add("~/css/temp.css") .AsNamed("Test", "~/css/output.css"); string tag = cssBundle.RenderNamed("Test"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/output.css?r=hash\" />", tag); } [Test] public void CanCreateNamedBundleWithDebug() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); cssBundle .Add("~/css/temp1.css") .Add("~/css/temp2.css") .AsNamed("TestWithDebug", "~/css/output.css"); string tag = cssBundle.RenderNamed("TestWithDebug"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp2.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanCreateNamedBundleWithMediaAttribute() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundle .Add("~/css/temp.css") .WithAttribute("media", "screen") .AsNamed("TestWithMedia", "~/css/output.css"); string tag = cssBundle.RenderNamed("TestWithMedia"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output.css")]); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"css/output.css?r=hash\" />", tag); } [Test] public void CanRenderDebugTags() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .Add("/css/first.css") .Add("/css/second.css") .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanRenderPreprocessedDebugTags() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .WithPreprocessor(new StubStylePreprocessor()) .Add("~/first.style.css") .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"first.style.css.squishit.debug.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanRenderDebugTagsTwice() { CSSBundle cssBundle1 = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); CSSBundle cssBundle2 = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag1 = cssBundle1 .Add("/css/first.css") .Add("/css/second.css") .Render("/css/output.css"); string tag2 = cssBundle2 .Add("/css/first.css") .Add("/css/second.css") .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag1)); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag2)); } [Test] public void CanRenderDebugTagsWithMediaAttribute() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .Add("/css/first.css") .Add("/css/second.css") .WithAttribute("media", "screen") .Render("/css/output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanBundleCssWithCompressorAttribute() { var cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); var tag = cssBundle .Add(firstPath) .Add(secondPath) .WithMinifier<YuiMinifier>() .Render("/css/css_with_compressor_output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/css_with_compressor_output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}" , cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_compressor_output.css")]); } [Test] public void CanBundleCssWithNullCompressorAttribute() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithMinifier<NullMinifier>() .Render("/css/css_with_null_compressor_output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/css_with_null_compressor_output.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(css + "\n" + css2 + "\n", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\css_with_null_compressor_output.css")]); } [Test] public void CanBundleCssWithCompressorInstance() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithMinifier<MsMinifier>() .Render("/css/compressor_instance.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/compressor_instance.css?r=hash\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}" , cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\compressor_instance.css")]); } [Test] public void CanRenderOnlyIfFileMissing() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundleFactory.FileReaderFactory.SetFileExists(false); cssBundle .Add("/css/first.css") .Render("~/css/can_render_only_if_file_missing.css"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_render_only_if_file_missing.css")]); cssBundleFactory.FileReaderFactory.SetContents(css2); cssBundleFactory.FileReaderFactory.SetFileExists(true); cssBundle.ClearCache(); cssBundle .Add("/css/first.css") .RenderOnlyIfOutputFileMissing() .Render("~/css/can_render_only_if_file_missing.css"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_render_only_if_file_missing.css")]); } [Test] public void CanRerenderFiles() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundleFactory.FileReaderFactory.SetFileExists(false); cssBundle.ClearCache(); cssBundle .Add("/css/first.css") .Render("~/css/can_rerender_files.css"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_rerender_files.css")]); CSSBundle cssBundle2 = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css2) .Create(); cssBundleFactory.FileReaderFactory.SetFileExists(true); cssBundleFactory.FileWriterFactory.Files.Clear(); cssBundle.ClearCache(); cssBundle2 .Add("/css/first.css") .Render("~/css/can_rerender_files.css"); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\can_rerender_files.css")]); } [Test] public void CanRenderCssFileWithHashInFileName() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .Render("/css/output_#.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/output_hash.css\" />", tag); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\output_hash.css")]); } [Test] public void CanRenderCssFileWithUnprocessedImportStatement() { string importCss = @" @import url(""/css/other.css""); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContents(importCss); cssBundleFactory.FileReaderFactory.SetContentsForFile(@"C:\css\other.css", "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .Render("/css/unprocessed_import.css"); Assert.AreEqual(@"@import url(""/css/other.css"");#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\unprocessed_import.css")]); } [Test] public void CanRenderCssFileWithImportStatement() { string importCss = @" @import url(""/css/other.css""); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContents(importCss); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .ProcessImports() .Render("/css/processed_import.css"); Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import.css")]); } [Test] public void CanRenderCssFileWithRelativeImportStatement() { string importCss = @" @import url(""other.css""); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContents(importCss); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .ProcessImports() .Render("/css/processed_import.css"); Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import.css")]); } [Test] public void CanRenderCssFileWithImportStatementNoQuotes() { string importCss = @" @import url(/css/other.css); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .ProcessImports() .Render("/css/processed_import_noquotes.css"); Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_noquotes.css")]); } [Test] public void CanRenderCssFileWithImportStatementSingleQuotes() { string importCss = @" @import url('/css/other.css'); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .ProcessImports() .Render("/css/processed_import_singlequotes.css"); Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_singlequotes.css")]); } [Test] public void CanRenderCssFileWithImportStatementUppercase() { string importCss = @" @IMPORT URL(/css/other.css); #header { color: #4D926F; }"; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(importCss) .Create(); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(@"css\other.css"), "#footer{color:#ffffff}"); cssBundle .Add("/css/first.css") .ProcessImports() .Render("/css/processed_import_uppercase.css"); Assert.AreEqual("#footer{color:#fff}#header{color:#4d926f}", cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\processed_import_uppercase.css")]); } [Test] public void CanCreateNamedBundleWithForceRelease() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); cssBundle .Add("~/css/temp.css") .ForceRelease() .AsNamed("TestForce", "~/css/named_withforce.css"); string tag = cssBundle.RenderNamed("TestForce"); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"css\named_withforce.css")]); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/named_withforce.css?r=hash\" />", tag); } [Test] public void CanBundleCssWithArbitraryAttributes() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var firstPath = "first.css"; var secondPath = "second.css"; cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), css); cssBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), css2); string tag = cssBundle .Add(firstPath) .Add(secondPath) .WithAttribute("media", "screen") .WithAttribute("test", "other") .Render("/css/css_with_attribute_output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/css_with_attribute_output.css?r=hash\" />", tag); } [Test] public void CanBundleDebugCssWithArbitraryAttributes() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .Add("/css/first.css") .Add("/css/second.css") .WithAttribute("media", "screen") .WithAttribute("test", "other") .Render("/css/css_with_debugattribute_output.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/first.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" test=\"other\" href=\"/css/second.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanCreateCachedBundle() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); string tag = cssBundle .Add("~/css/temp.css") .AsCached("TestCached", "~/static/css/TestCached.css"); string contents = cssBundle.RenderCached("TestCached"); Assert.AreEqual(minifiedCss, contents); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"static/css/TestCached.css?r=hash\" />", tag); } [Test] public void CanCreateCachedBundleAssetTag() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundle .Add("~/css/temp.css") .AsCached("TestCached", "~/static/css/TestCached.css"); string contents = cssBundle.RenderCached("TestCached"); cssBundle.ClearCache(); string tag = cssBundle.RenderCachedAssetTag("TestCached"); Assert.AreEqual(minifiedCss, contents); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"static/css/TestCached.css?r=hash\" />", tag); } [Test] public void CanCreateCachedBundleAssetTag_When_Debugging() { var cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .Create(); cssBundle .Add("~/css/temp.css") .AsCached("TestCached", "~/static/css/TestCached.css"); var tag = cssBundle.RenderCachedAssetTag("TestCached"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanCreateCachedBundleInDebugMode() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); string tag = cssBundle .Add("~/css/temp.css") .AsCached("TestCached", "~/static/css/TestCached.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/temp.css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanBundleDirectoryContentsInDebug() { var path = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css"); var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css"); using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 }))) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, css2); frf.SetContentsForFile(file2, css); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(true) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .Create() .Add(path) .Render("~/output.css"); var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file2.css\" />\n", path); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } } [Test] public void CanBundleDirectoryContentsInDebug_Ignores_Duplicates() { var path = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css"); var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css"); using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 }))) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, css2); frf.SetContentsForFile(file2, css); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(true) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .Create() .Add(path) .Render("~/output.css"); var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file2.css\" />\n", path); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } } [Test] public void CanBundleDirectoryContentsInDebug_Writes_And_Ignores_Preprocessed_Debug_Files() { var path = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.style.css"); var file2 = TestUtilities.PrepareRelativePath(path + "\\file1.style.squishit.debug.css"); var content = "some stuffs"; var preprocessor = new StubStylePreprocessor(); using(new StylePreprocessorScope<StubStylePreprocessor>(preprocessor)) using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 }))) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, content); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(true) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .Create() .Add(path) .Render("~/output.css"); var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/file1.style.css.squishit.debug.css\" />\n", path); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); Assert.AreEqual(content, preprocessor.CalledWith); Assert.AreEqual(1, writerFactory.Files.Count); Assert.AreEqual("styley", writerFactory.Files[file1 + ".squishit.debug.css"]); } } [Test] public void CanBundleDirectoryContentsInRelease() { var path = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css"); var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css"); using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 }))) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, css2); frf.SetContentsForFile(file2, css); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(false) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .Create() .Add(path) .Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, tag); var combined = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}"; Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")]); } } [Test] public void CanBundleDirectoryContentsInRelease_Ignores_Duplicates() { var path = Guid.NewGuid().ToString(); var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.css"); var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.css"); using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 }))) { var frf = new StubFileReaderFactory(); frf.SetContentsForFile(file1, css2); frf.SetContentsForFile(file2, css); var writerFactory = new StubFileWriterFactory(); var tag = cssBundleFactory.WithDebuggingEnabled(false) .WithFileReaderFactory(frf) .WithFileWriterFactory(writerFactory) .Create() .Add(path) .Add(file1) .Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, tag); var combined = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}"; Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.css")]); } } [Test] public void CanRenderArbitraryStringsInDebug() { var css2Format = "{0}{1}"; var hrColor = "hr {color:sienna;}"; var p = "p {margin-left:20px;}"; var tag = new CSSBundleFactory() .WithDebuggingEnabled(true) .Create() .AddString(css) .AddString(css2Format, new[] { hrColor, p }) .Render("doesn't matter where..."); var expectedTag = string.Format("<style type=\"text/css\">{0}</style>\n<style type=\"text/css\">{1}</style>\n", css, string.Format(css2Format, hrColor, p)); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanMaintainOrderBetweenArbitraryAndFileAssetsInRelease() { var file1 = "somefile.css"; var file2 = "anotherfile.css"; var arbitraryCss = ".someClass { color:red }"; var minifiedArbitraryCss = ".someClass{color:red}"; var readerFactory = new StubFileReaderFactory(); readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), css); readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), css2); var writerFactory = new StubFileWriterFactory(); var tag = new CSSBundleFactory() .WithFileReaderFactory(readerFactory) .WithFileWriterFactory(writerFactory) .WithDebuggingEnabled(false) .Create() .Add(file1) .AddString(arbitraryCss) .Add(file2) .Render("test.css"); var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css?r=hash\" />"); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); var combined = minifiedCss + minifiedArbitraryCss + minifiedCss2; Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"test.css")]); } [Test] public void CanMaintainOrderBetweenArbitraryAndFileAssetsInDebug() { var file1 = "somefile.css"; var file2 = "anotherfile.css"; var arbitraryCss = ".someClass { color:red }"; var readerFactory = new StubFileReaderFactory(); readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), css); readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), css2); var writerFactory = new StubFileWriterFactory(); var tag = new CSSBundleFactory() .WithFileReaderFactory(readerFactory) .WithFileWriterFactory(writerFactory) .WithDebuggingEnabled(true) .Create() .Add(file1) .AddString(arbitraryCss) .Add(file2) .Render("test.css"); var expectedTag = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"somefile.css\" />\n<style type=\"text/css\">{0}</style>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anotherfile.css\" />\n" , arbitraryCss); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanRenderArbitraryStringsInDebugWithoutType() { var css2Format = "{0}{1}"; var hrColor = "hr {color:sienna;}"; var p = "p {margin-left:20px;}"; var tag = new CSSBundleFactory() .WithDebuggingEnabled(true) .Create() .AddString(css) .AddString(css2Format, new[] { hrColor, p }) .WithoutTypeAttribute() .Render("doesn't matter where..."); var expectedTag = string.Format("<style>{0}</style>\n<style>{1}</style>\n", css, string.Format(css2Format, hrColor, p)); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } [Test] public void DoesNotRenderDuplicateArbitraryStringsInDebug() { var tag = new CSSBundleFactory() .WithDebuggingEnabled(true) .Create() .AddString(css) .AddString(css) .Render("doesn't matter where..."); var expectedTag = string.Format("<style type=\"text/css\">{0}</style>\n", css); Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanBundleArbitraryContentsInRelease() { var css2Format = "{0}{1}"; var hrColor = "hr {color:sienna;}"; var p = "p {margin-left:20px;}"; var writerFactory = new StubFileWriterFactory(); var tag = new CSSBundleFactory() .WithDebuggingEnabled(false) .WithFileWriterFactory(writerFactory) .WithHasher(new StubHasher("hashy")) .Create() .AddString(css) .AddString(css2Format, new[] { hrColor, p }) .Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hashy\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); var minifiedScript = "li{margin-bottom:.1em;margin-left:0;margin-top:.1em}th{font-weight:normal;vertical-align:bottom}.FloatRight{float:right}.FloatLeft{float:left}hr{color:#a0522d}p{margin-left:20px}"; Assert.AreEqual(minifiedScript, writerFactory.Files[TestUtilities.PrepareRelativePath("output.css")]); } [Test] public void PathRewritingDoesNotAffectClassesNamedUrl() { string css = @" a.url { color: #4D926F; } "; CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); cssBundle .Add("~/css/something/test.css") .Render("~/css/output_rewriting_url.css"); string contents = cssBundleFactory.FileWriterFactory.Files[ TestUtilities.PrepareRelativePath(@"css\output_rewriting_url.css")]; Assert.AreEqual("a.url{color:#4d926f}", contents); } [Test] public void CanUseArbitraryReleaseFileRenderer() { var renderer = new Mock<IRenderer>(); var content = "content"; cssBundleFactory .WithDebuggingEnabled(false) .Create() .WithReleaseFileRenderer(renderer.Object) .AddString(content) .Render("test.css"); renderer.Verify(r => r.Render(content, TestUtilities.PrepareRelativePath("test.css"))); } [Test] public void CanIgnoreArbitraryReleaseFileRendererIfDebugging() { var renderer = new Mock<IRenderer>(MockBehavior.Strict); var content = "content"; cssBundleFactory .WithDebuggingEnabled(true) .Create() .WithReleaseFileRenderer(renderer.Object) .AddString(content) .Render("test.css"); renderer.VerifyAll(); } [Test] public void CanIgnoreArbitraryReleaseRendererInDebug() { var renderer = new Mock<IRenderer>(); var content = "content"; cssBundleFactory .WithDebuggingEnabled(true) .Create() .WithReleaseFileRenderer(renderer.Object) .AddString(content) .Render("test.css"); renderer.VerifyAll(); } [Test] public void CanIncludeDynamicContentInDebug() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); request.SetupGet(r => r.Url).Returns(new Uri("http://example.com")); context.SetupGet(c => c.Request).Returns(request.Object); var bundle = cssBundleFactory .WithDebuggingEnabled(true) .Create(); using(new HttpContextScope(context.Object)) { bundle.AddDynamic("/some/dynamic/css"); } var tag = bundle.Render("~/combined_#.css"); Assert.AreEqual(0, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"/some/dynamic/css\" />\n", TestUtilities.NormalizeLineEndings(tag)); } [Test] public void CanIncludeDynamicContentInRelease() { //this doesn't really test the nitty-gritty details (http resolver, download etc...) but its a start var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); request.SetupGet(r => r.Url).Returns(new Uri("http://example.com")); context.SetupGet(c => c.Request).Returns(request.Object); var bundle = cssBundleFactory .WithContents(css) .WithDebuggingEnabled(false) .Create(); using(new HttpContextScope(context.Object)) { //some/dynamic/css started returning 404's bundle.AddDynamic("/"); } var tag = bundle.Render("~/combined.css"); Assert.AreEqual(1, cssBundleFactory.FileWriterFactory.Files.Count); Assert.AreEqual(minifiedCss, cssBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath("combined.css")]); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"combined.css?r=hash\" />", tag); } [Test] public void RenderRelease_OmitsRenderedTag_IfOnlyRemoteAssets() { //this is rendering tag correctly but incorrectly(?) merging both files using(new ResolverFactoryScope(typeof(Framework.Resolvers.HttpResolver).FullName, StubResolver.ForFile("http://www.someurl.com/css/first.css"))) { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); string tag = cssBundle .ForceRelease() .AddRemote("/css/first.css", "http://www.someurl.com/css/first.css") .Render("/css/output_remote.css"); Assert.AreEqual("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.someurl.com/css/first.css\" />", tag); Assert.AreEqual(0, cssBundleFactory.FileWriterFactory.Files.Count); } } [Test] public void CanRenderDistinctBundlesIfSameOutputButDifferentFileNames() { var hasher = new Hasher(new RetryableFileOpener()); CSSBundle cssBundle = cssBundleFactory .WithHasher(hasher) .WithDebuggingEnabled(false) .Create(); CSSBundle cssBundle2 = cssBundleFactory .WithHasher(hasher) .WithDebuggingEnabled(false) .Create(); cssBundleFactory.FileReaderFactory.SetContents(css); string tag = cssBundle .Add("/css/first.css") .Render("/css/output#.css"); cssBundleFactory.FileReaderFactory.SetContents(css2); string tag2 = cssBundle2 .Add("/css/second.css") .Render("/css/output#.css"); Assert.AreNotEqual(tag, tag2); } [Test] public void CanRenderDistinctBundlesIfSameOutputButDifferentArbitrary() { var hasher = new Hasher(new RetryableFileOpener()); CSSBundle cssBundle = cssBundleFactory .WithHasher(hasher) .WithDebuggingEnabled(false) .Create(); CSSBundle cssBundle2 = cssBundleFactory .WithHasher(hasher) .WithDebuggingEnabled(false) .Create(); string tag = cssBundle .AddString(css) .Render("/css/output#.css"); string tag2 = cssBundle2 .AddString(css2) .Render("/css/output#.css"); Assert.AreNotEqual(tag, tag2); } [Test] public void ForceDebugIf() { cssBundleFactory.FileReaderFactory.SetContents(css); var file1 = "test.css"; var file2 = "anothertest.css"; Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true"; var nonDebugContext = new Mock<HttpContextBase>(); nonDebugContext.Setup(hcb => hcb.Request.ApplicationPath).Returns(string.Empty); nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection()); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); CSSBundle bundle; using(new HttpContextScope(nonDebugContext.Object)) { bundle = cssBundleFactory .WithDebuggingEnabled(false) .Create() .Add(file1) .Add(file2) .ForceDebugIf(queryStringPredicate); var tag = bundle.Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } var debugContext = new Mock<HttpContextBase>(); debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } }); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); using(new HttpContextScope(debugContext.Object)) { var tag = bundle.Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } using(new HttpContextScope(nonDebugContext.Object)) { var tag = bundle.Render("~/output.css"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } } [Test] public void ForceDebugIf_Named() { cssBundleFactory.FileReaderFactory.SetContents(css); var file1 = "test.css"; var file2 = "anothertest.css"; Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true"; var debugContext = new Mock<HttpContextBase>(); debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } }); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); var nonDebugContext = new Mock<HttpContextBase>(); nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection()); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); using(new HttpContextScope(nonDebugContext.Object)) { cssBundleFactory .WithDebuggingEnabled(false) .Create() .Add(file1) .Add(file2) .ForceDebugIf(queryStringPredicate) .AsNamed("test", "~/output.css"); var tag = cssBundleFactory .Create() .RenderNamed("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } using(new HttpContextScope(debugContext.Object)) { var tag = cssBundleFactory .Create() .RenderNamed("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } using(new HttpContextScope(nonDebugContext.Object)) { var tag = cssBundleFactory .Create() .RenderNamed("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } } [Test] public void ForceDebugIf_Cached() { cssBundleFactory.FileReaderFactory.SetContents(css); var file1 = "test.css"; var file2 = "anothertest.css"; Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true"; var debugContext = new Mock<HttpContextBase>(); debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } }); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); debugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); var nonDebugContext = new Mock<HttpContextBase>(); nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection()); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2)); nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.css")).Returns(Path.Combine(Environment.CurrentDirectory, "output.css")); using(new HttpContextScope(nonDebugContext.Object)) { cssBundleFactory .WithDebuggingEnabled(false) .Create() .Add(file1) .Add(file2) .ForceDebugIf(queryStringPredicate) .AsCached("test", "~/output.css"); var tag = cssBundleFactory .Create() .RenderNamed("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } using(new HttpContextScope(debugContext.Object)) { var tag = cssBundleFactory .Create() .RenderCachedAssetTag("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"anothertest.css\" />\n"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } using(new HttpContextScope(nonDebugContext.Object)) { var tag = cssBundleFactory .Create() .RenderCachedAssetTag("test"); var expectedTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"output.css?r=hash\" />"; Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag)); } } [Test] public void CanRenderRawContent_Release() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(false) .WithContents(css) .Create(); var contents = cssBundle.Add("~/test/sample.js").RenderRawContent("testrelease"); Assert.AreEqual(minifiedCss, contents); Assert.AreEqual(contents, cssBundleFactory.Create().RenderCachedRawContent("testrelease")); } [Test] public void CanRenderRawContent_Debug() { CSSBundle cssBundle = cssBundleFactory .WithDebuggingEnabled(true) .WithContents(css) .Create(); var contents = cssBundle.Add("~/test/sample.js").RenderRawContent("testdebug"); Assert.AreEqual(css, contents); Assert.AreEqual(contents, cssBundleFactory.Create().RenderCachedRawContent("testdebug")); } } }
// 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.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { private static string ConvertToString(ExpressionSyntax expression) { var converted = expression.ConvertToSingleLine(); return converted.ToString(); } private static void AddExpressionTerms(ExpressionSyntax expression, IList<string> terms) { // Check here rather than at all the call sites... if (expression == null) { return; } // Collect terms from this expression, which returns flags indicating the validity // of this expression as a whole. var expressionType = ExpressionType.Invalid; AddSubExpressionTerms(expression, terms, ref expressionType); AddIfValidTerm(expression, expressionType, terms); } private static void AddIfValidTerm(ExpressionSyntax expression, ExpressionType type, IList<string> terms) { if (IsValidTerm(type)) { // If this expression identified itself as a valid term, add it to the // term table terms.Add(ConvertToString(expression)); } } private static bool IsValidTerm(ExpressionType type) { return (type & ExpressionType.ValidTerm) == ExpressionType.ValidTerm; } private static bool IsValidExpression(ExpressionType type) { return (type & ExpressionType.ValidExpression) == ExpressionType.ValidExpression; } private static void AddSubExpressionTerms(ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Check here rather than at all the call sites... if (expression == null) { return; } switch (expression.Kind()) { case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: // an op term is ok if it's a "this" or "base" op it allows us to see // "this.foo" in the autos window note: it's not a VALIDTERM since we don't // want "this" showing up in the auto's window twice. expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.IdentifierName: // Name nodes are always valid terms expressionType = ExpressionType.ValidTerm; return; case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: // Constants can make up a valid term, but we don't consider them valid // terms themselves (since we don't want them to show up in the autos window // on their own). expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.CastExpression: AddCastExpressionTerms((CastExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: AddMemberAccessExpressionTerms((MemberAccessExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.ObjectCreationExpression: AddObjectCreationExpressionTerms((ObjectCreationExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.ArrayCreationExpression: AddArrayCreationExpressionTerms((ArrayCreationExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.InvocationExpression: AddInvocationExpressionTerms((InvocationExpressionSyntax)expression, terms, ref expressionType); return; } // +, -, ++, --, !, etc. // // This is a valid expression if it doesn't have obvious side effects (i.e. ++, --) if (expression is PrefixUnaryExpressionSyntax prefixUnary) { AddPrefixUnaryExpressionTerms(prefixUnary, terms, ref expressionType); return; } if (expression is AwaitExpressionSyntax awaitExpression) { AddAwaitExpressionTerms(awaitExpression, terms, ref expressionType); return; } if (expression is PostfixUnaryExpressionSyntax postfixExpression) { AddPostfixUnaryExpressionTerms(postfixExpression, terms, ref expressionType); return; } if (expression is BinaryExpressionSyntax binaryExpression) { AddBinaryExpressionTerms(expression, binaryExpression.Left, binaryExpression.Right, terms, ref expressionType); return; } if (expression is AssignmentExpressionSyntax assignmentExpression) { AddBinaryExpressionTerms(expression, assignmentExpression.Left, assignmentExpression.Right, terms, ref expressionType); return; } if (expression is ConditionalExpressionSyntax conditional) { AddConditionalExpressionTerms(conditional, terms, ref expressionType); return; } if (expression is ParenthesizedExpressionSyntax parenthesizedExpression) { AddSubExpressionTerms(parenthesizedExpression.Expression, terms, ref expressionType); } expressionType = ExpressionType.Invalid; } private static void AddCastExpressionTerms(CastExpressionSyntax castExpression, IList<string> terms, ref ExpressionType expressionType) { // For a cast, just add the nested expression. Note: this is technically // unsafe as the cast *may* have side effects. However, in practice this is // extremely rare, so we allow for this since it's ok in the common case. var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(castExpression.Expression, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(castExpression.Expression, flags, terms); // If the subexpression is a valid term, so is the cast expression expressionType = flags; } private static void AddMemberAccessExpressionTerms(MemberAccessExpressionSyntax memberAccessExpression, IList<string> terms, ref ExpressionType expressionType) { var flags = ExpressionType.Invalid; // These operators always have a RHS of a name node, which we know would // "claim" to be a valid term, but is not valid without the LHS present. // So, we don't bother collecting anything from the RHS... AddSubExpressionTerms(memberAccessExpression.Expression, terms, ref flags); // If the LHS says it's a valid term, then we add it ONLY if our PARENT // is NOT another dot/arrow. This allows the expression 'a.b.c.d' to // add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'. if (IsValidTerm(flags) && !memberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && !memberAccessExpression.IsParentKind(SyntaxKind.PointerMemberAccessExpression)) { terms.Add(ConvertToString(memberAccessExpression.Expression)); } // And this expression itself is a valid term if the LHS is a valid // expression, and its PARENT is not an invocation. if (IsValidExpression(flags) && !memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression)) { expressionType = ExpressionType.ValidTerm; } else { expressionType = ExpressionType.ValidExpression; } } private static void AddObjectCreationExpressionTerms(ObjectCreationExpressionSyntax objectionCreationExpression, IList<string> terms, ref ExpressionType expressionType) { // Object creation can *definitely* cause side effects. So we initially // mark this as something invalid. We allow it as a valid expr if all // the sub arguments are valid terms. expressionType = ExpressionType.Invalid; if (objectionCreationExpression.ArgumentList != null) { var flags = ExpressionType.Invalid; AddArgumentTerms(objectionCreationExpression.ArgumentList, terms, ref flags); // If all arguments are terms, then this is possibly a valid expr that can be used // somewhere higher in the stack. if (IsValidTerm(flags)) { expressionType = ExpressionType.ValidExpression; } } } private static void AddArrayCreationExpressionTerms( ArrayCreationExpressionSyntax arrayCreationExpression, IList<string> terms, ref ExpressionType expressionType) { var validTerm = true; if (arrayCreationExpression.Initializer != null) { var flags = ExpressionType.Invalid; arrayCreationExpression.Initializer.Expressions.Do(e => AddSubExpressionTerms(e, terms, ref flags)); validTerm &= IsValidTerm(flags); } if (validTerm) { expressionType = ExpressionType.ValidExpression; } else { expressionType = ExpressionType.Invalid; } } private static void AddInvocationExpressionTerms(InvocationExpressionSyntax invocationExpression, IList<string> terms, ref ExpressionType expressionType) { // Invocations definitely have side effects. So we assume this // is invalid initially; expressionType = ExpressionType.Invalid; ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; AddSubExpressionTerms(invocationExpression.Expression, terms, ref leftFlags); AddArgumentTerms(invocationExpression.ArgumentList, terms, ref rightFlags); AddIfValidTerm(invocationExpression.Expression, leftFlags, terms); // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; } private static void AddPrefixUnaryExpressionTerms(PrefixUnaryExpressionSyntax prefixUnaryExpression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(prefixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(prefixUnaryExpression.Operand, flags, terms); if (prefixUnaryExpression.IsKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression)) { // We're a valid expression if our subexpression is... expressionType = flags & ExpressionType.ValidExpression; } } private static void AddAwaitExpressionTerms(AwaitExpressionSyntax awaitExpression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(awaitExpression.Expression, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(awaitExpression.Expression, flags, terms); } private static void AddPostfixUnaryExpressionTerms(PostfixUnaryExpressionSyntax postfixUnaryExpression, IList<string> terms, ref ExpressionType expressionType) { // ++ and -- are the only postfix operators. Since they always have side // effects, we never consider this an expression. expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(postfixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(postfixUnaryExpression.Operand, flags, terms); } private static void AddConditionalExpressionTerms(ConditionalExpressionSyntax conditionalExpression, IList<string> terms, ref ExpressionType expressionType) { ExpressionType conditionFlags = ExpressionType.Invalid, trueFlags = ExpressionType.Invalid, falseFlags = ExpressionType.Invalid; AddSubExpressionTerms(conditionalExpression.Condition, terms, ref conditionFlags); AddSubExpressionTerms(conditionalExpression.WhenTrue, terms, ref trueFlags); AddSubExpressionTerms(conditionalExpression.WhenFalse, terms, ref falseFlags); AddIfValidTerm(conditionalExpression.Condition, conditionFlags, terms); AddIfValidTerm(conditionalExpression.WhenTrue, trueFlags, terms); AddIfValidTerm(conditionalExpression.WhenFalse, falseFlags, terms); // We're valid if all children are... expressionType = (conditionFlags & trueFlags & falseFlags) & ExpressionType.ValidExpression; } private static void AddBinaryExpressionTerms(ExpressionSyntax binaryExpression, ExpressionSyntax left, ExpressionSyntax right, IList<string> terms, ref ExpressionType expressionType) { ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; AddSubExpressionTerms(left, terms, ref leftFlags); AddSubExpressionTerms(right, terms, ref rightFlags); if (IsValidTerm(leftFlags)) { terms.Add(ConvertToString(left)); } if (IsValidTerm(rightFlags)) { terms.Add(ConvertToString(right)); } // Many sorts of binops (like +=) will definitely have side effects. We only // consider this valid if it's a simple expression like +, -, etc. switch (binaryExpression.Kind()) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.CoalesceExpression: // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; return; default: expressionType = ExpressionType.Invalid; return; } } private static void AddArgumentTerms(ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType) { var validExpr = true; var validTerm = true; // Process the list of expressions. This is probably a list of // arguments to a function call(or a list of array index expressions) foreach (var arg in argumentList.Arguments) { var flags = ExpressionType.Invalid; AddSubExpressionTerms(arg.Expression, terms, ref flags); if (IsValidTerm(flags)) { terms.Add(ConvertToString(arg.Expression)); } validExpr &= IsValidExpression(flags); validTerm &= IsValidTerm(flags); } // We're never a valid term if all arguments were valid terms. If not, we're a valid // expression if all arguments where. Otherwise, we're just invalid. expressionType = validTerm ? ExpressionType.ValidTerm : validExpr ? ExpressionType.ValidExpression : ExpressionType.Invalid; } } }
// // pinvoke3.cs: // // Tests for native->managed marshalling // using System; using System.Text; using System.Runtime.InteropServices; using System.Threading; public class Tests { [StructLayout (LayoutKind.Sequential)] public struct SimpleStruct { public bool a; public bool b; public bool c; public string d; [MarshalAs(UnmanagedType.LPWStr)] public string d2; } [StructLayout (LayoutKind.Sequential)] public class SimpleClass { public bool a; public bool b; public bool c; public string d; } public static SimpleStruct delegate_test_struct (SimpleStruct ss) { SimpleStruct res; res.a = !ss.a; res.b = !ss.b; res.c = !ss.c; res.d = ss.d + "-RES"; res.d2 = ss.d2 + "-RES"; return res; } public static int delegate_test_struct_byref (int a, ref SimpleStruct ss, int b) { if (a == 1 && b == 2 && ss.a && !ss.b && ss.c && ss.d == "TEST2") { ss.a = true; ss.b = true; ss.c = true; ss.d = "TEST3"; return 0; } return 1; } public static int delegate_test_struct_out (int a, out SimpleStruct ss, int b) { ss.a = true; ss.b = true; ss.c = true; ss.d = "TEST3"; ss.d2 = "TEST4"; return 0; } public static int delegate_test_struct_in (int a, [In] ref SimpleStruct ss, int b) { if (a == 1 && b == 2 && ss.a && !ss.b && ss.c && ss.d == "TEST2") { ss.a = true; ss.b = true; ss.c = true; ss.d = "TEST3"; return 0; } return 1; } public static SimpleClass delegate_test_class (SimpleClass ss) { if (ss == null) return null; if (! (!ss.a && ss.b && !ss.c && ss.d == "TEST")) return null; SimpleClass res = ss; return res; } public static int delegate_test_class_byref (ref SimpleClass ss) { if (ss == null) return -1; if (!ss.a && ss.b && !ss.c && ss.d == "TEST") { ss.a = true; ss.b = false; ss.c = true; ss.d = "RES"; return 0; } return 1; } public static int delegate_test_class_out (out SimpleClass ss) { ss = new SimpleClass (); ss.a = true; ss.b = false; ss.c = true; ss.d = "RES"; return 0; } public static int delegate_test_primitive_byref (ref int i) { if (i != 1) return 1; i = 2; return 0; } public static int delegate_test_string_marshalling (string s) { return s == "ABC" ? 0 : 1; } public static int delegate_test_string_builder_marshalling (StringBuilder s) { if (s == null) return 2; else return s.ToString () == "ABC" ? 0 : 1; } [DllImport ("libtest", EntryPoint="mono_test_ref_vtype")] public static extern int mono_test_ref_vtype (int a, ref SimpleStruct ss, int b, TestDelegate d); public delegate int OutStructDelegate (int a, out SimpleStruct ss, int b); public delegate int InStructDelegate (int a, [In] ref SimpleStruct ss, int b); [DllImport ("libtest", EntryPoint="mono_test_marshal_out_struct")] public static extern int mono_test_marshal_out_struct (int a, out SimpleStruct ss, int b, OutStructDelegate d); [DllImport ("libtest", EntryPoint="mono_test_marshal_in_struct")] public static extern int mono_test_marshal_in_struct (int a, ref SimpleStruct ss, int b, InStructDelegate d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate2")] public static extern int mono_test_marshal_delegate2 (SimpleDelegate2 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate4")] public static extern int mono_test_marshal_delegate4 (SimpleDelegate4 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate5")] public static extern int mono_test_marshal_delegate5 (SimpleDelegate5 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate6")] public static extern int mono_test_marshal_delegate6 (SimpleDelegate5 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate7")] public static extern int mono_test_marshal_delegate7 (SimpleDelegate7 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate8", CharSet=CharSet.Unicode)] public static extern int mono_test_marshal_delegate8 (SimpleDelegate8 d, string s); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate9")] public static extern int mono_test_marshal_delegate9 (SimpleDelegate9 d, return_int_delegate d2); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate10")] public static extern int mono_test_marshal_delegate10 (SimpleDelegate9 d); [DllImport ("libtest", EntryPoint="mono_test_marshal_delegate8")] public static extern int mono_test_marshal_delegate11 (SimpleDelegate11 d, string s); [DllImport ("libtest", EntryPoint="mono_test_marshal_primitive_byref_delegate")] public static extern int mono_test_marshal_primitive_byref_delegate (PrimitiveByrefDelegate d); [DllImport ("libtest", EntryPoint="mono_test_marshal_return_delegate_delegate")] public static extern int mono_test_marshal_return_delegate_delegate (ReturnDelegateDelegate d); public delegate int TestDelegate (int a, ref SimpleStruct ss, int b); public delegate SimpleStruct SimpleDelegate2 (SimpleStruct ss); public delegate SimpleClass SimpleDelegate4 (SimpleClass ss); public delegate int SimpleDelegate5 (ref SimpleClass ss); public delegate int SimpleDelegate7 (out SimpleClass ss); public delegate int SimpleDelegate8 ([MarshalAs (UnmanagedType.LPWStr)] string s1); public delegate int return_int_delegate (int i); public delegate int SimpleDelegate9 (return_int_delegate del); public delegate int SimpleDelegate11 (StringBuilder s1); public delegate int PrimitiveByrefDelegate (ref int i); public delegate return_int_delegate ReturnDelegateDelegate (); public static int Main () { return TestDriver.RunTests (typeof (Tests)); } /* Test structures as arguments and return values of delegates */ public static int test_0_marshal_struct_delegate () { SimpleDelegate2 d = new SimpleDelegate2 (delegate_test_struct); return mono_test_marshal_delegate2 (d); } /* Test structures as byref arguments of delegates */ public static int test_0_marshal_byref_struct_delegate () { SimpleStruct ss = new SimpleStruct (); TestDelegate d = new TestDelegate (delegate_test_struct_byref); ss.b = true; ss.d = "TEST1"; if (mono_test_ref_vtype (1, ref ss, 2, d) != 0) return 1; if (! (ss.a && ss.b && ss.c && ss.d == "TEST3")) return 2; return 0; } /* Test structures as out arguments of delegates */ public static int test_0_marshal_out_struct_delegate () { SimpleStruct ss = new SimpleStruct (); OutStructDelegate d = new OutStructDelegate (delegate_test_struct_out); return mono_test_marshal_out_struct (1, out ss, 2, d); } /* Test structures as in arguments of delegates */ public static int test_0_marshal_in_struct_delegate () { SimpleStruct ss = new SimpleStruct () { a = true, b = false, c = true, d = "TEST2" }; InStructDelegate d = new InStructDelegate (delegate_test_struct_in); return mono_test_marshal_in_struct (1, ref ss, 2, d); } /* Test classes as arguments and return values of delegates */ public static int test_0_marshal_class_delegate () { SimpleDelegate4 d = new SimpleDelegate4 (delegate_test_class); return mono_test_marshal_delegate4 (d); } /* Test classes as byref arguments of delegates */ public static int test_0_marshal_byref_class_delegate () { SimpleDelegate5 d = new SimpleDelegate5 (delegate_test_class_byref); return mono_test_marshal_delegate5 (d); } /* Test classes as out arguments of delegates */ public static int test_0_marshal_out_class_delegate () { SimpleDelegate7 d = new SimpleDelegate7 (delegate_test_class_out); return mono_test_marshal_delegate7 (d); } /* Test string marshalling with delegates */ public static int test_0_marshal_string_delegate () { SimpleDelegate8 d = new SimpleDelegate8 (delegate_test_string_marshalling); return mono_test_marshal_delegate8 (d, "ABC"); } /* Test string builder marshalling with delegates */ public static int test_0_marshal_string_builder_delegate () { SimpleDelegate11 d = new SimpleDelegate11 (delegate_test_string_builder_marshalling); if (mono_test_marshal_delegate11 (d, null) != 2) return 2; return mono_test_marshal_delegate11 (d, "ABC"); } /* Test that the delegate wrapper correctly catches null byref arguments */ public static int test_0_marshal_byref_class_delegate_null () { SimpleDelegate5 d = new SimpleDelegate5 (delegate_test_class_byref); try { mono_test_marshal_delegate6 (d); return 1; } catch (ArgumentNullException ex) { return 0; } } static int return_self (int i) { return i; } static int call_int_delegate (return_int_delegate d) { return d (55); } public static int test_55_marshal_delegate_delegate () { SimpleDelegate9 d = new SimpleDelegate9 (call_int_delegate); return mono_test_marshal_delegate9 (d, new return_int_delegate (return_self)); } public static int test_0_marshal_primitive_byref_delegate () { PrimitiveByrefDelegate d = new PrimitiveByrefDelegate (delegate_test_primitive_byref); return mono_test_marshal_primitive_byref_delegate (d); } public static return_int_delegate return_delegate () { return new return_int_delegate (return_self); } public static int test_55_marshal_return_delegate_delegate () { return mono_test_marshal_return_delegate_delegate (new ReturnDelegateDelegate (return_delegate)); } /* Passing and returning strings */ public delegate String ReturnStringDelegate (String s); [DllImport ("libtest", EntryPoint="mono_test_return_string")] public static extern String mono_test_marshal_return_string_delegate (ReturnStringDelegate d); public static String managed_return_string (String s) { if (s != "TEST") return ""; else return "12345"; } public static int test_0_marshal_return_string_delegate () { ReturnStringDelegate d = new ReturnStringDelegate (managed_return_string); String s = mono_test_marshal_return_string_delegate (d); return (s == "12345") ? 0 : 1; } /* Passing and returning enums */ public enum FooEnum { Foo1, Foo2, Foo3 }; public delegate FooEnum ReturnEnumDelegate (FooEnum e); [DllImport ("libtest", EntryPoint="mono_test_marshal_return_enum_delegate")] public static extern int mono_test_marshal_return_enum_delegate (ReturnEnumDelegate d); public static FooEnum managed_return_enum (FooEnum e) { return (FooEnum)((int)e + 1); } public static int test_0_marshal_return_enum_delegate () { ReturnEnumDelegate d = new ReturnEnumDelegate (managed_return_enum); FooEnum e = (FooEnum)mono_test_marshal_return_enum_delegate (d); return e == FooEnum.Foo3 ? 0 : 1; } /* Passing and returning blittable structs */ [StructLayout (LayoutKind.Sequential)] public struct BlittableStruct { public int a, b, c; public long d; } public static BlittableStruct delegate_test_blittable_struct (BlittableStruct ss) { BlittableStruct res; res.a = -ss.a; res.b = -ss.b; res.c = -ss.c; res.d = -ss.d; return res; } public delegate BlittableStruct SimpleDelegate10 (BlittableStruct ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_blittable_struct_delegate")] public static extern int mono_test_marshal_blittable_struct_delegate (SimpleDelegate10 d); public static int test_0_marshal_blittable_struct_delegate () { return mono_test_marshal_blittable_struct_delegate (new SimpleDelegate10 (delegate_test_blittable_struct)); } /* * Passing and returning small structs */ /* TEST 1: 4 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct1 { public int i; } public static SmallStruct1 delegate_test_struct (SmallStruct1 ss) { SmallStruct1 res; res.i = -ss.i; return res; } public delegate SmallStruct1 SmallStructDelegate1 (SmallStruct1 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate1")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate1 d); public static int test_0_marshal_small_struct_delegate1 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate1 (delegate_test_struct)); } /* TEST 2: 2+2 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct2 { public short i, j; } public static SmallStruct2 delegate_test_struct (SmallStruct2 ss) { SmallStruct2 res; res.i = (short)-ss.i; res.j = (short)-ss.j; return res; } public delegate SmallStruct2 SmallStructDelegate2 (SmallStruct2 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate2")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate2 d); public static int test_0_marshal_small_struct_delegate2 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate2 (delegate_test_struct)); } /* TEST 3: 2+1 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct3 { public short i; public byte j; } public static SmallStruct3 delegate_test_struct (SmallStruct3 ss) { SmallStruct3 res; res.i = (short)-ss.i; res.j = (byte)-ss.j; return res; } public delegate SmallStruct3 SmallStructDelegate3 (SmallStruct3 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate3")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate3 d); public static int test_0_marshal_small_struct_delegate3 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate3 (delegate_test_struct)); } /* TEST 4: 2 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct4 { public short i; } public static SmallStruct4 delegate_test_struct (SmallStruct4 ss) { SmallStruct4 res; res.i = (short)-ss.i; return res; } public delegate SmallStruct4 SmallStructDelegate4 (SmallStruct4 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate4")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate4 d); public static int test_0_marshal_small_struct_delegate4 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate4 (delegate_test_struct)); } /* TEST 5: 8 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct5 { public long l; } public static SmallStruct5 delegate_test_struct (SmallStruct5 ss) { SmallStruct5 res; res.l = -ss.l; return res; } public delegate SmallStruct5 SmallStructDelegate5 (SmallStruct5 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate5")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate5 d); public static int test_0_marshal_small_struct_delegate5 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate5 (delegate_test_struct)); } /* TEST 6: 4+4 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct6 { public int i, j; } public static SmallStruct6 delegate_test_struct (SmallStruct6 ss) { SmallStruct6 res; res.i = -ss.i; res.j = -ss.j; return res; } public delegate SmallStruct6 SmallStructDelegate6 (SmallStruct6 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate6")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate6 d); public static int test_0_marshal_small_struct_delegate6 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate6 (delegate_test_struct)); } /* TEST 7: 4+2 byte long INTEGER struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct7 { public int i; public short j; } public static SmallStruct7 delegate_test_struct (SmallStruct7 ss) { SmallStruct7 res; res.i = -ss.i; res.j = (short)-ss.j; return res; } public delegate SmallStruct7 SmallStructDelegate7 (SmallStruct7 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate7")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate7 d); public static int test_0_marshal_small_struct_delegate7 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate7 (delegate_test_struct)); } /* TEST 8: 4 byte long FLOAT struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct8 { public float i; } public static SmallStruct8 delegate_test_struct (SmallStruct8 ss) { SmallStruct8 res; res.i = -ss.i; return res; } public delegate SmallStruct8 SmallStructDelegate8 (SmallStruct8 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate8")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate8 d); public static int test_0_marshal_small_struct_delegate8 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate8 (delegate_test_struct)); } /* TEST 9: 8 byte long FLOAT struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct9 { public double i; } public static SmallStruct9 delegate_test_struct (SmallStruct9 ss) { SmallStruct9 res; res.i = -ss.i; return res; } public delegate SmallStruct9 SmallStructDelegate9 (SmallStruct9 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate9")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate9 d); public static int test_0_marshal_small_struct_delegate9 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate9 (delegate_test_struct)); } /* TEST 10: 4+4 byte long FLOAT struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct10 { public float i; public float j; } public static SmallStruct10 delegate_test_struct (SmallStruct10 ss) { SmallStruct10 res; res.i = -ss.i; res.j = -ss.j; return res; } public delegate SmallStruct10 SmallStructDelegate10 (SmallStruct10 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate10")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate10 d); public static int test_0_marshal_small_struct_delegate10 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate10 (delegate_test_struct)); } /* TEST 11: 4+4 byte long MIXED struct */ [StructLayout (LayoutKind.Sequential)] public struct SmallStruct11 { public float i; public int j; } public static SmallStruct11 delegate_test_struct (SmallStruct11 ss) { SmallStruct11 res; res.i = -ss.i; res.j = -ss.j; return res; } public delegate SmallStruct11 SmallStructDelegate11 (SmallStruct11 ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_small_struct_delegate11")] public static extern int mono_test_marshal_small_struct_delegate (SmallStructDelegate11 d); public static int test_0_marshal_small_struct_delegate11 () { return mono_test_marshal_small_struct_delegate (new SmallStructDelegate11 (delegate_test_struct)); } /* * Passing arrays */ public delegate int ArrayDelegate1 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=0)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate1 (string[] arr, int len, ArrayDelegate1 d); public static int array_delegate1 (int i, string j, string[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != "ABC") || (arr [1] != "DEF")) return 2; return 0; } public static int test_0_marshal_array_delegate_string () { string[] arr = new string [] { "ABC", "DEF" }; return mono_test_marshal_array_delegate1 (arr, arr.Length, new ArrayDelegate1 (array_delegate1)); } public static int array_delegate2 (int i, string j, string[] arr) { return (arr == null) ? 0 : 1; } public static int test_0_marshal_array_delegate_null () { return mono_test_marshal_array_delegate1 (null, 0, new ArrayDelegate1 (array_delegate2)); } public delegate int ArrayDelegate3 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=3)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate3 (string[] arr, int len, ArrayDelegate3 d); public static int array_delegate3 (int i, string j, string[] arr) { return (arr == null) ? 0 : 1; } public static int test_0_marshal_array_delegate_bad_paramindex () { try { mono_test_marshal_array_delegate3 (null, 0, new ArrayDelegate3 (array_delegate3)); return 1; } catch (MarshalDirectiveException) { return 0; } } public delegate int ArrayDelegate4 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=1)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate4 (string[] arr, int len, ArrayDelegate4 d); public static int array_delegate4 (int i, string j, string[] arr) { return (arr == null) ? 0 : 1; } public static int test_0_marshal_array_delegate_bad_paramtype () { try { mono_test_marshal_array_delegate4 (null, 0, new ArrayDelegate4 (array_delegate4)); return 1; } catch (MarshalDirectiveException) { return 0; } } public delegate int ArrayDelegate4_2 (int i, string j, string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate4_2 (string[] arr, int len, ArrayDelegate4_2 d); public static int array_delegate4_2 (int i, string j, string[] arr) { return (arr == null) ? 0 : 1; } public static int test_0_marshal_array_delegate_no_marshal_directive () { try { mono_test_marshal_array_delegate4_2 (null, 0, new ArrayDelegate4_2 (array_delegate4_2)); return 1; } catch (MarshalDirectiveException) { return 0; } } public delegate int ArrayDelegate4_3 (int i, string j, string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate4_3 (string[] arr, int len, ArrayDelegate4_3 d); public int array_delegate4_3 (int i, string j, string[] arr) { return (arr == null) ? 0 : 1; } public static int test_0_marshal_array_delegate_no_marshal_directive_instance () { try { Tests t = new Tests (); mono_test_marshal_array_delegate4_3 (null, 0, new ArrayDelegate4_3 (t.array_delegate4_3)); return 1; } catch (MarshalDirectiveException) { return 0; } } public delegate int ArrayDelegate5 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr, SizeParamIndex=0)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate", CharSet=CharSet.Unicode)] public static extern int mono_test_marshal_array_delegate5 (string[] arr, int len, ArrayDelegate5 d); public static int array_delegate5 (int i, string j, string[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != "ABC") || (arr [1] != "DEF")) return 2; return 0; } public static int test_0_marshal_array_delegate_unicode_string () { string[] arr = new string [] { "ABC", "DEF" }; return mono_test_marshal_array_delegate5 (arr, arr.Length, new ArrayDelegate5 (array_delegate5)); } public delegate int ArrayDelegate6 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeConst=2)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate6 (string[] arr, int len, ArrayDelegate6 d); public static int array_delegate6 (int i, string j, string[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != "ABC") || (arr [1] != "DEF")) return 2; return 0; } public static int test_0_marshal_array_delegate_sizeconst () { string[] arr = new string [] { "ABC", "DEF" }; return mono_test_marshal_array_delegate6 (arr, 1024, new ArrayDelegate6 (array_delegate6)); } public delegate int ArrayDelegate7 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeConst=1, SizeParamIndex=0)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate7 (string[] arr, int len, ArrayDelegate7 d); public static int array_delegate7 (int i, string j, string[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != "ABC") || (arr [1] != "DEF")) return 2; return 0; } public static int test_0_marshal_array_delegate_sizeconst_paramindex () { string[] arr = new string [] { "ABC", "DEF" }; return mono_test_marshal_array_delegate7 (arr, 1, new ArrayDelegate7 (array_delegate7)); } public delegate int ArrayDelegate8 (int i, string j, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate")] public static extern int mono_test_marshal_array_delegate8 (int[] arr, int len, ArrayDelegate8 d); public static int array_delegate8 (int i, string j, int[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != 42) || (arr [1] != 43)) return 2; return 0; } public static int test_0_marshal_array_delegate_blittable () { int[] arr = new int [] { 42, 43 }; return mono_test_marshal_array_delegate8 (arr, 2, new ArrayDelegate8 (array_delegate8)); } /* Array with size param of type long */ public delegate int ArrayDelegate8_2 (long i, string j, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=0)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_array_delegate_long")] public static extern int mono_test_marshal_array_delegate8_2 (string[] arr, long len, ArrayDelegate8_2 d); public static int array_delegate8_2 (long i, string j, string[] arr) { if (arr.Length != 2) return 1; if ((arr [0] != "ABC") || (arr [1] != "DEF")) return 2; return 0; } public static int test_0_marshal_array_delegate_long_param () { string[] arr = new string [] { "ABC", "DEF" }; return mono_test_marshal_array_delegate8_2 (arr, arr.Length, new ArrayDelegate8_2 (array_delegate8_2)); } /* * [Out] blittable arrays */ public delegate int ArrayDelegate9 (int i, string j, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_out_array_delegate")] public static extern int mono_test_marshal_out_array_delegate (int[] arr, int len, ArrayDelegate9 d); public static int array_delegate9 (int i, string j, int[] arr) { if (arr.Length != 2) return 1; arr [0] = 1; arr [1] = 2; return 0; } public static int test_0_marshal_out_array_delegate () { int[] arr = new int [] { 42, 43 }; return mono_test_marshal_out_array_delegate (arr, 2, new ArrayDelegate9 (array_delegate9)); } /* * [Out] string arrays */ public delegate int ArrayDelegate10 (int i, string j, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeConst=2)] string[] arr); [DllImport ("libtest", EntryPoint="mono_test_marshal_out_string_array_delegate")] public static extern int mono_test_marshal_out_string_array_delegate (string[] arr, int len, ArrayDelegate10 d); public static int array_delegate10 (int i, string j, string[] arr) { if (arr.Length != 2) return 1; arr [0] = "ABC"; arr [1] = "DEF"; return 0; } public static int test_0_marshal_out_string_array_delegate () { string[] arr = new string [] { "", "" }; return mono_test_marshal_out_string_array_delegate (arr, 2, new ArrayDelegate10 (array_delegate10)); } /* * [In, Out] classes */ public delegate int InOutByvalClassDelegate ([In, Out] SimpleClass ss); [DllImport ("libtest", EntryPoint="mono_test_marshal_inout_byval_class_delegate")] public static extern int mono_test_marshal_inout_byval_class_delegate (InOutByvalClassDelegate d); public static int delegate_test_byval_class_inout (SimpleClass ss) { if ((ss.a != false) || (ss.b != true) || (ss.c != false) || (ss.d != "FOO")) return 1; ss.a = true; ss.b = false; ss.c = true; ss.d = "RES"; return 0; } public static int test_0_marshal_inout_byval_class_delegate () { return mono_test_marshal_inout_byval_class_delegate (new InOutByvalClassDelegate (delegate_test_byval_class_inout)); } /* * Returning unicode strings */ [return: MarshalAs(UnmanagedType.LPWStr)] public delegate string ReturnUnicodeStringDelegate([MarshalAs(UnmanagedType.LPWStr)] string message); [DllImport ("libtest", EntryPoint="mono_test_marshal_return_unicode_string_delegate")] public static extern int mono_test_marshal_return_unicode_string_delegate (ReturnUnicodeStringDelegate d); public static String return_unicode_string_delegate (string message) { return message; } public static int test_0_marshal_return_unicode_string_delegate () { return mono_test_marshal_return_unicode_string_delegate (new ReturnUnicodeStringDelegate (return_unicode_string_delegate)); } /* * Returning string arrays */ public delegate string[] ReturnArrayDelegate (int i); [DllImport ("libtest", EntryPoint="mono_test_marshal_return_string_array_delegate")] public static extern int mono_test_marshal_return_string_array_delegate (ReturnArrayDelegate d); public static String[] return_array_delegate (int i) { String[] arr = new String [2]; arr [0] = "ABC"; arr [1] = "DEF"; return arr; } public static String[] return_array_delegate_null (int i) { return null; } public static int test_0_marshal_return_string_array_delegate () { return mono_test_marshal_return_string_array_delegate (new ReturnArrayDelegate (return_array_delegate)); } public static int test_3_marshal_return_string_array_delegate_null () { return mono_test_marshal_return_string_array_delegate (new ReturnArrayDelegate (return_array_delegate_null)); } /* * Byref string marshalling */ public delegate int ByrefStringDelegate (ref string s); [DllImport ("libtest", EntryPoint="mono_test_marshal_byref_string_delegate")] public static extern int mono_test_marshal_byref_string_delegate (ByrefStringDelegate d); public static int byref_string_delegate (ref string s) { if (s != "ABC") return 1; s = "DEF"; return 0; } public static int test_0_marshal_byref_string_delegate () { return mono_test_marshal_byref_string_delegate (new ByrefStringDelegate (byref_string_delegate)); } /* * Thread attach */ public delegate int SimpleDelegate (int i); [DllImport ("libtest", EntryPoint="mono_test_marshal_thread_attach")] public static extern int mono_test_marshal_thread_attach (SimpleDelegate d); public static int test_43_thread_attach () { int res = mono_test_marshal_thread_attach (delegate (int i) { if (!Thread.CurrentThread.IsBackground) return 0; return i + 1; }); return res; } /* * Appdomain save/restore */ static Func<int> callback; [DllImport ("libtest", EntryPoint="mono_test_marshal_set_callback")] public static extern int mono_test_marshal_set_callback (Func<int> a); [DllImport ("libtest", EntryPoint="mono_test_marshal_call_callback")] public static extern int mono_test_marshal_call_callback (); public static int test_0_appdomain_switch () { // FIXME: The appdomain unload hangs //return 0; AppDomain ad = AppDomain.CreateDomain ("foo"); var c = (CallbackClass)ad.CreateInstanceAndUnwrap ( typeof (CallbackClass).Assembly.FullName, "Tests/CallbackClass"); c.SetCallback (); int domain_id = AppDomain.CurrentDomain.Id; int new_id = mono_test_marshal_call_callback (); int res = 0; if (new_id == domain_id) res = 1; if (AppDomain.CurrentDomain.Id != domain_id) res = 2; AppDomain.Unload (ad); return res; } static int domain_callback () { return AppDomain.CurrentDomain.Id; } class CallbackClass : MarshalByRefObject { public int SetCallback () { mono_test_marshal_set_callback (domain_callback); return 0; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mover : VertexMachine { public tk2dSpriteAnimator moverAnimator; public enum Conditionals { None, False, True } private Conditionals TopLeft; private Conditionals TopRight; private Conditionals BottomLeft; private Conditionals BottomRight; // This is used to determine whether to show a sound // effect during CanMove. private bool meetsConditions; private Direction facing = Direction.RIGHT; private MoverTypes moverType; public MoverTypes MoverType { get { return moverType; } set { moverType = value; SetMoverSprite(moverType); } } public enum MoverTypes { Default, Conditional } protected override void Start () { base.Start(); // Initialize conditionals. TopLeft = Conditionals.None; TopRight = Conditionals.None; BottomLeft = Conditionals.None; BottomRight = Conditionals.None; // Set to default arrow UpdateImage(); } void Update () { if (Input.GetKeyUp(KeyCode.R) && gameObject.GetComponent<DraggableVertexMachine>().dragging && !TickController.Obj.IsRunning()) { SoundManager.Instance.PlaySound(SoundManager.SoundTypes.RotateMover); rotateClockwise(); } } private void OnMouseOver() { if (Input.GetKeyUp(KeyCode.R) && !gameObject.GetComponent<DraggableVertexMachine>().dragging && !TickController.Obj.IsRunning()) { SoundManager.Instance.PlaySound(SoundManager.SoundTypes.RotateMover); rotateClockwise(); } } public void rotateClockwise() { facing = (Direction)(((int)facing + 1) % 4); transform.Rotate(Vector3.forward * -90); } protected override void Manipulate(float tickTime) { if (GridVertex.Grid.GridTablet != null) { // is there a tile over us? if (GridVertex.Grid.GridTablet.GridVertexX == this.GridVertex.X && GridVertex.Grid.GridTablet.GridVertexY == this.GridVertex.Y && CanMove()) { GridVertex.Grid.GridTablet.MovementDirection = facing; } } UnmeetAllConditionals (); } public enum Direction { UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3 } private bool CanMove() { meetsConditions = false; GridCell[] cells = GridVertex.GetSurroundingCells (); for (int i = 0; i < 4; i++) { CellMachine machine = cells [i].CellMachine; if (machine != null) { machine.CheckCondition (); } } if ((TopLeft == Conditionals.False) || (TopRight == Conditionals.False) || (BottomLeft == Conditionals.False) || (BottomRight == Conditionals.False)) { SoundManager.Instance.PlaySound(SoundManager.SoundTypes.ContitionalFailed); return false; } if (meetsConditions) { SoundManager.Instance.PlaySound (SoundManager.SoundTypes.ConditionalMet); } return true; } private void UpdateImage() { if ((TopLeft == Conditionals.None) && (TopRight == Conditionals.None) && (BottomLeft == Conditionals.None) && (BottomRight == Conditionals.None)) { MoverType = MoverTypes.Default; } else { // Set as conditional arrow. MoverType = MoverTypes.Conditional; } } public void AddConditional(int gridX, int gridY) { GridCell[] cells = GridVertex.GetSurroundingCells (); if (cells [0].X == gridX && cells [0].Y == gridY) { TopLeft = Conditionals.False; } if (cells [1].X == gridX && cells [1].Y == gridY) { TopRight = Conditionals.False; } if (cells [2].X == gridX && cells [2].Y == gridY) { BottomLeft = Conditionals.False; } if (cells [3].X == gridX && cells [3].Y == gridY) { BottomRight = Conditionals.False; } UpdateImage (); } public void RemoveConditional(int gridX, int gridY) { GridCell[] cells = GridVertex.GetSurroundingCells (); if (cells [0].X == gridX && cells [0].Y == gridY) { TopLeft = Conditionals.None; } if (cells [1].X == gridX && cells [1].Y == gridY) { TopRight = Conditionals.None; } if (cells [2].X == gridX && cells [2].Y == gridY) { BottomLeft = Conditionals.None; } if (cells [3].X == gridX && cells [3].Y == gridY) { BottomRight = Conditionals.None; } UpdateImage (); } public void RemoveAllConditionals() { TopLeft = Conditionals.None; TopRight = Conditionals.None; BottomLeft = Conditionals.None; BottomRight = Conditionals.None; UpdateImage (); } public void MeetConditional(int gridX, int gridY) { GridCell[] cells = GridVertex.GetSurroundingCells (); if (cells [0].X == gridX && cells [0].Y == gridY) { meetsConditions = true; TopLeft = Conditionals.True; } if (cells [1].X == gridX && cells [1].Y == gridY) { meetsConditions = true; TopRight = Conditionals.True; } if (cells [2].X == gridX && cells [2].Y == gridY) { meetsConditions = true; BottomLeft = Conditionals.True; } if (cells [3].X == gridX && cells [3].Y == gridY) { meetsConditions = true; BottomRight = Conditionals.True; } UpdateImage (); } public void UnmeetAllConditionals() { if (TopLeft == Conditionals.True) { TopLeft = Conditionals.False; } if (TopRight == Conditionals.True) { TopRight = Conditionals.False; } if (BottomLeft == Conditionals.True) { BottomLeft = Conditionals.False; } if (BottomRight == Conditionals.True) { BottomRight = Conditionals.False; } UpdateImage (); } public override void OnPlace() { GridCell[] cells = GridVertex.GetSurroundingCells (); for (int i = 0; i < 4; i++) { CellMachine machine = cells [i].CellMachine; if (machine != null) { machine.OnPlace (); } } } public override void OnRemove() { RemoveAllConditionals (); } private void SetMoverSprite (MoverTypes type) { switch (type) { case MoverTypes.Conditional: moverAnimator.SetFrame(1); break; default: moverAnimator.SetFrame(0); break; } } } public static class DirectionExtensions { public static Vector2 ToUnitVector(this Mover.Direction direction) { int x = 0; int y = 0; switch (direction) { case Mover.Direction.UP: y = 1; break; case Mover.Direction.RIGHT: x = 1; break; case Mover.Direction.DOWN: y = -1; break; case Mover.Direction.LEFT: x = -1; break; } return new Vector2(x, y); } public static Mover.Direction Clockwise(this Mover.Direction direction) { switch(direction) { case Mover.Direction.UP: return Mover.Direction.RIGHT; case Mover.Direction.RIGHT: return Mover.Direction.DOWN; case Mover.Direction.DOWN: return Mover.Direction.LEFT; case Mover.Direction.LEFT: return Mover.Direction.UP; default: throw new ArgumentException("OMGWTFBBQ"); } } }
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class tk2dBatchedSprite { public string name = ""; // for editing public int parentId = -1; public int spriteId = 0; public Quaternion rotation = Quaternion.identity; public Vector3 position = Vector3.zero; public Vector3 localScale = Vector3.one; public Color color = Color.white; public bool alwaysPixelPerfect = false; public bool IsDrawn { get { return spriteId != -1; } } public tk2dBatchedSprite() { parentId = -1; } } [AddComponentMenu("2D Toolkit/Sprite/tk2dStaticSpriteBatcher")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] public class tk2dStaticSpriteBatcher : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { public static int CURRENT_VERSION = 2; public int version; public tk2dBatchedSprite[] batchedSprites = null; public tk2dSpriteCollectionData spriteCollection = null; tk2dSpriteCollectionData spriteCollectionInst = null; Mesh mesh = null; Mesh colliderMesh = null; [SerializeField] Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); #if UNITY_EDITOR // This is not exposed to game, as the cost of rebuilding this data is very high public Vector3 scale { get { UpgradeData(); return _scale; } set { bool needBuild = _scale != value; _scale = value; if (needBuild) Build(); } } #endif void Awake() { Build(); } // Sanitize data, returns true if needs rebuild bool UpgradeData() { if (version == CURRENT_VERSION) return false; if (_scale == Vector3.zero) _scale = Vector3.one; if (version < 2) { if (batchedSprites != null) { // Parented to this object foreach (var sprite in batchedSprites) sprite.parentId = -1; } } version = CURRENT_VERSION; return true; } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } if (colliderMesh) { #if UNITY_EDITOR DestroyImmediate(colliderMesh); #else Destroy(colliderMesh); #endif } } public void Build() { UpgradeData(); if (spriteCollection != null) spriteCollectionInst = spriteCollection.inst; if (mesh == null) { mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; } else { // this happens when the sprite rebuilds mesh.Clear(); } if (colliderMesh) { #if UNITY_EDITOR DestroyImmediate(colliderMesh); #else Destroy(colliderMesh); #endif colliderMesh = null; } if (!spriteCollectionInst || batchedSprites == null || batchedSprites.Length == 0) { } else { SortBatchedSprites(); BuildRenderMesh(); BuildPhysicsMesh(); } } void SortBatchedSprites() { List<tk2dBatchedSprite> solidBatches = new List<tk2dBatchedSprite>(); List<tk2dBatchedSprite> otherBatches = new List<tk2dBatchedSprite>(); List<tk2dBatchedSprite> undrawnBatches = new List<tk2dBatchedSprite>(); foreach (var sprite in batchedSprites) { if (!sprite.IsDrawn) { undrawnBatches.Add(sprite); continue; } var spriteData = spriteCollectionInst.spriteDefinitions[sprite.spriteId]; if (spriteData.materialInst.renderQueue == 2000) solidBatches.Add(sprite); else otherBatches.Add(sprite); } List<tk2dBatchedSprite> allBatches = new List<tk2dBatchedSprite>(solidBatches.Count + otherBatches.Count + undrawnBatches.Count); allBatches.AddRange(solidBatches); allBatches.AddRange(otherBatches); allBatches.AddRange(undrawnBatches); // Re-index parents Dictionary<tk2dBatchedSprite, int> lookup = new Dictionary<tk2dBatchedSprite, int>(); int index = 0; foreach (var v in allBatches) lookup[v] = index++; foreach (var v in allBatches) { if (v.parentId == -1) continue; v.parentId = lookup[ batchedSprites[v.parentId] ]; } batchedSprites = allBatches.ToArray(); } void BuildRenderMesh() { List<Material> materials = new List<Material>(); List<List<int>> indices = new List<List<int>>(); bool needNormals = false; bool needTangents = false; if (batchedSprites.Length > 0) { var v = spriteCollectionInst.FirstValidDefinition; needNormals = v.normals != null && v.normals.Length > 0; needTangents = v.tangents != null && v.tangents.Length > 0; } int numVertices = 0; foreach (var sprite in batchedSprites) { if (!sprite.IsDrawn) // when the first non-drawn child is found, it signals the end of the drawn list break; var spriteData = spriteCollectionInst.spriteDefinitions[sprite.spriteId]; numVertices += spriteData.positions.Length; } Vector3[] meshNormals = needNormals?new Vector3[numVertices]:null; Vector4[] meshTangents = needTangents?new Vector4[numVertices]:null; Vector3[] meshVertices = new Vector3[numVertices]; Color[] meshColors = new Color[numVertices]; Vector2[] meshUvs = new Vector2[numVertices]; int currVertex = 0; int currIndex = 0; Material currentMaterial = null; List<int> currentIndices = null; foreach (var sprite in batchedSprites) { if (!sprite.IsDrawn) // when the first non-drawn child is found, it signals the end of the drawn list break; var spriteData = spriteCollectionInst.spriteDefinitions[sprite.spriteId]; if (spriteData.materialInst != currentMaterial) { if (currentMaterial != null) { materials.Add(currentMaterial); indices.Add(currentIndices); } currentMaterial = spriteData.materialInst; currentIndices = new List<int>(); } Color color = sprite.color; if (spriteCollectionInst.premultipliedAlpha) { color.r *= color.a; color.g *= color.a; color.b *= color.a; } for (int i = 0; i < spriteData.indices.Length; ++i) currentIndices.Add(currVertex + spriteData.indices[i]); for (int i = 0; i < spriteData.positions.Length; ++i) { Vector3 pos = new Vector3(spriteData.positions[i].x * sprite.localScale.x, spriteData.positions[i].y * sprite.localScale.y, spriteData.positions[i].z * sprite.localScale.z); pos = sprite.rotation * pos; pos += sprite.position; pos = new Vector3(pos.x * _scale.x, pos.y * _scale.y, pos.z * _scale.z); meshVertices[currVertex + i] = pos; if (needNormals) { meshNormals[currVertex + i] = sprite.rotation * spriteData.normals[i]; } if (needTangents) { Vector4 tangent = spriteData.tangents[i]; Vector3 tangent3 = new Vector3(tangent.x, tangent.y, tangent.z); Vector3 transformedTangent = sprite.rotation * tangent3; meshTangents[currVertex + i] = new Vector4(transformedTangent.x, transformedTangent.y, transformedTangent.z, tangent.w); } meshUvs[currVertex + i] = spriteData.uvs[i]; meshColors[currVertex + i] = color; } currIndex += spriteData.indices.Length; currVertex += spriteData.positions.Length; } if (currentIndices != null) { materials.Add(currentMaterial); indices.Add(currentIndices); } if (mesh) { mesh.vertices = meshVertices; mesh.uv = meshUvs; mesh.colors = meshColors; if (needNormals) mesh.normals = meshNormals; if (needTangents) mesh.tangents = meshTangents; mesh.subMeshCount = indices.Count; for (int i = 0; i < indices.Count; ++i) mesh.SetTriangles(indices[i].ToArray(), i); mesh.RecalculateBounds(); } renderer.sharedMaterials = materials.ToArray(); } void BuildPhysicsMesh() { MeshCollider meshCollider = GetComponent<MeshCollider>(); if (meshCollider != null && collider != meshCollider) { // Already has a collider return; } int numIndices = 0; int numVertices = 0; // first pass, count required vertices and indices foreach (var sprite in batchedSprites) { if (!sprite.IsDrawn) // when the first non-drawn child is found, it signals the end of the drawn list break; var spriteData = spriteCollectionInst.spriteDefinitions[sprite.spriteId]; if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Box) { numIndices += 6 * 4; numVertices += 8; } else if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Mesh) { numIndices += spriteData.colliderIndicesFwd.Length; numVertices += spriteData.colliderVertices.Length; } } if (numIndices == 0) { if (colliderMesh) { #if UNITY_EDTIOR DestroyImmediate(colliderMesh); #else Destroy(colliderMesh); #endif } return; } if (meshCollider == null) { meshCollider = gameObject.AddComponent<MeshCollider>(); } if (colliderMesh == null) { colliderMesh = new Mesh(); colliderMesh.hideFlags = HideFlags.DontSave; } else { colliderMesh.Clear(); } // second pass, build composite mesh int currVertex = 0; Vector3[] vertices = new Vector3[numVertices]; int currIndex = 0; int[] indices = new int[numIndices]; foreach (var sprite in batchedSprites) { if (!sprite.IsDrawn) // when the first non-drawn child is found, it signals the end of the drawn list break; var spriteData = spriteCollectionInst.spriteDefinitions[sprite.spriteId]; if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Box) { Vector3 origin = new Vector3(spriteData.colliderVertices[0].x * sprite.localScale.x, spriteData.colliderVertices[0].y * sprite.localScale.y, spriteData.colliderVertices[0].z * sprite.localScale.z); Vector3 extents = new Vector3(spriteData.colliderVertices[1].x * sprite.localScale.x, spriteData.colliderVertices[1].y * sprite.localScale.y, spriteData.colliderVertices[1].z * sprite.localScale.z); Vector3 min = origin - extents; Vector3 max = origin + extents; vertices[currVertex + 0] = sprite.rotation * new Vector3(min.x, min.y, min.z) + sprite.position; vertices[currVertex + 1] = sprite.rotation * new Vector3(min.x, min.y, max.z) + sprite.position; vertices[currVertex + 2] = sprite.rotation * new Vector3(max.x, min.y, min.z) + sprite.position; vertices[currVertex + 3] = sprite.rotation * new Vector3(max.x, min.y, max.z) + sprite.position; vertices[currVertex + 4] = sprite.rotation * new Vector3(min.x, max.y, min.z) + sprite.position; vertices[currVertex + 5] = sprite.rotation * new Vector3(min.x, max.y, max.z) + sprite.position; vertices[currVertex + 6] = sprite.rotation * new Vector3(max.x, max.y, min.z) + sprite.position; vertices[currVertex + 7] = sprite.rotation * new Vector3(max.x, max.y, max.z) + sprite.position; for (int j = 0; j < 8; ++j) { Vector3 v = vertices[currVertex + j]; v = new Vector3(v.x * _scale.x, v.y * _scale.y, v.z * _scale.z); vertices[currVertex + j] = v; } int[] indicesBack = { 0, 1, 2, 2, 1, 3, 6, 5, 4, 7, 5, 6, 3, 7, 6, 2, 3, 6, 4, 5, 1, 4, 1, 0 }; int[] indicesFwd = { 2, 1, 0, 3, 1, 2, 4, 5, 6, 6, 5, 7, 6, 7, 3, 6, 3, 2, 1, 5, 4, 0, 1, 4 }; float scl = sprite.localScale.x * sprite.localScale.y * sprite.localScale.z; int[] srcIndices = (scl >= 0)?indicesFwd:indicesBack; for (int i = 0; i < srcIndices.Length; ++i) indices[currIndex + i] = currVertex + srcIndices[i]; currIndex += 6 * 4; currVertex += 8; } else if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Mesh) { for (int i = 0; i < spriteData.colliderVertices.Length; ++i) { Vector3 pos = new Vector3(spriteData.colliderVertices[i].x * sprite.localScale.x, spriteData.colliderVertices[i].y * sprite.localScale.y, spriteData.colliderVertices[i].z * sprite.localScale.z); pos = sprite.rotation * pos; pos += sprite.position; pos = new Vector3(pos.x * _scale.x, pos.y * _scale.y, pos.z * _scale.z); vertices[currVertex + i] = pos; } float scl = sprite.localScale.x * sprite.localScale.y * sprite.localScale.z; int[] srcIndices = (scl >= 0)?spriteData.colliderIndicesFwd:spriteData.colliderIndicesBack; for (int i = 0; i < srcIndices.Length; ++i) { indices[currIndex + i] = currVertex + srcIndices[i]; } currIndex += spriteData.colliderIndicesFwd.Length; currVertex += spriteData.colliderVertices.Length; } } colliderMesh.vertices = vertices; colliderMesh.triangles = indices; meshCollider.sharedMesh = colliderMesh; } public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { return this.spriteCollection == spriteCollection; } public void ForceBuild() { Build(); } }
namespace XenAdmin.Wizards.NewVMWizard { partial class Page_Storage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Page_Storage)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.CloneCheckBox = new System.Windows.Forms.CheckBox(); this.DisksGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.ImageColumn = new System.Windows.Forms.DataGridViewImageColumn(); this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.SrColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.SizeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.SharedColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DeleteButton = new System.Windows.Forms.Button(); this.EditButton = new System.Windows.Forms.Button(); this.AddButton = new System.Windows.Forms.Button(); this.DisklessVMRadioButton = new System.Windows.Forms.RadioButton(); this.DisksRadioButton = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); ((System.ComponentModel.ISupportInitialize)(this.DisksGridView)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // CloneCheckBox // resources.ApplyResources(this.CloneCheckBox, "CloneCheckBox"); this.tableLayoutPanel1.SetColumnSpan(this.CloneCheckBox, 2); this.CloneCheckBox.Name = "CloneCheckBox"; this.CloneCheckBox.UseVisualStyleBackColor = true; // // DisksGridView // this.DisksGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.DisksGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; resources.ApplyResources(this.DisksGridView, "DisksGridView"); this.DisksGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.DisksGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ImageColumn, this.NameColumn, this.SrColumn, this.SizeColumn, this.SharedColumn}); dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.DisksGridView.DefaultCellStyle = dataGridViewCellStyle1; this.DisksGridView.Name = "DisksGridView"; this.tableLayoutPanel1.SetRowSpan(this.DisksGridView, 3); this.DisksGridView.Enter += new System.EventHandler(this.DisksGridView_Enter); this.DisksGridView.SelectionChanged += new System.EventHandler(this.DisksGridView_SelectionChanged); // // ImageColumn // this.ImageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ImageColumn, "ImageColumn"); this.ImageColumn.Name = "ImageColumn"; this.ImageColumn.ReadOnly = true; // // NameColumn // this.NameColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.NameColumn.FillWeight = 40F; resources.ApplyResources(this.NameColumn, "NameColumn"); this.NameColumn.Name = "NameColumn"; this.NameColumn.ReadOnly = true; // // SrColumn // this.SrColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.SrColumn.FillWeight = 60F; resources.ApplyResources(this.SrColumn, "SrColumn"); this.SrColumn.Name = "SrColumn"; this.SrColumn.ReadOnly = true; // // SizeColumn // this.SizeColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.SizeColumn, "SizeColumn"); this.SizeColumn.Name = "SizeColumn"; this.SizeColumn.ReadOnly = true; // // SharedColumn // this.SharedColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.SharedColumn, "SharedColumn"); this.SharedColumn.Name = "SharedColumn"; this.SharedColumn.ReadOnly = true; // // DeleteButton // resources.ApplyResources(this.DeleteButton, "DeleteButton"); this.DeleteButton.Name = "DeleteButton"; this.DeleteButton.UseVisualStyleBackColor = true; this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click); // // EditButton // resources.ApplyResources(this.EditButton, "EditButton"); this.EditButton.Name = "EditButton"; this.EditButton.UseVisualStyleBackColor = true; this.EditButton.Click += new System.EventHandler(this.EditButton_Click); // // AddButton // resources.ApplyResources(this.AddButton, "AddButton"); this.AddButton.Name = "AddButton"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // DisklessVMRadioButton // resources.ApplyResources(this.DisklessVMRadioButton, "DisklessVMRadioButton"); this.tableLayoutPanel1.SetColumnSpan(this.DisklessVMRadioButton, 3); this.DisklessVMRadioButton.Name = "DisklessVMRadioButton"; this.DisklessVMRadioButton.TabStop = true; this.DisklessVMRadioButton.UseVisualStyleBackColor = true; this.DisklessVMRadioButton.CheckedChanged += new System.EventHandler(this.DisklessVMRadioButton_CheckedChanged); // // DisksRadioButton // resources.ApplyResources(this.DisksRadioButton, "DisksRadioButton"); this.tableLayoutPanel1.SetColumnSpan(this.DisksRadioButton, 3); this.DisksRadioButton.Name = "DisksRadioButton"; this.DisksRadioButton.TabStop = true; this.DisksRadioButton.UseVisualStyleBackColor = true; this.DisksRadioButton.CheckedChanged += new System.EventHandler(this.DisksRadioButton_CheckedChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.tableLayoutPanel1.SetColumnSpan(this.label1, 3); this.label1.Name = "label1"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.CloneCheckBox, 1, 5); this.tableLayoutPanel1.Controls.Add(this.DeleteButton, 2, 4); this.tableLayoutPanel1.Controls.Add(this.DisksGridView, 1, 2); this.tableLayoutPanel1.Controls.Add(this.EditButton, 2, 3); this.tableLayoutPanel1.Controls.Add(this.DisksRadioButton, 0, 1); this.tableLayoutPanel1.Controls.Add(this.AddButton, 2, 2); this.tableLayoutPanel1.Controls.Add(this.DisklessVMRadioButton, 0, 6); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // Page_Storage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.tableLayoutPanel1); this.Name = "Page_Storage"; ((System.ComponentModel.ISupportInitialize)(this.DisksGridView)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.RadioButton DisksRadioButton; private System.Windows.Forms.RadioButton DisklessVMRadioButton; private System.Windows.Forms.Button AddButton; private System.Windows.Forms.Button EditButton; private System.Windows.Forms.Button DeleteButton; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx DisksGridView; private System.Windows.Forms.CheckBox CloneCheckBox; private System.Windows.Forms.DataGridViewImageColumn ImageColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NameColumn; private System.Windows.Forms.DataGridViewTextBoxColumn SrColumn; private System.Windows.Forms.DataGridViewTextBoxColumn SizeColumn; private System.Windows.Forms.DataGridViewTextBoxColumn SharedColumn; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }
// // X509Helper2.cs // // Authors: // Martin Baulig <martin.baulig@xamarin.com> // // Copyright (C) 2016 Xamarin, Inc. (http://www.xamarin.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. // #if SECURITY_DEP #if MONO_SECURITY_ALIAS extern alias MonoSecurity; #endif #if MONO_SECURITY_ALIAS using MonoSecurity::Mono.Security.Interface; using MX = MonoSecurity::Mono.Security.X509; #else #if MONO_FEATURE_BTLS using Mono.Security.Interface; #endif using MX = Mono.Security.X509; #endif #if MONO_FEATURE_BTLS using Mono.Btls; #endif #endif using System.IO; using System.Text; namespace System.Security.Cryptography.X509Certificates { internal static class X509Helper2 { internal static long GetSubjectNameHash (X509CertificateMono certificate) { return GetSubjectNameHash (certificate.Impl); } internal static long GetSubjectNameHash (X509CertificateImpl impl) { #if SECURITY_DEP using (var x509 = GetNativeInstance (impl)) return GetSubjectNameHash (x509); #else throw new NotSupportedException (); #endif } internal static void ExportAsPEM (X509CertificateMono certificate, Stream stream, bool includeHumanReadableForm) { ExportAsPEM (certificate.Impl, stream, includeHumanReadableForm); } internal static void ExportAsPEM (X509CertificateImpl impl, Stream stream, bool includeHumanReadableForm) { #if SECURITY_DEP using (var x509 = GetNativeInstance (impl)) ExportAsPEM (x509, stream, includeHumanReadableForm); #else throw new NotSupportedException (); #endif } #if SECURITY_DEP internal static void Initialize () { X509Helper.InstallNativeHelper (new MyNativeHelper ()); } internal static void ThrowIfContextInvalid (X509CertificateImpl impl) { X509Helper.ThrowIfContextInvalid (impl); } #if !MONO_FEATURE_BTLS static X509Certificate GetNativeInstance (X509CertificateImpl impl) { throw new PlatformNotSupportedException (); } #else static MonoBtlsX509 GetNativeInstance (X509CertificateImpl impl) { ThrowIfContextInvalid (impl); var btlsImpl = impl as X509CertificateImplBtls; if (btlsImpl != null) return btlsImpl.X509.Copy (); else return MonoBtlsX509.LoadFromData (impl.GetRawCertData (), MonoBtlsX509Format.DER); } internal static long GetSubjectNameHash (MonoBtlsX509 x509) { using (var subject = x509.GetSubjectName ()) return subject.GetHash (); } internal static void ExportAsPEM (MonoBtlsX509 x509, Stream stream, bool includeHumanReadableForm) { using (var bio = MonoBtlsBio.CreateMonoStream (stream)) { x509.ExportAsPEM (bio, includeHumanReadableForm); } } #endif // !MONO_FEATURE_BTLS internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags, bool disableProvider = false) { if (rawData == null || rawData.Length == 0) return null; #if MONO_FEATURE_BTLS if (!disableProvider) { var provider = MonoTlsProviderFactory.GetProvider (); if (provider.HasNativeCertificates) { var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags); return impl; } } #endif // MONO_FEATURE_BTLS var impl2 = new X509Certificate2ImplMono (); impl2.Import (rawData, password, keyStorageFlags); return impl2; } internal static X509Certificate2Impl Import (X509Certificate cert, bool disableProvider = false) { if (cert.Impl == null) return null; #if MONO_FEATURE_BTLS if (!disableProvider) { var provider = MonoTlsProviderFactory.GetProvider (); if (provider.HasNativeCertificates) { var impl = provider.GetNativeCertificate (cert); return impl; } } #endif // MONO_FEATURE_BTLS var impl2 = cert.Impl as X509Certificate2Impl; if (impl2 != null) return (X509Certificate2Impl)impl2.Clone (); return Import (cert.GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet); } /* * This is used by X509ChainImplMono * * Some of the missing APIs such as X509v3 extensions can be added to the native * BTLS implementation. * * We should also consider replacing X509ChainImplMono with a new X509ChainImplBtls * at some point. */ [MonoTODO ("Investigate replacement; see comments in source.")] internal static MX.X509Certificate GetMonoCertificate (X509Certificate2 certificate) { var impl2 = certificate.Impl as X509Certificate2Impl; if (impl2 == null) impl2 = Import (certificate, true); var fallbackImpl = impl2.FallbackImpl as X509Certificate2ImplMono; if (fallbackImpl == null) throw new NotSupportedException (); return fallbackImpl.MonoCertificate; } internal static X509ChainImpl CreateChainImpl (bool useMachineContext) { return new X509ChainImplMono (useMachineContext); } public static bool IsValid (X509ChainImpl impl) { return impl != null && impl.IsValid; } internal static void ThrowIfContextInvalid (X509ChainImpl impl) { if (!IsValid (impl)) throw GetInvalidChainContextException (); } internal static Exception GetInvalidChainContextException () { return new CryptographicException (Locale.GetText ("Chain instance is empty.")); } class MyNativeHelper : INativeCertificateHelper { public X509CertificateImpl Import ( byte[] data, string password, X509KeyStorageFlags flags) { return X509Helper2.Import (data, password, flags); } public X509CertificateImpl Import (X509Certificate cert) { return X509Helper2.Import (cert); } } #endif } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using System.Management.Automation.Runspaces; using System.Threading; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// class to manage the database instances, do the reloading, etc. /// </summary> internal sealed class TypeInfoDataBaseManager { #region Private Data /// <summary> /// instance of the object holding the format.ps1xml in memory database /// </summary> internal TypeInfoDataBase Database { get; private set; } // for locking the F&O database internal object databaseLock = new object(); // for locking the update from XMLs internal object updateDatabaseLock = new object(); // this is used to throw errors when updating a shared TypeTable. internal bool isShared; private List<string> _formatFileList; internal bool DisableFormatTableUpdates { get; set; } #endregion #region Constructors internal TypeInfoDataBaseManager() { isShared = false; _formatFileList = new List<string>(); } /// <summary> /// /// </summary> /// <param name="formatFiles"></param> /// <param name="isShared"></param> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> /// <exception cref="ArgumentNullException" /> /// <exception cref="ArgumentException"> /// 1. FormatFile is not rooted. /// </exception> /// <exception cref="FormatTableLoadException"> /// 1. There were errors loading Formattable. Look in the Errors property to get /// detailed error messages. /// </exception> internal TypeInfoDataBaseManager( IEnumerable<string> formatFiles, bool isShared, AuthorizationManager authorizationManager, PSHost host) { _formatFileList = new List<string>(); Collection<PSSnapInTypeAndFormatErrors> filesToLoad = new Collection<PSSnapInTypeAndFormatErrors>(); ConcurrentBag<string> errors = new ConcurrentBag<string>(); foreach (string formatFile in formatFiles) { if (string.IsNullOrEmpty(formatFile) || (!Path.IsPathRooted(formatFile))) { throw PSTraceSource.NewArgumentException("formatFiles", FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); } PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); fileToLoad.Errors = errors; filesToLoad.Add(fileToLoad); _formatFileList.Add(formatFile); } MshExpressionFactory expressionFactory = new MshExpressionFactory(); List<XmlLoaderLoggerEntry> logEntries = null; // load the files LoadFromFile(filesToLoad, expressionFactory, true, authorizationManager, host, false, out logEntries); this.isShared = isShared; // check to see if there are any errors loading the format files if (errors.Count > 0) { throw new FormatTableLoadException(errors); } } #endregion internal TypeInfoDataBase GetTypeInfoDataBase() { return Database; } /// <summary> /// Adds the <paramref name="formatFile"/> to the current FormatTable's file list. /// The FormatTable will not reflect the change until Update is called. /// </summary> /// <param name="formatFile"></param> /// <param name="shouldPrepend"> /// if true, <paramref name="formatFile"/> is prepended to the current FormatTable's file list. /// if false, it will be appended. /// </param> internal void Add(string formatFile, bool shouldPrepend) { if (string.IsNullOrEmpty(formatFile) || (!Path.IsPathRooted(formatFile))) { throw PSTraceSource.NewArgumentException("formatFile", FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); } lock (_formatFileList) { if (shouldPrepend) { _formatFileList.Insert(0, formatFile); } else { _formatFileList.Add(formatFile); } } } /// <summary> /// Removes the <paramref name="formatFile"/> from the current FormatTable's file list. /// The FormatTable will not reflect the change until Update is called. /// </summary> /// <param name="formatFile"></param> internal void Remove(string formatFile) { lock (_formatFileList) { _formatFileList.Remove(formatFile); } } /// <summary> /// Update a shared formatting database with formatData of 'ExtendedTypeDefinition' type. /// This method should only be called from the FormatTable, where are shared formatting /// database is created. /// </summary> /// <param name="formatData"> /// The format data to update the database /// </param> /// <param name="shouldPrepend"> /// Specify the order in which the format data will be loaded /// </param> internal void AddFormatData(IEnumerable<ExtendedTypeDefinition> formatData, bool shouldPrepend) { Diagnostics.Assert(isShared, "this method should only be called from FormatTable to update a shared database"); Collection<PSSnapInTypeAndFormatErrors> filesToLoad = new Collection<PSSnapInTypeAndFormatErrors>(); ConcurrentBag<string> errors = new ConcurrentBag<string>(); if (shouldPrepend) { foreach (ExtendedTypeDefinition typeDefinition in formatData) { PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition); entryToLoad.Errors = errors; filesToLoad.Add(entryToLoad); } // check if the passed in formatData is empty if (filesToLoad.Count == 0) { return; } } lock (_formatFileList) { foreach (string formatFile in _formatFileList) { PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); fileToLoad.Errors = errors; filesToLoad.Add(fileToLoad); } } if (!shouldPrepend) { foreach (ExtendedTypeDefinition typeDefinition in formatData) { PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition); entryToLoad.Errors = errors; filesToLoad.Add(entryToLoad); } // check if the passed in formatData is empty if (filesToLoad.Count == _formatFileList.Count) { return; } } MshExpressionFactory expressionFactory = new MshExpressionFactory(); List<XmlLoaderLoggerEntry> logEntries = null; // load the formatting data LoadFromFile(filesToLoad, expressionFactory, false, null, null, false, out logEntries); // check to see if there are any errors loading the format files if (errors.Count > 0) { throw new FormatTableLoadException(errors); } } /// <summary> /// Update the current formattable with the existing formatFileList. /// New files might have been added using Add() or Files might /// have been removed using Remove. /// </summary> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> internal void Update(AuthorizationManager authorizationManager, PSHost host) { if (DisableFormatTableUpdates) { return; } if (isShared) { throw PSTraceSource.NewInvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); } Collection<PSSnapInTypeAndFormatErrors> filesToLoad = new Collection<PSSnapInTypeAndFormatErrors>(); lock (_formatFileList) { foreach (string formatFile in _formatFileList) { PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); filesToLoad.Add(fileToLoad); } } UpdateDataBase(filesToLoad, authorizationManager, host, false); } /// <summary> /// Update the format data database. If there is any error in loading the format xml files, /// the old database is unchanged. /// The reference returned should NOT be modified by any means by the caller /// </summary> /// <param name="mshsnapins">files to be loaded and errors to be updated</param> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> /// <param name="preValidated"> /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be /// skipped at runtime. /// </param> /// <returns> database instance</returns> internal void UpdateDataBase( Collection<PSSnapInTypeAndFormatErrors> mshsnapins, AuthorizationManager authorizationManager, PSHost host, bool preValidated ) { if (DisableFormatTableUpdates) { return; } if (isShared) { throw PSTraceSource.NewInvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); } MshExpressionFactory expressionFactory = new MshExpressionFactory(); List<XmlLoaderLoggerEntry> logEntries = null; LoadFromFile(mshsnapins, expressionFactory, false, authorizationManager, host, preValidated, out logEntries); } /// <summary> /// load the database /// NOTE: need to be protected by lock since not thread safe per se /// </summary> /// <param name="files">*.formal.xml files to be loaded</param> /// <param name="expressionFactory">expression factory to validate script blocks</param> /// <param name="acceptLoadingErrors">if true, load the database even if there are loading errors</param> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> /// <param name="preValidated"> /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be /// skipped at runtime. /// </param> /// <param name="logEntries">Trace and error logs from loading the format Xml files.</param> /// <returns>true if we had a successful load</returns> internal bool LoadFromFile( Collection<PSSnapInTypeAndFormatErrors> files, MshExpressionFactory expressionFactory, bool acceptLoadingErrors, AuthorizationManager authorizationManager, PSHost host, bool preValidated, out List<XmlLoaderLoggerEntry> logEntries) { bool success; try { TypeInfoDataBase newDataBase = null; lock (updateDatabaseLock) { newDataBase = LoadFromFileHelper(files, expressionFactory, authorizationManager, host, preValidated, out logEntries, out success); } // if we have a valid database, assign it to the // current database lock (databaseLock) { if (acceptLoadingErrors || success) Database = newDataBase; } } finally { // if, for any reason, we failed the load, we initialize the // data base to an empty instance lock (databaseLock) { if (Database == null) { TypeInfoDataBase tempDataBase = new TypeInfoDataBase(); AddPreLoadIntrinsics(tempDataBase); AddPostLoadIntrinsics(tempDataBase); Database = tempDataBase; } } } return success; } /// <summary> /// it loads a database from file(s). /// </summary> /// <param name="files">*.formal.xml files to be loaded</param> /// <param name="expressionFactory">expression factory to validate script blocks</param> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> /// <param name="preValidated"> /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be /// skipped at runtime. /// </param> /// <param name="logEntries">list of logger entries (errors, etc.) to return to the caller</param> /// <param name="success"> true if no error occurred</param> /// <returns>a database instance loaded from file(s)</returns> private static TypeInfoDataBase LoadFromFileHelper( Collection<PSSnapInTypeAndFormatErrors> files, MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, bool preValidated, out List<XmlLoaderLoggerEntry> logEntries, out bool success) { success = true; // Holds the aggregated log entries for all files... logEntries = new List<XmlLoaderLoggerEntry>(); // fresh instance of the database TypeInfoDataBase db = new TypeInfoDataBase(); // prepopulate the database with any necessary overriding data AddPreLoadIntrinsics(db); var etwEnabled = RunspaceEventSource.Log.IsEnabled(); // load the XML document into a copy of the // in memory database foreach (PSSnapInTypeAndFormatErrors file in files) { // Loads formatting data from ExtendedTypeDefinition instance if (file.FormatData != null) { LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: false, isForHelp: false); continue; } if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success)) { // Loads formatting data from formatting data XML file XmlFileLoadInfo info = new XmlFileLoadInfo(Path.GetPathRoot(file.FullPath), file.FullPath, file.Errors, file.PSSnapinName); using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader()) { if (!loader.LoadXmlFile(info, db, expressionFactory, authorizationManager, host, preValidated)) success = false; foreach (XmlLoaderLoggerEntry entry in loader.LogEntries) { // filter in only errors from the current file... if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError, info.psSnapinName, entry.message); info.errors.Add(mshsnapinMessage); if (entry.failToLoadFile) { file.FailToLoadFile = true; } } } // now aggregate the entries... logEntries.AddRange(loader.LogEntries); } } if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); } // add any sensible defaults to the database AddPostLoadIntrinsics(db); return db; } private static void LoadFormatDataHelper( ExtendedTypeDefinition formatData, MshExpressionFactory expressionFactory, List<XmlLoaderLoggerEntry> logEntries, ref bool success, PSSnapInTypeAndFormatErrors file, TypeInfoDataBase db, bool isBuiltInFormatData, bool isForHelp) { using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader()) { if (!loader.LoadFormattingData(formatData, db, expressionFactory, isBuiltInFormatData, isForHelp)) success = false; foreach (XmlLoaderLoggerEntry entry in loader.LogEntries) { // filter in only errors from the current file... if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError, file.PSSnapinName, entry.message); file.Errors.Add(mshsnapinMessage); } } // now aggregate the entries... logEntries.AddRange(loader.LogEntries); } } private delegate IEnumerable<ExtendedTypeDefinition> TypeGenerator(); private static Dictionary<string, Tuple<bool, TypeGenerator>> s_builtinGenerators; private static Tuple<bool, TypeGenerator> GetBuiltin(bool isForHelp, TypeGenerator generator) { return new Tuple<bool, TypeGenerator>(isForHelp, generator); } private static bool ProcessBuiltin( PSSnapInTypeAndFormatErrors file, TypeInfoDataBase db, MshExpressionFactory expressionFactory, List<XmlLoaderLoggerEntry> logEntries, ref bool success) { if (s_builtinGenerators == null) { var builtInGenerators = new Dictionary<string, Tuple<bool, TypeGenerator>>(StringComparer.OrdinalIgnoreCase); var psHome = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); builtInGenerators.Add(Path.Combine(psHome, "Certificate.format.ps1xml"), GetBuiltin(false, Certificate_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Diagnostics.Format.ps1xml"), GetBuiltin(false, Diagnostics_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "DotNetTypes.format.ps1xml"), GetBuiltin(false, DotNetTypes_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Event.Format.ps1xml"), GetBuiltin(false, Event_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "FileSystem.format.ps1xml"), GetBuiltin(false, FileSystem_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Help.format.ps1xml"), GetBuiltin(true, Help_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "HelpV3.format.ps1xml"), GetBuiltin(true, HelpV3_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "PowerShellCore.format.ps1xml"), GetBuiltin(false, PowerShellCore_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "PowerShellTrace.format.ps1xml"), GetBuiltin(false, PowerShellTrace_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Registry.format.ps1xml"), GetBuiltin(false, Registry_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "WSMan.Format.ps1xml"), GetBuiltin(false, WSMan_Format_Ps1Xml.GetFormatData)); Interlocked.CompareExchange(ref s_builtinGenerators, builtInGenerators, null); } Tuple<bool, TypeGenerator> generator; if (!s_builtinGenerators.TryGetValue(file.FullPath, out generator)) return false; ProcessBuiltinFormatViewDefinitions(generator.Item2(), db, expressionFactory, file, logEntries, generator.Item1, ref success); return true; } private static void ProcessBuiltinFormatViewDefinitions( IEnumerable<ExtendedTypeDefinition> views, TypeInfoDataBase db, MshExpressionFactory expressionFactory, PSSnapInTypeAndFormatErrors file, List<XmlLoaderLoggerEntry> logEntries, bool isForHelp, ref bool success) { foreach (var v in views) { LoadFormatDataHelper(v, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: true, isForHelp: isForHelp); } } /// <summary> /// helper to to add any pre-load intrinsics to the db /// </summary> /// <param name="db">db being initialized</param> private static void AddPreLoadIntrinsics(TypeInfoDataBase db) { // NOTE: nothing to add for the time being. Add here if needed. } /// <summary> /// helper to to add any post-load intrinsics to the db /// </summary> /// <param name="db">db being initialized</param> private static void AddPostLoadIntrinsics(TypeInfoDataBase db) { // add entry for the output of update-formatdata // we want to be able to display this as a list, unless overridden // by an entry loaded from file FormatShapeSelectionOnType sel = new FormatShapeSelectionOnType(); sel.appliesTo = new AppliesTo(); sel.appliesTo.AddAppliesToType("Microsoft.PowerShell.Commands.FormatDataLoadingInfo"); sel.formatShape = FormatShape.List; db.defaultSettingsSection.shapeSelectionDirectives.formatShapeSelectionOnTypeList.Add(sel); } } }
/* Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2021 the ZAP development team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; /* * This file was automatically generated. */ namespace OWASPZAPDotNetAPI.Generated { public class Alert { private ClientApi api = null; public Alert(ClientApi api) { this.api = api; } /// <summary> ///Gets the alert with the given ID, the corresponding HTTP message can be obtained with the 'messageId' field and 'message' API method /// </summary> /// <returns></returns> public IApiResponse alert(string id) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("id", id); return api.CallApi("alert", "view", "alert", parameters); } /// <summary> ///Gets the alerts raised by ZAP, optionally filtering by URL or riskId, and paginating with 'start' position and 'count' of alerts /// </summary> /// <returns></returns> public IApiResponse alerts(string baseurl, string start, string count, string riskid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("baseurl", baseurl); parameters.Add("start", start); parameters.Add("count", count); parameters.Add("riskId", riskid); return api.CallApi("alert", "view", "alerts", parameters); } /// <summary> ///Gets number of alerts grouped by each risk level, optionally filtering by URL /// </summary> /// <returns></returns> public IApiResponse alertsSummary(string baseurl) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("baseurl", baseurl); return api.CallApi("alert", "view", "alertsSummary", parameters); } /// <summary> ///Gets the number of alerts, optionally filtering by URL or riskId /// </summary> /// <returns></returns> public IApiResponse numberOfAlerts(string baseurl, string riskid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("baseurl", baseurl); parameters.Add("riskId", riskid); return api.CallApi("alert", "view", "numberOfAlerts", parameters); } /// <summary> ///Gets a summary of the alerts, optionally filtered by a 'url'. If 'recurse' is true then all alerts that apply to urls that start with the specified 'url' will be returned, otherwise only those on exactly the same 'url' (ignoring url parameters) /// </summary> /// <returns></returns> public IApiResponse alertsByRisk(string url, string recurse) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("url", url); parameters.Add("recurse", recurse); return api.CallApi("alert", "view", "alertsByRisk", parameters); } /// <summary> ///Gets a count of the alerts, optionally filtered as per alertsPerRisk /// </summary> /// <returns></returns> public IApiResponse alertCountsByRisk(string url, string recurse) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("url", url); parameters.Add("recurse", recurse); return api.CallApi("alert", "view", "alertCountsByRisk", parameters); } /// <summary> ///Deletes all alerts of the current session. /// </summary> /// <returns></returns> public IApiResponse deleteAllAlerts() { Dictionary<string, string> parameters = null; return api.CallApi("alert", "action", "deleteAllAlerts", parameters); } /// <summary> ///Deletes the alert with the given ID. /// </summary> /// <returns></returns> public IApiResponse deleteAlert(string id) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("id", id); return api.CallApi("alert", "action", "deleteAlert", parameters); } /// <summary> ///Update the confidence of the alerts. /// </summary> /// <returns></returns> public IApiResponse updateAlertsConfidence(string ids, string confidenceid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("ids", ids); parameters.Add("confidenceId", confidenceid); return api.CallApi("alert", "action", "updateAlertsConfidence", parameters); } /// <summary> ///Update the risk of the alerts. /// </summary> /// <returns></returns> public IApiResponse updateAlertsRisk(string ids, string riskid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("ids", ids); parameters.Add("riskId", riskid); return api.CallApi("alert", "action", "updateAlertsRisk", parameters); } /// <summary> ///Update the alert with the given ID, with the provided details. /// </summary> /// <returns></returns> public IApiResponse updateAlert(string id, string name, string riskid, string confidenceid, string description, string param, string attack, string otherinfo, string solution, string references, string evidence, string cweid, string wascid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("id", id); parameters.Add("name", name); parameters.Add("riskId", riskid); parameters.Add("confidenceId", confidenceid); parameters.Add("description", description); parameters.Add("param", param); parameters.Add("attack", attack); parameters.Add("otherInfo", otherinfo); parameters.Add("solution", solution); parameters.Add("references", references); parameters.Add("evidence", evidence); parameters.Add("cweId", cweid); parameters.Add("wascId", wascid); return api.CallApi("alert", "action", "updateAlert", parameters); } /// <summary> ///Add an alert associated with the given message ID, with the provided details. (The ID of the created alert is returned.) /// </summary> /// <returns></returns> public IApiResponse addAlert(string messageid, string name, string riskid, string confidenceid, string description, string param, string attack, string otherinfo, string solution, string references, string evidence, string cweid, string wascid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("messageId", messageid); parameters.Add("name", name); parameters.Add("riskId", riskid); parameters.Add("confidenceId", confidenceid); parameters.Add("description", description); parameters.Add("param", param); parameters.Add("attack", attack); parameters.Add("otherInfo", otherinfo); parameters.Add("solution", solution); parameters.Add("references", references); parameters.Add("evidence", evidence); parameters.Add("cweId", cweid); parameters.Add("wascId", wascid); return api.CallApi("alert", "action", "addAlert", parameters); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualInt64() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt64 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[ElementCount]; private static Int64[] _data2 = new Int64[ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64> _dataTable; static SimpleBinaryOpTest__CompareEqualInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; using System.Collections; using System.IO; using System.Text; using IO; using MIME; #endregion /// <summary> /// Rfc 2822 Mime Entity. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class MimeEntity { #region Members private readonly MimeEntityCollection m_pChildEntities; private readonly HeaderFieldCollection m_pHeader; private readonly Hashtable m_pHeaderFieldCache; private byte[] m_EncodedData; private MimeEntity m_pParentEntity; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public MimeEntity() { m_pHeader = new HeaderFieldCollection(); m_pChildEntities = new MimeEntityCollection(this); m_pHeaderFieldCache = new Hashtable(); } #endregion #region Properties /// <summary> /// Gets or sets header field "<b>Bcc:</b>" value. Returns null if value isn't set. /// </summary> public AddressList Bcc { get { if (m_pHeader.Contains("Bcc:")) { // There is already cached version, return it if (m_pHeaderFieldCache.Contains("Bcc:")) { return (AddressList) m_pHeaderFieldCache["Bcc:"]; } // These isn't cached version, we need to create it else { // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Bcc:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Bcc:"] = list; return list; } } else { return null; } } set { // Just remove header field if (value == null) { m_pHeader.Remove(m_pHeader.GetFirst("Bcc:")); return; } // Release old address collection if (m_pHeaderFieldCache["Bcc:"] != null) { ((AddressList) m_pHeaderFieldCache["Bcc:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField bcc = m_pHeader.GetFirst("Bcc:"); if (bcc == null) { bcc = new HeaderField("Bcc:", value.ToAddressListString()); m_pHeader.Add(bcc); } else { bcc.Value = value.ToAddressListString(); } value.BoundedHeaderField = bcc; m_pHeaderFieldCache["Bcc:"] = value; } } /// <summary> /// Gets or sets header field "<b>Cc:</b>" value. Returns null if value isn't set. /// </summary> public AddressList Cc { get { if (m_pHeader.Contains("Cc:")) { // There is already cached version, return it if (m_pHeaderFieldCache.Contains("Cc:")) { return (AddressList) m_pHeaderFieldCache["Cc:"]; } // These isn't cached version, we need to create it else { // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Cc:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Cc:"] = list; return list; } } else { return null; } } set { // Just remove header field if (value == null) { m_pHeader.Remove(m_pHeader.GetFirst("Cc:")); return; } // Release old address collection if (m_pHeaderFieldCache["Cc:"] != null) { ((AddressList) m_pHeaderFieldCache["Cc:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField cc = m_pHeader.GetFirst("Cc:"); if (cc == null) { cc = new HeaderField("Cc:", value.ToAddressListString()); m_pHeader.Add(cc); } else { cc.Value = value.ToAddressListString(); } value.BoundedHeaderField = cc; m_pHeaderFieldCache["Cc:"] = value; } } /// <summary> /// Gets child entities. This property is available only if ContentType = multipart/... . /// </summary> public MimeEntityCollection ChildEntities { get { return m_pChildEntities; } } /// <summary> /// Gets or sets header field "<b>Content-class:</b>" value. Returns null if value isn't set.<br/> /// Additional property to support messages of CalendarItem type which have iCal/vCal entries. /// </summary> public string ContentClass { get { if (m_pHeader.Contains("Content-Class:")) { return m_pHeader.GetFirst("Content-Class:").Value; } else { return null; } } set { if (m_pHeader.Contains("Content-Class:")) { m_pHeader.GetFirst("Content-Class:").Value = value; } else { m_pHeader.Add("Content-Class:", value); } } } /// <summary> /// Gets or sets header field "<b>Content-Description:</b>" value. Returns null if value isn't set. /// </summary> public string ContentDescription { get { if (m_pHeader.Contains("Content-Description:")) { return m_pHeader.GetFirst("Content-Description:").Value; } else { return null; } } set { if (m_pHeader.Contains("Content-Description:")) { m_pHeader.GetFirst("Content-Description:").Value = value; } else { m_pHeader.Add("Content-Description:", value); } } } /// <summary> /// Gets or sets header field "<b>Content-Disposition:</b>" value. /// </summary> public ContentDisposition_enum ContentDisposition { get { if (m_pHeader.Contains("Content-Disposition:")) { return MimeUtils.ParseContentDisposition(m_pHeader.GetFirst("Content-Disposition:").Value); } else { return ContentDisposition_enum.NotSpecified; } } set { if (value == ContentDisposition_enum.Unknown) { throw new Exception("ContentDisposition_enum.Unknown isn't allowed to set !"); } // Just remove Content-Disposition: header field if exists if (value == ContentDisposition_enum.NotSpecified) { HeaderField disposition = m_pHeader.GetFirst("Content-Disposition:"); if (disposition != null) { m_pHeader.Remove(disposition); } } else { string disposition = MimeUtils.ContentDispositionToString(value); if (m_pHeader.Contains("Content-Disposition:")) { m_pHeader.GetFirst("Content-Disposition:").Value = disposition; } else { m_pHeader.Add("Content-Disposition:", disposition); } } } } /// <summary> /// Gets or sets "<b>Content-Disposition:</b>" header field "<b>filename</b>" parameter. /// Returns null if Content-Disposition: header field value isn't set or Content-Disposition: header field "<b>filename</b>" parameter isn't set. /// Note: Content-Disposition must be attachment or inline. /// </summary> public string ContentDisposition_FileName { get { if (m_pHeader.Contains("Content-Disposition:")) { ParametizedHeaderField contentDisposition = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Disposition:")); if (contentDisposition.Parameters.Contains("filename")) { return MimeUtils.DecodeWords(contentDisposition.Parameters["filename"]); } else { return null; } } else { return null; } } set { if (!m_pHeader.Contains("Content-Disposition:")) { throw new Exception("Please specify Content-Disposition first !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Disposition:")); if (contentType.Parameters.Contains("filename")) { contentType.Parameters["filename"] = MimeUtils.EncodeWord(value); } else { contentType.Parameters.Add("filename", MimeUtils.EncodeWord(value)); } } } /// <summary> /// Gets or sets header field "<b>Content-ID:</b>" value. Returns null if value isn't set. /// </summary> public string ContentID { get { if (m_pHeader.Contains("Content-ID:")) { return m_pHeader.GetFirst("Content-ID:").Value; } else { return null; } } set { if (m_pHeader.Contains("Content-ID:")) { m_pHeader.GetFirst("Content-ID:").Value = value; } else { m_pHeader.Add("Content-ID:", value); } } } /// <summary> /// Gets or sets header field "<b>Content-Transfer-Encoding:</b>" value. This property specifies how data is encoded/decoded. /// If you set this value, it's recommended that you use QuotedPrintable for text and Base64 for binary data. /// 7bit,_8bit,Binary are today obsolete (used for parsing). /// </summary> public ContentTransferEncoding_enum ContentTransferEncoding { get { if (m_pHeader.Contains("Content-Transfer-Encoding:")) { return MimeUtils.ParseContentTransferEncoding( m_pHeader.GetFirst("Content-Transfer-Encoding:").Value); } else { return ContentTransferEncoding_enum.NotSpecified; } } set { if (value == ContentTransferEncoding_enum.Unknown) { throw new Exception("ContentTransferEncoding_enum.Unknown isn't allowed to set !"); } if (value == ContentTransferEncoding_enum.NotSpecified) { throw new Exception("ContentTransferEncoding_enum.NotSpecified isn't allowed to set !"); } string encoding = MimeUtils.ContentTransferEncodingToString(value); // There is entity data specified and encoding changed, we need to convert existing data if (DataEncoded != null) { ContentTransferEncoding_enum oldEncoding = ContentTransferEncoding; if (oldEncoding == ContentTransferEncoding_enum.Unknown || oldEncoding == ContentTransferEncoding_enum.NotSpecified) { throw new Exception("Data can't be converted because old encoding '" + MimeUtils.ContentTransferEncodingToString(oldEncoding) + "' is unknown !"); } DataEncoded = EncodeData(Data, value); } if (m_pHeader.Contains("Content-Transfer-Encoding:")) { m_pHeader.GetFirst("Content-Transfer-Encoding:").Value = encoding; } else { m_pHeader.Add("Content-Transfer-Encoding:", encoding); } } } /// <summary> /// Gets or sets header field "<b>Content-Type:</b>" value. This property specifies what entity data is. /// NOTE: ContentType can't be changed while there is data specified(Exception is thrown) in this mime entity, because it isn't /// possible todo data conversion between different types. For example text/xx has charset parameter and other types don't, /// changing loses it and text data becomes useless. /// </summary> public MediaType_enum ContentType { get { if (m_pHeader.Contains("Content-Type:")) { string contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")).Value; return MimeUtils.ParseMediaType(contentType); } else { return MediaType_enum.NotSpecified; } } set { if (DataEncoded != null) { throw new Exception( "ContentType can't be changed while there is data specified, set data to null before !"); } if (value == MediaType_enum.Unknown) { throw new Exception("MediaType_enum.Unkown isn't allowed to set !"); } if (value == MediaType_enum.NotSpecified) { throw new Exception("MediaType_enum.NotSpecified isn't allowed to set !"); } string contentType = ""; //--- Text/xxx --------------------------------// if (value == MediaType_enum.Text_plain) { contentType = "text/plain; charset=\"utf-8\""; } else if (value == MediaType_enum.Text_html) { contentType = "text/html; charset=\"utf-8\""; } else if (value == MediaType_enum.Text_xml) { contentType = "text/xml; charset=\"utf-8\""; } else if (value == MediaType_enum.Text_rtf) { contentType = "text/rtf; charset=\"utf-8\""; } else if (value == MediaType_enum.Text) { contentType = "text; charset=\"utf-8\""; } //---------------------------------------------// //--- Image/xxx -------------------------------// else if (value == MediaType_enum.Image_gif) { contentType = "image/gif"; } else if (value == MediaType_enum.Image_tiff) { contentType = "image/tiff"; } else if (value == MediaType_enum.Image_jpeg) { contentType = "image/jpeg"; } else if (value == MediaType_enum.Image) { contentType = "image"; } //---------------------------------------------// //--- Audio/xxx -------------------------------// else if (value == MediaType_enum.Audio) { contentType = "audio"; } //---------------------------------------------// //--- Video/xxx -------------------------------// else if (value == MediaType_enum.Video) { contentType = "video"; } //---------------------------------------------// //--- Application/xxx -------------------------// else if (value == MediaType_enum.Application_octet_stream) { contentType = "application/octet-stream"; } else if (value == MediaType_enum.Application) { contentType = "application"; } //---------------------------------------------// //--- Multipart/xxx ---------------------------// else if (value == MediaType_enum.Multipart_mixed) { contentType = "multipart/mixed; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } else if (value == MediaType_enum.Multipart_alternative) { contentType = "multipart/alternative; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } else if (value == MediaType_enum.Multipart_parallel) { contentType = "multipart/parallel; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } else if (value == MediaType_enum.Multipart_related) { contentType = "multipart/related; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } else if (value == MediaType_enum.Multipart_signed) { contentType = "multipart/signed; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } else if (value == MediaType_enum.Multipart) { contentType = "multipart; boundary=\"part_" + Guid.NewGuid().ToString().Replace("-", "_") + "\""; } //---------------------------------------------// //--- Message/xxx -----------------------------// else if (value == MediaType_enum.Message_rfc822) { contentType = "message/rfc822"; } else if (value == MediaType_enum.Message) { contentType = "message"; } //---------------------------------------------// else { throw new Exception("Invalid flags combination of MediaType_enum was specified !"); } if (m_pHeader.Contains("Content-Type:")) { m_pHeader.GetFirst("Content-Type:").Value = contentType; } else { m_pHeader.Add("Content-Type:", contentType); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>boundary</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>boundary</b>" parameter isn't set. /// Note: Content-Type must be multipart/xxx or exception is thrown. /// </summary> public string ContentType_Boundary { get { if (m_pHeader.Contains("Content-Type:")) { ParametizedHeaderField contentDisposition = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentDisposition.Parameters.Contains("boundary")) { return contentDisposition.Parameters["boundary"]; } else { return null; } } else { return null; } } set { if (!m_pHeader.Contains("Content-Type:")) { throw new Exception("Please specify Content-Type first !"); } if ((ContentType & MediaType_enum.Multipart) == 0) { throw new Exception("Parameter boundary is available only for ContentType multipart/xxx !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentType.Parameters.Contains("boundary")) { contentType.Parameters["boundary"] = value; } else { contentType.Parameters.Add("boundary", value); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>charset</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>charset</b>" parameter isn't set. /// If you don't know what charset to use then <b>utf-8</b> is recommended, most of times this is sufficient. /// Note: Content-Type must be text/xxx or exception is thrown. /// </summary> public string ContentType_CharSet { get { if (m_pHeader.Contains("Content-Type:")) { ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentType.Parameters.Contains("charset")) { return contentType.Parameters["charset"]; } else { return null; } } else { return null; } } set { if (!m_pHeader.Contains("Content-Type:")) { throw new Exception("Please specify Content-Type first !"); } if ((ContentType & MediaType_enum.Text) == 0) { throw new Exception("Parameter boundary is available only for ContentType text/xxx !"); } // There is data specified, we need to convert it because charset changed if (DataEncoded != null) { string currentCharSet = ContentType_CharSet; if (currentCharSet == null) { currentCharSet = "ascii"; } if (EncodingTools.GetEncodingByCodepageName(currentCharSet) == null) { throw new Exception("Data can't be converted because current charset '" + currentCharSet + "' isn't supported !"); } Encoding encoding = EncodingTools.GetEncodingByCodepageName(value); if(encoding == null) { throw new Exception("Data can't be converted because new charset '" + value + "' isn't supported !"); } Data = encoding.GetBytes(DataText); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentType.Parameters.Contains("charset")) { contentType.Parameters["charset"] = value; } else { contentType.Parameters.Add("charset", value); } } } /// <summary> /// Gets or sets "<b>Content-Type:</b>" header field "<b>name</b>" parameter. /// Returns null if Content-Type: header field value isn't set or Content-Type: header field "<b>name</b>" parameter isn't set. /// <p/> /// Note: Content-Type must be application/xxx or exception is thrown. /// This property is obsolete today, it's replaced with <b>Content-Disposition: filename</b> parameter. /// If possible always set FileName property instead of it. /// </summary> public string ContentType_Name { get { if (m_pHeader.Contains("Content-Type:")) { ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentType.Parameters.Contains("name")) { return contentType.Parameters["name"]; } else { return null; } } else { return null; } } set { if (!m_pHeader.Contains("Content-Type:")) { throw new Exception("Please specify Content-Type first !"); } if ((ContentType & MediaType_enum.Application) == 0) { throw new Exception("Parameter name is available only for ContentType application/xxx !"); } ParametizedHeaderField contentType = new ParametizedHeaderField(m_pHeader.GetFirst("Content-Type:")); if (contentType.Parameters.Contains("name")) { contentType.Parameters["name"] = value; } else { contentType.Parameters.Add("name", value); } } } /// <summary> /// Gets or sets header field "<b>Content-Type:</b>" value. Returns null if value isn't set. This property specifies what entity data is. /// This property is meant for advanced users, who needs other values what defined MediaType_enum provides. /// Example value: text/plain; charset="utf-8". /// NOTE: ContentType can't be changed while there is data specified(Exception is thrown) in this mime entity, because it isn't /// possible todo data conversion between different types. For example text/xx has charset parameter and other types don't, /// changing loses it and text data becomes useless. /// </summary> public string ContentTypeString { get { if (m_pHeader.Contains("Content-Type:")) { return m_pHeader.GetFirst("Content-Type:").Value; } else { return null; } } set { if (DataEncoded != null) { throw new Exception( "ContentType can't be changed while there is data specified, set data to null before !"); } if (m_pHeader.Contains("Content-Type:")) { m_pHeader.GetFirst("Content-Type:").Value = value; } else { m_pHeader.Add("Content-Type:", value); } } } /// <summary> /// Gets or sets entity data. Data is encoded/decoded with "<b>Content-Transfer-Encoding:</b>" header field value. /// Note: This property can be set only if Content-Type: isn't multipart. /// </summary> public byte[] Data { get { // Decode Data ContentTransferEncoding_enum encoding = ContentTransferEncoding; if (encoding == ContentTransferEncoding_enum.Base64) { return Core.Base64Decode(DataEncoded); } else if (encoding == ContentTransferEncoding_enum.QuotedPrintable) { Encoding enc = ContentType_CharSet == null ? Encoding.ASCII : (EncodingTools.GetEncodingByCodepageName(ContentType_CharSet) ?? Encoding.ASCII); return enc.GetBytes(Core.QuotedPrintableDecode(Encoding.ASCII.GetString(DataEncoded), enc));//decode using ASCII } else { return DataEncoded; } } set { if (value == null) { DataEncoded = null; return; } ContentTransferEncoding_enum encoding = ContentTransferEncoding; DataEncoded = EncodeData(value, encoding); } } /// <summary> /// Gets or sets entity encoded data. If you set this value, be sure that you encode this value as specified by Content-Transfer-Encoding: header field. /// Set this value only if you need custom Content-Transfer-Encoding: what current Mime class won't support, other wise set data through this.Data property. /// Note: This property can be set only if Content-Type: isn't multipart. /// </summary> public byte[] DataEncoded { get { return m_EncodedData; } set { m_EncodedData = value; } } /// <summary> /// Gets or sets entity text data. Data is encoded/decoded with "<b>Content-Transfer-Encoding:</b>" header field value with this.Charset charset. /// Note: This property is available only if ContentType is Text/xxx... or no content type specified, othwerwise Excpetion is thrown. /// </summary> public string DataText { get { if ((ContentType & MediaType_enum.Text) == 0 && (ContentType & MediaType_enum.NotSpecified) == 0) { throw new Exception("This property is only available if ContentType is Text/xxx... !"); } string charSet = ContentType_CharSet; // Charset isn't specified, use system default if (charSet == null) { return Encoding.Default.GetString(Data); } else { // If charset is not supported then use default return (EncodingTools.GetEncodingByCodepageName(charSet) ?? Encoding.Default).GetString(Data); } } set { if (value == null) { DataEncoded = null; return; } // Check charset string charSet = ContentType_CharSet; if (charSet == null) { throw new Exception("Please specify CharSet property first !"); } Encoding encoding = EncodingTools.GetEncodingByCodepageName(charSet); if(encoding == null) { throw new Exception("Not supported charset '" + charSet + "' ! If you need to use this charset, then set data through Data or DataEncoded property."); } Data = encoding.GetBytes(value); } } /// <summary> /// Gets or sets header field "<b>Date:</b>" value. /// </summary> public DateTime Date { get { if (m_pHeader.Contains("Date:")) { try { return MIME_Utils.ParseRfc2822DateTime(m_pHeader.GetFirst("Date:").Value); } catch { return DateTime.MinValue; } } else { return DateTime.MinValue; } } set { if (m_pHeader.Contains("Date:")) { m_pHeader.GetFirst("Date:").Value = MIME_Utils.DateTimeToRfc2822(value); } else { m_pHeader.Add("Date:", MimeUtils.DateTimeToRfc2822(value)); } } } /// <summary> /// Gets or sets header field "<b>Disposition-Notification-To:</b>" value. Returns null if value isn't set. /// </summary> public string DSN { get { if (m_pHeader.Contains("Disposition-Notification-To:")) { return m_pHeader.GetFirst("Disposition-Notification-To:").Value; } else { return null; } } set { if (m_pHeader.Contains("Disposition-Notification-To:")) { m_pHeader.GetFirst("Disposition-Notification-To:").Value = value; } else { m_pHeader.Add("Disposition-Notification-To:", value); } } } /// <summary> /// Gets or sets header field "<b>From:</b>" value. Returns null if value isn't set. /// </summary> public AddressList From { get { if (m_pHeader.Contains("From:")) { // There is already cached version, return it if (m_pHeaderFieldCache.Contains("From:")) { return (AddressList) m_pHeaderFieldCache["From:"]; } // These isn't cached version, we need to create it else { // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("From:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["From:"] = list; return list; } } else { return null; } } set { // Just remove header field if (value == null && m_pHeader.Contains("From:")) { m_pHeader.Remove(m_pHeader.GetFirst("From:")); return; } // Release old address collection if (m_pHeaderFieldCache["From:"] != null) { ((AddressList) m_pHeaderFieldCache["From:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField from = m_pHeader.GetFirst("From:"); if (from == null) { from = new HeaderField("From:", value.ToAddressListString()); m_pHeader.Add(from); } else { from.Value = value.ToAddressListString(); } value.BoundedHeaderField = from; m_pHeaderFieldCache["From:"] = value; } } /// <summary> /// Gets message header. /// </summary> public HeaderFieldCollection Header { get { return m_pHeader; } } /// <summary> /// Gets header as RFC 2822 message headers. /// </summary> public string HeaderString { get { return m_pHeader.ToHeaderString("utf-8"); } } /// <summary> /// Gets or sets header field "<b>In-Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public string InReplyTo { get { if (m_pHeader.Contains("In-Reply-To:")) { return m_pHeader.GetFirst("In-Reply-To:").Value; } else { return null; } } set { if (m_pHeader.Contains("In-Reply-To:")) { m_pHeader.GetFirst("In-Reply-To:").Value = value; } else { m_pHeader.Add("In-Reply-To:", value); } } } /// <summary> /// Gets or sets header field "<b>Message-ID:</b>" value. Returns null if value isn't set. /// Syntax: '&lt;'id-left@id-right'&gt;'. Example: &lt;621bs724bfs8@jnfsjaas4263&gt; /// </summary> public string MessageID { get { if (m_pHeader.Contains("Message-ID:")) { return m_pHeader.GetFirst("Message-ID:").Value; } else { return null; } } set { if (m_pHeader.Contains("Message-ID:")) { m_pHeader.GetFirst("Message-ID:").Value = value; } else { m_pHeader.Add("Message-ID:", value); } } } /// <summary> /// Gets or sets header field "<b>Mime-Version:</b>" value. Returns null if value isn't set. /// </summary> public string MimeVersion { get { if (m_pHeader.Contains("Mime-Version:")) { return m_pHeader.GetFirst("Mime-Version:").Value; } else { return null; } } set { if (m_pHeader.Contains("Mime-Version:")) { m_pHeader.GetFirst("Mime-Version:").Value = value; } else { m_pHeader.Add("Mime-Version:", value); } } } /// <summary> /// Gets parent entity of this entity. If this entity is top level, then this property returns null. /// </summary> public MimeEntity ParentEntity { get { return m_pParentEntity; } } /// <summary> /// Gets or sets header field "<b>Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public AddressList ReplyTo { get { if (m_pHeader.Contains("Reply-To:")) { // There is already cached version, return it if (m_pHeaderFieldCache.Contains("Reply-To:")) { return (AddressList) m_pHeaderFieldCache["Reply-To:"]; } // These isn't cached version, we need to create it else { // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("Reply-To:"); AddressList list = new AddressList(); list.Parse(field.Value); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["Reply-To:"] = list; return list; } } else { return null; } } set { // Just remove header field if (value == null && m_pHeader.Contains("Reply-To:")) { m_pHeader.Remove(m_pHeader.GetFirst("Reply-To:")); return; } // Release old address collection if (m_pHeaderFieldCache["Reply-To:"] != null) { ((AddressList) m_pHeaderFieldCache["Reply-To:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField replyTo = m_pHeader.GetFirst("Reply-To:"); if (replyTo == null) { replyTo = new HeaderField("Reply-To:", value.ToAddressListString()); m_pHeader.Add(replyTo); } else { replyTo.Value = value.ToAddressListString(); } value.BoundedHeaderField = replyTo; m_pHeaderFieldCache["Reply-To:"] = value; } } /// <summary> /// Gets or sets header field "<b>Sender:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress Sender { get { if (m_pHeader.Contains("Sender:")) { return MailboxAddress.Parse(m_pHeader.GetFirst("Sender:").EncodedValue); } else { return null; } } set { if (m_pHeader.Contains("Sender:")) { m_pHeader.GetFirst("Sender:").Value = value.ToMailboxAddressString(); } else { m_pHeader.Add("Sender:", value.ToMailboxAddressString()); } } } /// <summary> /// Gets or sets header field "<b>Subject:</b>" value. Returns null if value isn't set. /// </summary> public string Subject { get { if (m_pHeader.Contains("Subject:")) { return m_pHeader.GetFirst("Subject:").Value; } else { return null; } } set { if (m_pHeader.Contains("Subject:")) { m_pHeader.GetFirst("Subject:").Value = value; } else { m_pHeader.Add("Subject:", value); } } } /// <summary> /// Gets or sets header field "<b>To:</b>" value. Returns null if value isn't set. /// </summary> public AddressList To { get { if (m_pHeader.Contains("To:")) { // There is already cached version, return it if (m_pHeaderFieldCache.Contains("To:")) { return (AddressList) m_pHeaderFieldCache["To:"]; } // These isn't cached version, we need to create it else { // Create and bound address-list to existing header field HeaderField field = m_pHeader.GetFirst("To:"); AddressList list = new AddressList(); list.Parse(field.EncodedValue); list.BoundedHeaderField = field; // Cache header field m_pHeaderFieldCache["To:"] = list; return list; } } else { return null; } } set { // Just remove header field if (value == null) { m_pHeader.Remove(m_pHeader.GetFirst("To:")); return; } // Release old address collection if (m_pHeaderFieldCache["To:"] != null) { ((AddressList) m_pHeaderFieldCache["To:"]).BoundedHeaderField = null; } // Bound address-list to To: header field. If header field doesn't exist, add it. HeaderField to = m_pHeader.GetFirst("To:"); if (to == null) { to = new HeaderField("To:", value.ToAddressListString()); m_pHeader.Add(to); } else { to.Value = value.ToAddressListString(); } value.BoundedHeaderField = to; m_pHeaderFieldCache["To:"] = value; } } #endregion #region Methods /// <summary> /// Stores mime entity and it's child entities to specified stream. /// </summary> /// <param name="storeStream">Stream where to store mime entity.</param> public void ToStream(Stream storeStream) { // Write headers byte[] data = Encoding.Default.GetBytes(FoldHeader(HeaderString)); storeStream.Write(data, 0, data.Length); // If multipart entity, write child entities.(multipart entity don't contain data, it contains nested entities ) if ((ContentType & MediaType_enum.Multipart) != 0) { string boundary = ContentType_Boundary; foreach (MimeEntity entity in ChildEntities) { // Write boundary start. Syntax: <CRLF>--BoundaryID<CRLF> data = Encoding.Default.GetBytes("\r\n--" + boundary + "\r\n"); storeStream.Write(data, 0, data.Length); // Force child entity to store itself entity.ToStream(storeStream); } // Write boundaries end Syntax: <CRLF>--BoundaryID--<CRLF> data = Encoding.Default.GetBytes("\r\n--" + boundary + "--\r\n"); storeStream.Write(data, 0, data.Length); } // If singlepart (text,image,audio,video,message, ...), write entity data. else { // Write blank line between headers and content storeStream.Write(new[] {(byte) '\r', (byte) '\n'}, 0, 2); if (DataEncoded != null) { storeStream.Write(DataEncoded, 0, DataEncoded.Length); } } } /// <summary> /// Saves this.Data property value to specified file. /// </summary> /// <param name="fileName">File name where to store data.</param> public void DataToFile(string fileName) { using (FileStream fs = File.Create(fileName)) { DataToStream(fs); } } /// <summary> /// Saves this.Data property value to specified stream. /// </summary> /// <param name="stream">Stream where to store data.</param> public void DataToStream(Stream stream) { byte[] data = Data; stream.Write(data, 0, data.Length); } /// <summary> /// Loads MimeEntity.Data property from file. /// </summary> /// <param name="fileName">File name.</param> public void DataFromFile(string fileName) { using (FileStream fs = File.OpenRead(fileName)) { DataFromStream(fs); } } /// <summary> /// Loads MimeEntity.Data property from specified stream. Note: reading starts from current position and stream isn't closed. /// </summary> /// <param name="stream">Data stream.</param> public void DataFromStream(Stream stream) { byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int) stream.Length); Data = data; } #endregion #region Internal methods /// <summary> /// Parses mime entity from stream. /// </summary> /// <param name="stream">Data stream from where to read data.</param> /// <param name="toBoundary">Entity data is readed to specified boundary.</param> /// <returns>Returns false if last entity. Returns true for mulipart entity, if there are more entities.</returns> internal bool Parse(SmartStream stream, string toBoundary) { // Clear header fields m_pHeader.Clear(); m_pHeaderFieldCache.Clear(); // Parse header m_pHeader.Parse(stream); // Parse entity and child entities if any (Conent-Type: multipart/xxx...) // Multipart entity if ((ContentType & MediaType_enum.Multipart) != 0) { // There must be be boundary ID (rfc 1341 7.2.1 The Content-Type field for multipart entities requires one parameter, // "boundary", which is used to specify the encapsulation boundary.) string boundaryID = ContentType_Boundary; if (boundaryID == null) { // This is invalid message, just skip this mime entity } else { // There is one or more mime entities // Find first boundary start position SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[8000], SizeExceededAction. JunkAndThrowException); stream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } string lineString = args.LineUtf8; while (lineString != null) { if (lineString.StartsWith("--" + boundaryID)) { break; } stream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } lineString = args.LineUtf8; } // This is invalid entity, boundary start not found. Skip that entity. if (string.IsNullOrEmpty(lineString)) { return false; } // Start parsing child entities of this entity while (true) { // Parse and add child entity MimeEntity childEntity = new MimeEntity(); ChildEntities.Add(childEntity); // This is last entity, stop parsing if (childEntity.Parse(stream, boundaryID) == false) { break; } // else{ // There are more entities, parse them } // This entity is child of mulipart entity. // All this entity child entities are parsed, // we need to move stream position to next entity start. if (!string.IsNullOrEmpty(toBoundary)) { stream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } lineString = args.LineUtf8; while (lineString != null) { if (lineString.StartsWith("--" + toBoundary)) { break; } stream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } lineString = args.LineUtf8; } // Invalid boundary end, there can't be more entities if (string.IsNullOrEmpty(lineString)) { return false; } // See if last boundary or there is more. Last boundary ends with -- if (lineString.EndsWith(toBoundary + "--")) { return false; } // else{ // There are more entities return true; } } } // Singlepart entity. else { // Boundary is specified, read data to specified boundary. if (!string.IsNullOrEmpty(toBoundary)) { MemoryStream entityData = new MemoryStream(); SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction . JunkAndThrowException); // Read entity data while get boundary end tag --boundaryID-- or EOS. while (true) { stream.ReadLine(readLineOP, false); if (readLineOP.Error != null) { throw readLineOP.Error; } // End of stream reached. Normally we should get boundary end tag --boundaryID--, but some x mailers won't add it, so // if we reach EOS, consider boundary closed. if (readLineOP.BytesInBuffer == 0) { // Just return data what was readed. m_EncodedData = entityData.ToArray(); return false; } // We readed a line. else { // We have boundary start/end tag or just "--" at the beginning of line. if (readLineOP.LineBytesInBuffer >= 2 && readLineOP.Buffer[0] == '-' && readLineOP.Buffer[1] == '-') { string lineString = readLineOP.LineUtf8; // We have boundary end tag, no more boundaries. if (lineString == "--" + toBoundary + "--") { m_EncodedData = entityData.ToArray(); return false; } // We have new boundary start. else if (lineString == "--" + toBoundary) { m_EncodedData = entityData.ToArray(); return true; } else { // Just skip } } // Write readed line. entityData.Write(readLineOP.Buffer, 0, readLineOP.BytesInBuffer); } } } // Boundary isn't specified, read data to the stream end. else { MemoryStream ms = new MemoryStream(); stream.ReadAll(ms); m_EncodedData = ms.ToArray(); } } return false; } #endregion #region Utility methods /// <summary> /// Encodes data with specified content transfer encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <param name="encoding">Encoding with what to encode data.</param> private byte[] EncodeData(byte[] data, ContentTransferEncoding_enum encoding) { // Allow only known Content-Transfer-Encoding (ContentTransferEncoding_enum value), // otherwise we don't know how to encode data. if (encoding == ContentTransferEncoding_enum.NotSpecified) { throw new Exception("Please specify Content-Transfer-Encoding first !"); } if (encoding == ContentTransferEncoding_enum.Unknown) { throw new Exception( "Not supported Content-Transfer-Encoding. If it's your custom encoding, encode data yourself and set it with DataEncoded property !"); } if (encoding == ContentTransferEncoding_enum.Base64) { return Core.Base64Encode(data); } else if (encoding == ContentTransferEncoding_enum.QuotedPrintable) { return Core.QuotedPrintableEncode(data); } else { return data; } } /// <summary> /// Folds header. /// </summary> /// <param name="header">Header string.</param> /// <returns></returns> private string FoldHeader(string header) { /* Rfc 2822 2.2.3 Long Header Fields Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is imply WSP characters), a CRLF may be inserted before any WSP. For example, the header field: Subject: This is a test can be represented as: Subject: This is a test */ // Just fold header fields what contain <TAB> StringBuilder retVal = new StringBuilder(); header = header.Replace("\r\n", "\n"); string[] headerLines = header.Split('\n'); foreach (string headerLine in headerLines) { // Folding is needed if (headerLine.IndexOf('\t') > -1) { retVal.Append(headerLine.Replace("\t", "\r\n\t") + "\r\n"); } // No folding needed, just write back header line else { retVal.Append(headerLine + "\r\n"); } } // Split splits last line <CRLF> to element, but we don't need it if (retVal.Length > 1) { return retVal.ToString(0, retVal.Length - 2); } else { return retVal.ToString(); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache { using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; /// <summary> /// Cache metrics used to obtain statistics on cache. /// </summary> internal class CacheMetricsImpl : ICacheMetrics { /** */ private readonly long _cacheHits; /** */ private readonly float _cacheHitPercentage; /** */ private readonly long _cacheMisses; /** */ private readonly float _cacheMissPercentage; /** */ private readonly long _cacheGets; /** */ private readonly long _cachePuts; /** */ private readonly long _cacheRemovals; /** */ private readonly long _cacheEvictions; /** */ private readonly float _averageGetTime; /** */ private readonly float _averagePutTime; /** */ private readonly float _averageRemoveTime; /** */ private readonly float _averageTxCommitTime; /** */ private readonly float _averageTxRollbackTime; /** */ private readonly long _cacheTxCommits; /** */ private readonly long _cacheTxRollbacks; /** */ private readonly string _cacheName; /** */ private readonly long _offHeapGets; /** */ private readonly long _offHeapPuts; /** */ private readonly long _offHeapRemovals; /** */ private readonly long _offHeapEvictions; /** */ private readonly long _offHeapHits; /** */ private readonly float _offHeapHitPercentage; /** */ private readonly long _offHeapMisses; /** */ private readonly float _offHeapMissPercentage; /** */ private readonly long _offHeapEntriesCount; /** */ private readonly long _offHeapPrimaryEntriesCount; /** */ private readonly long _offHeapBackupEntriesCount; /** */ private readonly long _offHeapAllocatedSize; /** */ private readonly int _size; /** */ private readonly int _keySize; /** */ private readonly bool _isEmpty; /** */ private readonly int _dhtEvictQueueCurrentSize; /** */ private readonly int _txThreadMapSize; /** */ private readonly int _txXidMapSize; /** */ private readonly int _txCommitQueueSize; /** */ private readonly int _txPrepareQueueSize; /** */ private readonly int _txStartVersionCountsSize; /** */ private readonly int _txCommittedVersionsSize; /** */ private readonly int _txRolledbackVersionsSize; /** */ private readonly int _txDhtThreadMapSize; /** */ private readonly int _txDhtXidMapSize; /** */ private readonly int _txDhtCommitQueueSize; /** */ private readonly int _txDhtPrepareQueueSize; /** */ private readonly int _txDhtStartVersionCountsSize; /** */ private readonly int _txDhtCommittedVersionsSize; /** */ private readonly int _txDhtRolledbackVersionsSize; /** */ private readonly bool _isWriteBehindEnabled; /** */ private readonly int _writeBehindFlushSize; /** */ private readonly int _writeBehindFlushThreadCount; /** */ private readonly long _writeBehindFlushFrequency; /** */ private readonly int _writeBehindStoreBatchSize; /** */ private readonly int _writeBehindTotalCriticalOverflowCount; /** */ private readonly int _writeBehindCriticalOverflowCount; /** */ private readonly int _writeBehindErrorRetryCount; /** */ private readonly int _writeBehindBufferSize; /** */ private readonly string _keyType; /** */ private readonly string _valueType; /** */ private readonly bool _isStoreByValue; /** */ private readonly bool _isStatisticsEnabled; /** */ private readonly bool _isManagementEnabled; /** */ private readonly bool _isReadThrough; /** */ private readonly bool _isWriteThrough; /// <summary> /// Initializes a new instance of the <see cref="CacheMetricsImpl"/> class. /// </summary> /// <param name="reader">The reader.</param> public CacheMetricsImpl(IBinaryRawReader reader) { _cacheHits = reader.ReadLong(); _cacheHitPercentage = reader.ReadFloat(); _cacheMisses = reader.ReadLong(); _cacheMissPercentage = reader.ReadFloat(); _cacheGets = reader.ReadLong(); _cachePuts = reader.ReadLong(); _cacheRemovals = reader.ReadLong(); _cacheEvictions = reader.ReadLong(); _averageGetTime = reader.ReadFloat(); _averagePutTime = reader.ReadFloat(); _averageRemoveTime = reader.ReadFloat(); _averageTxCommitTime = reader.ReadFloat(); _averageTxRollbackTime = reader.ReadFloat(); _cacheTxCommits = reader.ReadLong(); _cacheTxRollbacks = reader.ReadLong(); _cacheName = reader.ReadString(); _offHeapGets = reader.ReadLong(); _offHeapPuts = reader.ReadLong(); _offHeapRemovals = reader.ReadLong(); _offHeapEvictions = reader.ReadLong(); _offHeapHits = reader.ReadLong(); _offHeapHitPercentage = reader.ReadFloat(); _offHeapMisses = reader.ReadLong(); _offHeapMissPercentage = reader.ReadFloat(); _offHeapEntriesCount = reader.ReadLong(); _offHeapPrimaryEntriesCount = reader.ReadLong(); _offHeapBackupEntriesCount = reader.ReadLong(); _offHeapAllocatedSize = reader.ReadLong(); _size = reader.ReadInt(); _keySize = reader.ReadInt(); _isEmpty = reader.ReadBoolean(); _dhtEvictQueueCurrentSize = reader.ReadInt(); _txThreadMapSize = reader.ReadInt(); _txXidMapSize = reader.ReadInt(); _txCommitQueueSize = reader.ReadInt(); _txPrepareQueueSize = reader.ReadInt(); _txStartVersionCountsSize = reader.ReadInt(); _txCommittedVersionsSize = reader.ReadInt(); _txRolledbackVersionsSize = reader.ReadInt(); _txDhtThreadMapSize = reader.ReadInt(); _txDhtXidMapSize = reader.ReadInt(); _txDhtCommitQueueSize = reader.ReadInt(); _txDhtPrepareQueueSize = reader.ReadInt(); _txDhtStartVersionCountsSize = reader.ReadInt(); _txDhtCommittedVersionsSize = reader.ReadInt(); _txDhtRolledbackVersionsSize = reader.ReadInt(); _isWriteBehindEnabled = reader.ReadBoolean(); _writeBehindFlushSize = reader.ReadInt(); _writeBehindFlushThreadCount = reader.ReadInt(); _writeBehindFlushFrequency = reader.ReadLong(); _writeBehindStoreBatchSize = reader.ReadInt(); _writeBehindTotalCriticalOverflowCount = reader.ReadInt(); _writeBehindCriticalOverflowCount = reader.ReadInt(); _writeBehindErrorRetryCount = reader.ReadInt(); _writeBehindBufferSize = reader.ReadInt(); _keyType = reader.ReadString(); _valueType = reader.ReadString(); _isStoreByValue = reader.ReadBoolean(); _isStatisticsEnabled = reader.ReadBoolean(); _isManagementEnabled = reader.ReadBoolean(); _isReadThrough = reader.ReadBoolean(); _isWriteThrough = reader.ReadBoolean(); } /** <inheritDoc /> */ public long CacheHits { get { return _cacheHits; } } /** <inheritDoc /> */ public float CacheHitPercentage { get { return _cacheHitPercentage; } } /** <inheritDoc /> */ public long CacheMisses { get { return _cacheMisses; } } /** <inheritDoc /> */ public float CacheMissPercentage { get { return _cacheMissPercentage; } } /** <inheritDoc /> */ public long CacheGets { get { return _cacheGets; } } /** <inheritDoc /> */ public long CachePuts { get { return _cachePuts; } } /** <inheritDoc /> */ public long CacheRemovals { get { return _cacheRemovals; } } /** <inheritDoc /> */ public long CacheEvictions { get { return _cacheEvictions; } } /** <inheritDoc /> */ public float AverageGetTime { get { return _averageGetTime; } } /** <inheritDoc /> */ public float AveragePutTime { get { return _averagePutTime; } } /** <inheritDoc /> */ public float AverageRemoveTime { get { return _averageRemoveTime; } } /** <inheritDoc /> */ public float AverageTxCommitTime { get { return _averageTxCommitTime; } } /** <inheritDoc /> */ public float AverageTxRollbackTime { get { return _averageTxRollbackTime; } } /** <inheritDoc /> */ public long CacheTxCommits { get { return _cacheTxCommits; } } /** <inheritDoc /> */ public long CacheTxRollbacks { get { return _cacheTxRollbacks; } } /** <inheritDoc /> */ public string CacheName { get { return _cacheName; } } /** <inheritDoc /> */ public long OffHeapGets { get { return _offHeapGets; } } /** <inheritDoc /> */ public long OffHeapPuts { get { return _offHeapPuts; } } /** <inheritDoc /> */ public long OffHeapRemovals { get { return _offHeapRemovals; } } /** <inheritDoc /> */ public long OffHeapEvictions { get { return _offHeapEvictions; } } /** <inheritDoc /> */ public long OffHeapHits { get { return _offHeapHits; } } /** <inheritDoc /> */ public float OffHeapHitPercentage { get { return _offHeapHitPercentage; } } /** <inheritDoc /> */ public long OffHeapMisses { get { return _offHeapMisses; } } /** <inheritDoc /> */ public float OffHeapMissPercentage { get { return _offHeapMissPercentage; } } /** <inheritDoc /> */ public long OffHeapEntriesCount { get { return _offHeapEntriesCount; } } /** <inheritDoc /> */ public long OffHeapPrimaryEntriesCount { get { return _offHeapPrimaryEntriesCount; } } /** <inheritDoc /> */ public long OffHeapBackupEntriesCount { get { return _offHeapBackupEntriesCount; } } /** <inheritDoc /> */ public long OffHeapAllocatedSize { get { return _offHeapAllocatedSize; } } /** <inheritDoc /> */ public int Size { get { return _size; } } /** <inheritDoc /> */ public int KeySize { get { return _keySize; } } /** <inheritDoc /> */ public bool IsEmpty { get { return _isEmpty; } } /** <inheritDoc /> */ public int DhtEvictQueueCurrentSize { get { return _dhtEvictQueueCurrentSize; } } /** <inheritDoc /> */ public int TxThreadMapSize { get { return _txThreadMapSize; } } /** <inheritDoc /> */ public int TxXidMapSize { get { return _txXidMapSize; } } /** <inheritDoc /> */ public int TxCommitQueueSize { get { return _txCommitQueueSize; } } /** <inheritDoc /> */ public int TxPrepareQueueSize { get { return _txPrepareQueueSize; } } /** <inheritDoc /> */ public int TxStartVersionCountsSize { get { return _txStartVersionCountsSize; } } /** <inheritDoc /> */ public int TxCommittedVersionsSize { get { return _txCommittedVersionsSize; } } /** <inheritDoc /> */ public int TxRolledbackVersionsSize { get { return _txRolledbackVersionsSize; } } /** <inheritDoc /> */ public int TxDhtThreadMapSize { get { return _txDhtThreadMapSize; } } /** <inheritDoc /> */ public int TxDhtXidMapSize { get { return _txDhtXidMapSize; } } /** <inheritDoc /> */ public int TxDhtCommitQueueSize { get { return _txDhtCommitQueueSize; } } /** <inheritDoc /> */ public int TxDhtPrepareQueueSize { get { return _txDhtPrepareQueueSize; } } /** <inheritDoc /> */ public int TxDhtStartVersionCountsSize { get { return _txDhtStartVersionCountsSize; } } /** <inheritDoc /> */ public int TxDhtCommittedVersionsSize { get { return _txDhtCommittedVersionsSize; } } /** <inheritDoc /> */ public int TxDhtRolledbackVersionsSize { get { return _txDhtRolledbackVersionsSize; } } /** <inheritDoc /> */ public bool IsWriteBehindEnabled { get { return _isWriteBehindEnabled; } } /** <inheritDoc /> */ public int WriteBehindFlushSize { get { return _writeBehindFlushSize; } } /** <inheritDoc /> */ public int WriteBehindFlushThreadCount { get { return _writeBehindFlushThreadCount; } } /** <inheritDoc /> */ public long WriteBehindFlushFrequency { get { return _writeBehindFlushFrequency; } } /** <inheritDoc /> */ public int WriteBehindStoreBatchSize { get { return _writeBehindStoreBatchSize; } } /** <inheritDoc /> */ public int WriteBehindTotalCriticalOverflowCount { get { return _writeBehindTotalCriticalOverflowCount; } } /** <inheritDoc /> */ public int WriteBehindCriticalOverflowCount { get { return _writeBehindCriticalOverflowCount; } } /** <inheritDoc /> */ public int WriteBehindErrorRetryCount { get { return _writeBehindErrorRetryCount; } } /** <inheritDoc /> */ public int WriteBehindBufferSize { get { return _writeBehindBufferSize; } } /** <inheritDoc /> */ public string KeyType { get { return _keyType; } } /** <inheritDoc /> */ public string ValueType { get { return _valueType; } } /** <inheritDoc /> */ public bool IsStoreByValue { get { return _isStoreByValue; } } /** <inheritDoc /> */ public bool IsStatisticsEnabled { get { return _isStatisticsEnabled; } } /** <inheritDoc /> */ public bool IsManagementEnabled { get { return _isManagementEnabled; } } /** <inheritDoc /> */ public bool IsReadThrough { get { return _isReadThrough; } } /** <inheritDoc /> */ public bool IsWriteThrough { get { return _isWriteThrough; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndNotInt64() { var test = new SimpleBinaryOpTest__AndNotInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotInt64 testClass) { var result = Avx2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt64 testClass) { fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public SimpleBinaryOpTest__AndNotInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.AndNot( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.AndNot( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int64>* pClsVar1 = &_clsVar1) fixed (Vector256<Int64>* pClsVar2 = &_clsVar2) { var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(pClsVar1)), Avx.LoadVector256((Int64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotInt64(); var result = Avx2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotInt64(); fixed (Vector256<Int64>* pFld1 = &test._fld1) fixed (Vector256<Int64>* pFld2 = &test._fld2) { var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.AndNot( Avx.LoadVector256((Int64*)(&test._fld1)), Avx.LoadVector256((Int64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((long)(~left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(~left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Numerics; partial class VectorTest { const int Pass = 100; const int Fail = -1; static Random random; // Arrays to use for creating random Vectors. static Double[] doubles; static Single[] singles; static Int64[] int64s; static UInt64[] uint64s; static Int32[] int32s; static UInt32[] uint32s; static Int16[] int16s; static UInt16[] uint16s; static SByte[] sbytes; static Byte[] bytes; // Arrays with some boundary condition values static Double[] firstDoubles; static Single[] firstSingles; static Int64[] firstInt64s; static UInt64[] firstUInt64s; static Int32[] firstInt32s; static UInt32[] firstUInt32s; static Int16[] firstInt16s; static UInt16[] firstUInt16s; static SByte[] firstSBytes; static Byte[] firstBytes; static VectorTest() { doubles = new Double[Vector<Double>.Count]; singles = new Single[Vector<Single>.Count]; int64s = new Int64[Vector<Int64>.Count]; uint64s = new UInt64[Vector<UInt64>.Count]; int32s = new Int32[Vector<Int32>.Count]; uint32s = new UInt32[Vector<UInt32>.Count]; int16s = new Int16[Vector<Int16>.Count]; uint16s = new UInt16[Vector<UInt16>.Count]; sbytes = new SByte[Vector<SByte>.Count]; bytes = new Byte[Vector<Byte>.Count]; unchecked { firstDoubles = new Double[] { Double.MinValue, Double.MaxValue, (Double)Int64.MinValue, (Double)(Int64.MinValue), (Double)(UInt64.MinValue), (Double)(UInt64.MaxValue) }; firstSingles = new Single[] { Single.MinValue, Single.MaxValue, (Single)Int32.MinValue, (Single)(Int32.MinValue), (Single)(UInt32.MinValue), (Single)(UInt32.MaxValue) }; firstInt64s = new Int64[] { Int64.MinValue, Int64.MaxValue, (Int64)Double.MinValue, (Int64)(Double.MinValue), (Int64)(UInt64.MinValue), (Int64)(UInt64.MaxValue) }; firstUInt64s = new UInt64[] { UInt64.MinValue, UInt64.MaxValue, (UInt64)Double.MinValue, (UInt64)(Double.MinValue), (UInt64)(Int64.MinValue), (UInt64)(Int64.MaxValue) }; firstInt32s = new Int32[] { Int32.MinValue, Int32.MaxValue, (Int32)Single.MinValue, (Int32)(Single.MinValue), (Int32)(UInt32.MinValue), (Int32)(UInt32.MaxValue) }; firstUInt32s = new UInt32[] { UInt32.MinValue, UInt32.MaxValue, (UInt32)Single.MinValue, (UInt32)(Single.MinValue), (UInt32)(Int32.MinValue), (UInt32)(Int32.MaxValue) }; firstInt16s = new Int16[] { Int16.MinValue, Int16.MaxValue, SByte.MinValue, SByte.MaxValue, (Int16)(UInt16.MinValue), (Int16)(UInt16.MaxValue) }; firstUInt16s = new UInt16[] { UInt16.MinValue, UInt16.MaxValue, Byte.MinValue, Byte.MaxValue, (UInt16)(Int16.MinValue), (UInt16)(Int16.MaxValue) }; firstSBytes = new SByte[] { SByte.MinValue, SByte.MaxValue, (SByte)(Byte.MinValue), (SByte)(Byte.MaxValue) }; firstBytes = new Byte[] { Byte.MinValue, Byte.MaxValue, (Byte)(SByte.MinValue), (Byte)(SByte.MaxValue) }; } random = new Random(1234); } static T getRandomValue<T>(int i, int j) where T : struct { int element = i + j * Vector<T>.Count; int sign = (random.Next(0, 2) < 1) ? -1 : 1; double randomDouble = random.NextDouble(); if (typeof(T) == typeof(float)) { if (element < firstSingles.Length) return (T)(object)firstSingles[element]; float floatValue = (float)randomDouble * (float)(Int32.MaxValue) * (float)sign; return (T)(object)floatValue; } if (typeof(T) == typeof(double)) { if (element < firstDoubles.Length) return (T)(object)firstDoubles[element]; return (T)(object)(randomDouble * (double)(Int64.MaxValue) * (double)sign); } if (typeof(T) == typeof(Int64)) { if (element < firstInt64s.Length) return (T)(object)firstInt64s[element]; return (T)(object)(Int64)(randomDouble * (double)(Int64.MaxValue) * (double)sign); } if (typeof(T) == typeof(UInt64)) { if (element < firstUInt64s.Length) return (T)(object)firstUInt64s[element]; return (T)(object)(UInt64)(randomDouble * (double)(Int64.MaxValue)); } if ((typeof(T) == typeof(Int32)) && (element < firstInt32s.Length)) return (T)(object)firstInt32s[element]; if ((typeof(T) == typeof(UInt32)) && (element < firstUInt32s.Length)) return (T)(object)firstUInt32s[element]; if ((typeof(T) == typeof(Int16)) && (element < firstInt16s.Length)) return (T)(object)firstInt16s[element]; if ((typeof(T) == typeof(UInt16)) && (element < firstUInt16s.Length)) return (T)(object)firstUInt16s[element]; if ((typeof(T) == typeof(SByte)) && (element < firstSBytes.Length)) return (T)(object)firstSBytes[element]; if ((typeof(T) == typeof(Byte)) && (element < firstBytes.Length)) return (T)(object)firstBytes[element]; int intValue = sign * (int)(randomDouble * (double)(Int32.MaxValue)); T value = GetValueFromInt<T>(intValue); return value; } static Vector<T> getRandomVector<T>(T[] valueArray, int j) where T : struct { for (int i = 0; i < Vector<T>.Count; i++) { valueArray[i] = getRandomValue<T>(i, j); } return new Vector<T>(valueArray); } class VectorConvertTest { public static int VectorConvertSingleInt(Vector<Single> A) { Vector<Int32> B = Vector.ConvertToInt32(A); Vector<Single> C = Vector.ConvertToSingle(B); int returnVal = Pass; for (int i = 0; i < Vector<Single>.Count; i++) { Int32 int32Val = (Int32)A[i]; Single cvtSglVal = (Single)int32Val; if (B[i] != int32Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", int32Val = " + int32Val); returnVal = Fail; } if (C[i] != cvtSglVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtSglVal = " + cvtSglVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertSingleUInt(Vector<Single> A) { Vector<UInt32> B = Vector.ConvertToUInt32(A); Vector<Single> C = Vector.ConvertToSingle(B); int returnVal = Pass; for (int i = 0; i < Vector<Single>.Count; i++) { UInt32 uint32Val = (UInt32)A[i]; Single cvtSglVal = (Single)uint32Val; if ((B[i] != uint32Val) || (C[i] != cvtSglVal)) { Console.WriteLine("A[{0}] = {1}, B[{0}] = {2}, C[{0}] = {3}, uint32Val = {4}, cvtSglVal = {5}", i, A[i], B[i], C[i], uint32Val, cvtSglVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleInt64(Vector<Double> A) { Vector<Int64> B = Vector.ConvertToInt64(A); Vector<Double> C = Vector.ConvertToDouble(B); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { Int64 int64Val = (Int64)A[i]; Double cvtDblVal = (Double)int64Val; if (B[i] != int64Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", int64Val = " + int64Val); returnVal = Fail; } if (C[i] != cvtDblVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtDblVal = " + cvtDblVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleUInt64(Vector<Double> A) { Vector<UInt64> B = Vector.ConvertToUInt64(A); Vector<Double> C = Vector.ConvertToDouble(B); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { UInt64 uint64Val = (UInt64)A[i]; Double cvtDblVal = (Double)uint64Val; if ((B[i] != uint64Val) || (C[i] != cvtDblVal)) { Console.WriteLine("A[{0}] = {1}, B[{0}] = {2}, C[{0}] = {3}, uint64Val = {4}, cvtDblVal = {5}", i, A[i], B[i], C[i], uint64Val, cvtDblVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleSingle(Vector<Double> A1, Vector<Double> A2) { Vector<Single> B = Vector.Narrow(A1, A2); Vector<Double> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { Single sglVal1 = (Single)A1[i]; Single sglVal2 = (Single)A2[i]; Double dblVal1 = (Double)sglVal1; Double dblVal2 = (Double)sglVal2; if (B[i] != sglVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", sglVal1 = " + sglVal1); returnVal = Fail; } int i2 = i + Vector<Double>.Count; if (B[i2] != sglVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", sglVal2 = " + sglVal2); returnVal = Fail; } if (C1[i] != dblVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", dblVal1 = " + dblVal1); returnVal = Fail; } if (C2[i] != dblVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", dblVal2 = " + dblVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt64And32(Vector<Int64> A1, Vector<Int64> A2) { Vector<Int32> B = Vector.Narrow(A1, A2); Vector<Int64> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int64>.Count; i++) { Int32 smallVal1 = (Int32)A1[i]; Int32 smallVal2 = (Int32)A2[i]; Int64 largeVal1 = (Int64)smallVal1; Int64 largeVal2 = (Int64)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int64>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt32And16(Vector<Int32> A1, Vector<Int32> A2) { Vector<Int16> B = Vector.Narrow(A1, A2); Vector<Int32> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int32>.Count; i++) { Int16 smallVal1 = (Int16)A1[i]; Int16 smallVal2 = (Int16)A2[i]; Int32 largeVal1 = (Int32)smallVal1; Int32 largeVal2 = (Int32)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int32>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt16And8(Vector<Int16> A1, Vector<Int16> A2) { Vector<SByte> B = Vector.Narrow(A1, A2); Vector<Int16> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int16>.Count; i++) { SByte smallVal1 = (SByte)A1[i]; SByte smallVal2 = (SByte)A2[i]; Int16 largeVal1 = (Int16)smallVal1; Int16 largeVal2 = (Int16)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int16>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt64And32(Vector<UInt64> A1, Vector<UInt64> A2) { Vector<UInt32> B = Vector.Narrow(A1, A2); Vector<UInt64> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt64>.Count; i++) { UInt32 smallVal1 = (UInt32)A1[i]; UInt32 smallVal2 = (UInt32)A2[i]; UInt64 largeVal1 = (UInt64)smallVal1; UInt64 largeVal2 = (UInt64)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt64>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt32And16(Vector<UInt32> A1, Vector<UInt32> A2) { Vector<UInt16> B = Vector.Narrow(A1, A2); Vector<UInt32> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt32>.Count; i++) { UInt16 smallVal1 = (UInt16)A1[i]; UInt16 smallVal2 = (UInt16)A2[i]; UInt32 largeVal1 = (UInt32)smallVal1; UInt32 largeVal2 = (UInt32)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt32>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt16And8(Vector<UInt16> A1, Vector<UInt16> A2) { Vector<Byte> B = Vector.Narrow(A1, A2); Vector<UInt16> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt16>.Count; i++) { Byte smallVal1 = (Byte)A1[i]; Byte smallVal2 = (Byte)A2[i]; UInt16 largeVal1 = (UInt16)smallVal1; UInt16 largeVal2 = (UInt16)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt16>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } } static int Main() { int returnVal = Pass; for (int i = 0; i < 10; i++) { Vector<Single> singleVector = getRandomVector<Single>(singles, i); if (VectorConvertTest.VectorConvertSingleInt(singleVector) != Pass) { Console.WriteLine("Testing Converts Between Single and Int32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Single> singleVector = getRandomVector<Single>(singles, i); if (VectorConvertTest.VectorConvertSingleUInt(singleVector) != Pass) { Console.WriteLine("Testing Converts Between Single and UInt32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector = getRandomVector<Double>(doubles, i); if (VectorConvertTest.VectorConvertDoubleInt64(doubleVector) != Pass) { Console.WriteLine("Testing Converts between Double and Int64 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector = getRandomVector<Double>(doubles, i); if (VectorConvertTest.VectorConvertDoubleUInt64(doubleVector) != Pass) { Console.WriteLine("Testing Converts between Double and UInt64 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector1 = getRandomVector<Double>(doubles, i); Vector<Double> doubleVector2 = getRandomVector<Double>(doubles, i); if (VectorConvertTest.VectorConvertDoubleSingle(doubleVector1, doubleVector2) != Pass) { Console.WriteLine("Testing Converts between Single and Double failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int64> int64Vector1 = getRandomVector<Int64>(int64s, i); Vector<Int64> int64Vector2 = getRandomVector<Int64>(int64s, i); if (VectorConvertTest.VectorConvertInt64And32(int64Vector1, int64Vector2) != Pass) { Console.WriteLine("Testing Converts between Int64 and Int32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int32> int32Vector1 = getRandomVector<Int32>(int32s, i); Vector<Int32> int32Vector2 = getRandomVector<Int32>(int32s, i); if (VectorConvertTest.VectorConvertInt32And16(int32Vector1, int32Vector2) != Pass) { Console.WriteLine("Testing Converts between Int32 and Int16 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int16> int16Vector1 = getRandomVector<Int16>(int16s, i); Vector<Int16> int16Vector2 = getRandomVector<Int16>(int16s, i); if (VectorConvertTest.VectorConvertInt16And8(int16Vector1, int16Vector2) != Pass) { Console.WriteLine("Testing Converts between Int16 and SByte failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt64> uint64Vector1 = getRandomVector<UInt64>(uint64s, i); Vector<UInt64> uint64Vector2 = getRandomVector<UInt64>(uint64s, i); if (VectorConvertTest.VectorConvertUInt64And32(uint64Vector1, uint64Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt64 and UInt32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt32> uint32Vector1 = getRandomVector<UInt32>(uint32s, i); Vector<UInt32> uint32Vector2 = getRandomVector<UInt32>(uint32s, i); if (VectorConvertTest.VectorConvertUInt32And16(uint32Vector1, uint32Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt32 and UInt16 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt16> uint16Vector1 = getRandomVector<UInt16>(uint16s, i); Vector<UInt16> uint16Vector2 = getRandomVector<UInt16>(uint16s, i); if (VectorConvertTest.VectorConvertUInt16And8(uint16Vector1, uint16Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt16 and Byte failed"); returnVal = Fail; } } JitLog jitLog = new JitLog(); // SIMD conversions from floating point to unsigned are not supported on x86 or x64 if (!jitLog.Check("System.Numerics.Vector:ConvertToInt32(struct):struct")) returnVal = Fail; if (!jitLog.Check("System.Numerics.Vector:ConvertToSingle(struct):struct")) returnVal = Fail; // SIMD Conversion to Int64 is not supported on x86 #if !BIT32 if (!jitLog.Check("System.Numerics.Vector:ConvertToInt64(struct):struct")) returnVal = Fail; #endif // !BIT32 if (!jitLog.Check("System.Numerics.Vector:ConvertToDouble(struct):struct")) returnVal = Fail; if (!jitLog.Check("System.Numerics.Vector:Narrow(struct,struct):struct")) returnVal = Fail; if (!jitLog.Check("System.Numerics.Vector:Widen(struct,byref,byref)")) returnVal = Fail; jitLog.Dispose(); return returnVal; } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:42 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.ux.statusbar { #region StatusBar /// <inheritdocs /> /// <summary> /// <p>Basic status bar component that can be used as the bottom toolbar of any <see cref="Ext.panel.Panel">Ext.Panel</see>. In addition to /// supporting the standard <see cref="Ext.toolbar.Toolbar">Ext.toolbar.Toolbar</see> interface for adding buttons, menus and other items, the StatusBar /// provides a greedy status element that can be aligned to either side and has convenient methods for setting the /// status text and icon. You can also indicate that something is processing using the <see cref="Ext.ux.statusbar.StatusBar.showBusy">showBusy</see> method.</p> /// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.panel.Panel">Ext.Panel</see>', { /// title: 'StatusBar', /// // etc. /// bbar: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.StatusBar</see>', { /// id: 'my-status', /// // defaults to use when the status is cleared: /// defaultText: 'Default status text', /// defaultIconCls: 'default-icon', /// // values to set initially: /// text: 'Ready', /// iconCls: 'ready-icon', /// // any standard Toolbar items: /// items: [{ /// text: 'A Button' /// }, '-', 'Plain Text'] /// }) /// }); /// // Update the status bar later in code: /// var sb = <see cref="Ext.ExtContext.getCmp">Ext.getCmp</see>('my-status'); /// sb.setStatus({ /// text: 'OK', /// iconCls: 'ok-icon', /// clear: true // auto-clear after a set interval /// }); /// // Set the status bar to show that something is processing: /// sb.showBusy(); /// // processing.... /// sb.clearStatus(); // once completeed /// </code></pre> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class StatusBar : Ext.toolbar.Toolbar { /// <summary> /// The number of milliseconds to wait after setting the status via /// setStatus before automatically clearing the status text and icon. /// Note that this only applies when passing the clear argument to setStatus /// since that is the only way to defer clearing the status. This can /// be overridden by specifying a different wait value in setStatus. /// Calls to clearStatus always clear the status bar immediately and ignore this value. /// Defaults to: <c>5000</c> /// </summary> public JsNumber autoClear; /// <summary> /// The default iconCls applied when calling showBusy. /// It can be overridden at any time by passing the iconCls argument into showBusy. /// Defaults to: <c>&quot;x-status-busy&quot;</c> /// </summary> public JsString busyIconCls; /// <summary> /// The default text applied when calling showBusy. /// It can be overridden at any time by passing the text argument into showBusy. /// Defaults to: <c>&quot;Loading...&quot;</c> /// </summary> public JsString busyText; /// <summary> /// The default iconCls value (see the iconCls docs for additional details about customizing the icon). /// This will be used anytime the status bar is cleared with the useDefaults:true option. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString defaultIconCls; /// <summary> /// The default text value. This will be used anytime the status bar is cleared with the /// useDefaults:true option. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString defaultText; /// <summary> /// The text string to use if no text has been set. If there are no other items in /// the toolbar using an empty string ('') for this value would end up in the toolbar /// height collapsing since the empty string will not maintain the toolbar height. /// Use '' if the toolbar should collapse in height vertically when no text is /// specified and there are no other items in the toolbar. /// Defaults to: <c>&quot;&amp;#160;&quot;</c> /// </summary> public JsString emptyText; /// <summary> /// A CSS class that will be initially set as the status bar icon and is /// expected to provide a background image. /// Example usage: /// <code>// Example CSS rule: /// .x-statusbar .x-status-custom { /// padding-left: 25px; /// background: transparent url(images/custom-icon.gif) no-repeat 3px 2px; /// } /// // Setting a default icon: /// var sb = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultIconCls: 'x-status-custom' /// }); /// // Changing the icon: /// sb.setStatus({ /// text: 'New status', /// iconCls: 'x-status-custom' /// }); /// </code> /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString iconCls; /// <summary> /// The alignment of the status element within the overall StatusBar layout. When the StatusBar is rendered, /// it creates an internal div containing the status text and icon. Any additional Toolbar items added in the /// StatusBar's items config, or added via add or any of the supported add* methods, will be /// rendered, in added order, to the opposite side. The status element is greedy, so it will automatically /// expand to take up all sapce left over by any other items. Example usage: /// <code>// Create a left-aligned status bar containing a button, /// // separator and text item that will be right-aligned (default): /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.panel.Panel">Ext.Panel</see>', { /// title: 'StatusBar', /// // etc. /// bbar: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultText: 'Default status text', /// id: 'status-id', /// items: [{ /// text: 'A Button' /// }, '-', 'Plain Text'] /// }) /// }); /// // By adding the statusAlign config, this will create the /// // exact same toolbar, except the status and toolbar item /// // layout will be reversed from the previous example: /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.panel.Panel">Ext.Panel</see>', { /// title: 'StatusBar', /// // etc. /// bbar: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultText: 'Default status text', /// id: 'status-id', /// statusAlign: 'right', /// items: [{ /// text: 'A Button' /// }, '-', 'Plain Text'] /// }) /// }); /// </code> /// </summary> public JsString statusAlign; /// <summary> /// A string that will be initially set as the status message. This string /// will be set as innerHTML (html tags are accepted) for the toolbar item. /// If not specified, the value set for defaultText will be used. /// </summary> public JsString text; /// <summary> /// Clears the status text and iconCls. Also supports clearing via an optional fade out animation. /// </summary> /// <param name="config"><p>A config object containing any or all of the following properties. If this /// object is not specified the status will be cleared using the defaults below:</p> /// <ul><li><span>anim</span> : <see cref="bool">Boolean</see><div><p>True to clear the status by fading out the status element (defaults /// to false which clears immediately).</p> /// </div></li><li><span>useDefaults</span> : <see cref="bool">Boolean</see><div><p>True to reset the text and icon using <see cref="Ext.ux.statusbar.StatusBarConfig.defaultText">defaultText</see> and /// <see cref="Ext.ux.statusbar.StatusBarConfig.defaultIconCls">defaultIconCls</see> (defaults to false which sets the text to '' and removes any existing icon class).</p> /// </div></li></ul></param> /// <returns> /// <span><see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see></span><div><p>this</p> /// </div> /// </returns> public StatusBar clearStatus(object config=null){return null;} /// <summary> /// Returns the current status text. /// </summary> /// <returns> /// <span><see cref="String">String</see></span><div><p>The status text</p> /// </div> /// </returns> public JsString getText(){return null;} /// <summary> /// Convenience method for setting the status icon directly. For more flexible options see setStatus. /// See iconCls for complete details about customizing the icon. /// </summary> /// <param name="iconCls"><p>The icon class to set (defaults to '', and any current icon class is removed)</p> /// </param> /// <returns> /// <span><see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see></span><div><p>this</p> /// </div> /// </returns> public StatusBar setIcon(object iconCls=null){return null;} /// <summary> /// Sets the status text and/or iconCls. Also supports automatically clearing the /// status that was set after a specified interval. /// Example usage: /// <code>// Simple call to update the text /// statusBar.setStatus('New status'); /// // Set the status and icon, auto-clearing with default options: /// statusBar.setStatus({ /// text: 'New status', /// iconCls: 'x-status-custom', /// clear: true /// }); /// // Auto-clear with custom options: /// statusBar.setStatus({ /// text: 'New status', /// iconCls: 'x-status-custom', /// clear: { /// wait: 8000, /// anim: false, /// useDefaults: false /// } /// }); /// </code> /// </summary> /// <param name="config"><p>A config object specifying what status to set, or a string assumed /// to be the status text (and all other options are defaulted as explained below). A config /// object containing any or all of the following properties can be passed:</p> /// <ul><li><span>text</span> : <see cref="String">String</see><div><p>The status text to display. If not specified, any current /// status text will remain unchanged.</p> /// </div></li><li><span>iconCls</span> : <see cref="String">String</see><div><p>The CSS class used to customize the status icon (see /// <see cref="Ext.ux.statusbar.StatusBarConfig.iconCls">iconCls</see> for details). If not specified, any current iconCls will remain unchanged.</p> /// </div></li><li><span>clear</span> : <see cref="bool">Boolean</see>/<see cref="Number">Number</see>/<see cref="Object">Object</see><div><p>Allows you to set an internal callback that will /// automatically clear the status text and iconCls after a specified amount of time has passed. If clear is not /// specified, the new status will not be auto-cleared and will stay until updated again or cleared using /// <see cref="Ext.ux.statusbar.StatusBar.clearStatus">clearStatus</see>. If <c>true</c> is passed, the status will be cleared using <see cref="Ext.ux.statusbar.StatusBarConfig.autoClear">autoClear</see>, /// <see cref="Ext.ux.statusbar.StatusBarConfig.defaultText">defaultText</see> and <see cref="Ext.ux.statusbar.StatusBarConfig.defaultIconCls">defaultIconCls</see> via a fade out animation. If a numeric value is passed, /// it will be used as the callback interval (in milliseconds), overriding the <see cref="Ext.ux.statusbar.StatusBarConfig.autoClear">autoClear</see> value. /// All other options will be defaulted as with the boolean option. To customize any other options, /// you can pass an object in the format:</p> /// <ul><li><span>wait</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to wait before clearing /// (defaults to <see cref="Ext.ux.statusbar.StatusBarConfig.autoClear">autoClear</see>).</p> /// </div></li><li><span>anim</span> : <see cref="bool">Boolean</see><div><p>False to clear the status immediately once the callback /// executes (defaults to true which fades the status out).</p> /// </div></li><li><span>useDefaults</span> : <see cref="bool">Boolean</see><div><p>False to completely clear the status text and iconCls /// (defaults to true which uses <see cref="Ext.ux.statusbar.StatusBarConfig.defaultText">defaultText</see> and <see cref="Ext.ux.statusbar.StatusBarConfig.defaultIconCls">defaultIconCls</see>).</p> /// </div></li></ul></div></li></ul></param> /// <returns> /// <span><see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see></span><div><p>this</p> /// </div> /// </returns> public StatusBar setStatus(object config=null){return null;} /// <summary> /// Convenience method for setting the status text directly. For more flexible options see setStatus. /// </summary> /// <param name="text"><p>The text to set (defaults to '')</p> /// </param> /// <returns> /// <span><see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see></span><div><p>this</p> /// </div> /// </returns> public StatusBar setText(object text=null){return null;} /// <summary> /// Convenience method for setting the status text and icon to special values that are pre-configured to indicate /// a "busy" state, usually for loading or processing activities. /// </summary> /// <param name="config"><p>A config object in the same format supported by <see cref="Ext.ux.statusbar.StatusBar.setStatus">setStatus</see>, or a /// string to use as the status text (in which case all other options for setStatus will be defaulted). Use the /// <c>text</c> and/or <c>iconCls</c> properties on the config to override the default <see cref="Ext.ux.statusbar.StatusBarConfig.busyText">busyText</see> /// and <see cref="Ext.ux.statusbar.StatusBarConfig.busyIconCls">busyIconCls</see> settings. If the config argument is not specified, <see cref="Ext.ux.statusbar.StatusBarConfig.busyText">busyText</see> and /// <see cref="Ext.ux.statusbar.StatusBarConfig.busyIconCls">busyIconCls</see> will be used in conjunction with all of the default options for <see cref="Ext.ux.statusbar.StatusBar.setStatus">setStatus</see>.</p> /// </param> /// <returns> /// <span><see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see></span><div><p>this</p> /// </div> /// </returns> public StatusBar showBusy(object config=null){return null;} public StatusBar(StatusBarConfig config){} public StatusBar(){} public StatusBar(params object[] args){} } #endregion #region StatusBarConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class StatusBarConfig : Ext.toolbar.ToolbarConfig { /// <summary> /// The number of milliseconds to wait after setting the status via /// setStatus before automatically clearing the status text and icon. /// Note that this only applies when passing the clear argument to setStatus /// since that is the only way to defer clearing the status. This can /// be overridden by specifying a different wait value in setStatus. /// Calls to clearStatus always clear the status bar immediately and ignore this value. /// Defaults to: <c>5000</c> /// </summary> public JsNumber autoClear; /// <summary> /// The default iconCls applied when calling showBusy. /// It can be overridden at any time by passing the iconCls argument into showBusy. /// Defaults to: <c>&quot;x-status-busy&quot;</c> /// </summary> public JsString busyIconCls; /// <summary> /// The default text applied when calling showBusy. /// It can be overridden at any time by passing the text argument into showBusy. /// Defaults to: <c>&quot;Loading...&quot;</c> /// </summary> public JsString busyText; /// <summary> /// The default iconCls value (see the iconCls docs for additional details about customizing the icon). /// This will be used anytime the status bar is cleared with the useDefaults:true option. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString defaultIconCls; /// <summary> /// The default text value. This will be used anytime the status bar is cleared with the /// useDefaults:true option. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString defaultText; /// <summary> /// The text string to use if no text has been set. If there are no other items in /// the toolbar using an empty string ('') for this value would end up in the toolbar /// height collapsing since the empty string will not maintain the toolbar height. /// Use '' if the toolbar should collapse in height vertically when no text is /// specified and there are no other items in the toolbar. /// Defaults to: <c>&quot;&amp;#160;&quot;</c> /// </summary> public JsString emptyText; /// <summary> /// A CSS class that will be initially set as the status bar icon and is /// expected to provide a background image. /// Example usage: /// <code>// Example CSS rule: /// .x-statusbar .x-status-custom { /// padding-left: 25px; /// background: transparent url(images/custom-icon.gif) no-repeat 3px 2px; /// } /// // Setting a default icon: /// var sb = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultIconCls: 'x-status-custom' /// }); /// // Changing the icon: /// sb.setStatus({ /// text: 'New status', /// iconCls: 'x-status-custom' /// }); /// </code> /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString iconCls; /// <summary> /// The alignment of the status element within the overall StatusBar layout. When the StatusBar is rendered, /// it creates an internal div containing the status text and icon. Any additional Toolbar items added in the /// StatusBar's items config, or added via add or any of the supported add* methods, will be /// rendered, in added order, to the opposite side. The status element is greedy, so it will automatically /// expand to take up all sapce left over by any other items. Example usage: /// <code>// Create a left-aligned status bar containing a button, /// // separator and text item that will be right-aligned (default): /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.panel.Panel">Ext.Panel</see>', { /// title: 'StatusBar', /// // etc. /// bbar: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultText: 'Default status text', /// id: 'status-id', /// items: [{ /// text: 'A Button' /// }, '-', 'Plain Text'] /// }) /// }); /// // By adding the statusAlign config, this will create the /// // exact same toolbar, except the status and toolbar item /// // layout will be reversed from the previous example: /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.panel.Panel">Ext.Panel</see>', { /// title: 'StatusBar', /// // etc. /// bbar: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.ux.statusbar.StatusBar">Ext.ux.statusbar.StatusBar</see>', { /// defaultText: 'Default status text', /// id: 'status-id', /// statusAlign: 'right', /// items: [{ /// text: 'A Button' /// }, '-', 'Plain Text'] /// }) /// }); /// </code> /// </summary> public JsString statusAlign; /// <summary> /// A string that will be initially set as the status message. This string /// will be set as innerHTML (html tags are accepted) for the toolbar item. /// If not specified, the value set for defaultText will be used. /// </summary> public JsString text; public StatusBarConfig(params object[] args){} } #endregion #region StatusBarEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class StatusBarEvents : Ext.toolbar.ToolbarEvents { public StatusBarEvents(params object[] args){} } #endregion }
using System; using Loon.Utils; using System.Collections.Generic; namespace Loon.Core.Geom { public class Polygon : Shape { private const long serialVersionUID = 1L; public class Polygon2i { public int npoints; public int[] xpoints; public int[] ypoints; private const int MIN_LENGTH = 4; public Polygon2i() { xpoints = new int[MIN_LENGTH]; ypoints = new int[MIN_LENGTH]; } public Polygon2i(int[] xpoints_0, int[] ypoints_1, int npoints_2) { if (npoints_2 > xpoints_0.Length || npoints_2 > ypoints_1.Length) { throw new IndexOutOfRangeException("npoints > xpoints.length || " + "npoints > ypoints.length".ToString()); } if (npoints_2 < 0) { throw new IndexOutOfRangeException("npoints < 0"); } this.npoints = npoints_2; this.xpoints = CollectionUtils.CopyOf(xpoints_0, npoints_2); this.ypoints = CollectionUtils.CopyOf(ypoints_1, npoints_2); } public static int HighestOneBit(int i) { i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - ((int)((uint)i >> 1)); } public void AddPoint(int x, int y) { if (npoints >= xpoints.Length || npoints >= ypoints.Length) { int newLength = (npoints * 2); if (newLength < MIN_LENGTH) { newLength = MIN_LENGTH; } else if ((newLength & (newLength - 1)) != 0) { newLength = HighestOneBit(newLength); } xpoints = CollectionUtils.CopyOf(xpoints, newLength); ypoints = CollectionUtils.CopyOf(ypoints, newLength); } xpoints[npoints] = x; ypoints[npoints] = y; npoints++; } public int[] GetVertices() { int vertice_size = xpoints.Length * 2; int[] verts = new int[vertice_size]; for (int i = 0, j = 0; i < vertice_size; i += 2, j++) { verts[i] = xpoints[j]; verts[i + 1] = ypoints[j]; } return verts; } public void Reset() { npoints = 0; xpoints = new int[MIN_LENGTH]; ypoints = new int[MIN_LENGTH]; } } private bool allowDups; private bool closed; public Polygon(float[] points) { this.allowDups = false; this.closed = true; int length = points.Length; this.points = new float[length]; maxX = -System.Single.MinValue; maxY = -System.Single.MinValue; minX = System.Single.MaxValue; minY = System.Single.MaxValue; x = System.Single.MaxValue; y = System.Single.MaxValue; for (int i = 0; i < length; i++) { this.points[i] = points[i]; if (i % 2 == 0) { if (points[i] > maxX) { maxX = points[i]; } if (points[i] < minX) { minX = points[i]; } if (points[i] < x) { x = points[i]; } } else { if (points[i] > maxY) { maxY = points[i]; } if (points[i] < minY) { minY = points[i]; } if (points[i] < y) { y = points[i]; } } } FindCenter(); CalculateRadius(); pointsDirty = true; } public Polygon() { this.allowDups = false; this.closed = true; points = new float[0]; maxX = -System.Single.MinValue; maxY = -System.Single.MinValue; minX = System.Single.MaxValue; minY = System.Single.MaxValue; } public Polygon(float[] xpoints_0, float[] ypoints_1, int npoints_2) { this.allowDups = false; this.closed = true; if (npoints_2 > xpoints_0.Length || npoints_2 > ypoints_1.Length) { throw new IndexOutOfRangeException("npoints > xpoints.length || " + "npoints > ypoints.length".ToString()); } if (npoints_2 < 0) { throw new IndexOutOfRangeException("npoints < 0"); } points = new float[0]; maxX = -System.Single.MinValue; maxY = -System.Single.MinValue; minX = System.Single.MaxValue; minY = System.Single.MaxValue; for (int i = 0; i < npoints_2; i++) { AddPoint(xpoints_0[i], ypoints_1[i]); } } public Polygon(int[] xpoints_0, int[] ypoints_1, int npoints_2) { this.allowDups = false; this.closed = true; if (npoints_2 > xpoints_0.Length || npoints_2 > ypoints_1.Length) { throw new IndexOutOfRangeException("npoints > xpoints.length || " + "npoints > ypoints.length".ToString()); } if (npoints_2 < 0) { throw new IndexOutOfRangeException("npoints < 0"); } points = new float[0]; maxX = -System.Single.MinValue; maxY = -System.Single.MinValue; minX = System.Single.MaxValue; minY = System.Single.MaxValue; for (int i = 0; i < npoints_2; i++) { AddPoint(xpoints_0[i], ypoints_1[i]); } } public void SetAllowDuplicatePoints(bool allowDups_0) { this.allowDups = allowDups_0; } public void AddPoint(float x, float y) { if (HasVertex(x, y) && (!allowDups)) { return; } List<Single> tempPoints = new List<Single>(); for (int i = 0; i < points.Length; i++) { CollectionUtils.Add(tempPoints,points[i]); } CollectionUtils.Add(tempPoints, x); CollectionUtils.Add(tempPoints, y); int length = tempPoints.Count; this.points = new float[length]; for (int i_0 = 0; i_0 < length; i_0++) { points[i_0] = (tempPoints[i_0]); } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } if (x < minX) { minX = x; } if (y < minY) { minY = y; } FindCenter(); CalculateRadius(); pointsDirty = true; } public override Shape Transform(Matrix transform) { CheckPoints(); Polygon resultPolygon = new Polygon(); float[] result = new float[points.Length]; transform.Transform(points, 0, result, 0, points.Length / 2); resultPolygon.points = result; resultPolygon.FindCenter(); resultPolygon.closed = closed; return resultPolygon; } public override void SetX(float x) { base.SetX(x); pointsDirty = false; } public override void SetY(float y) { base.SetY(y); pointsDirty = false; } protected internal override void CreatePoints() { } public override bool Closed() { return closed; } public void SetClosed(bool closed_0) { this.closed = closed_0; } public Polygon Copy() { float[] copyPoints = new float[points.Length]; System.Array.Copy((Array)(points),0,(Array)(copyPoints),0,copyPoints.Length); return new Polygon(copyPoints); } } }
// 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 Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class LoopHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override IHighlighter CreateHighlighter() { return new LoopHighlighter(); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample1_1() { Test( @"class C { void M() { {|Cursor:[|while|]|} (true) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample1_2() { Test( @"class C { void M() { [|while|] (true) { if (x) { {|Cursor:[|break|]|}; } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample1_3() { Test( @"class C { void M() { [|while|] (true) { if (x) { [|break|]; } else { {|Cursor:[|continue|]|}; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_1() { Test( @"class C { void M() { {|Cursor:[|do|]|} { if (x) { [|break|]; } else { [|continue|]; } } [|while|] (true); } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_2() { Test( @"class C { void M() { [|do|] { if (x) { {|Cursor:[|break|]|}; } else { [|continue|]; } } [|while|] (true); } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_3() { Test( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { {|Cursor:[|continue|]|}; } } [|while|] (true); } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_4() { Test( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { [|continue|]; } } {|Cursor:[|while|]|} (true); } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_5() { Test( @"class C { void M() { do { if (x) { break; } else { continue; } } while {|Cursor:(true)|}; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample2_6() { Test( @"class C { void M() { [|do|] { if (x) { [|break|]; } else { [|continue|]; } } [|while|] (true);{|Cursor:|} } }"); } private const string SpecExample3 = @"for (int i = 0; i < 10; i++) { if (x) { break; } else { continue; } }"; [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample3_1() { Test( @"class C { void M() { {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample3_2() { Test( @"class C { void M() { [|for|] (int i = 0; i < 10; i++) { if (x) { {|Cursor:[|break|];|} } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample3_3() { Test( @"class C { void M() { [|for|] (int i = 0; i < 10; i++) { if (x) { [|break|]; } else { {|Cursor:[|continue|];|} } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample4_1() { Test( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (x) { [|break|]; } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample4_2() { Test( @"class C { void M() { [|foreach|] (var a in x) { if (x) { {|Cursor:[|break|];|} } else { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestExample4_3() { Test( @"class C { void M() { [|foreach|] (var a in x) { if (x) { [|break|]; } else { {|Cursor:[|continue|];|} } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_1() { Test( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (a) { [|break|]; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_2() { Test( @"class C { void M() { [|foreach|] (var a in x) { if (a) { {|Cursor:[|break|];|} } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_3() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { {|Cursor:[|do|]|} { [|break|]; } [|while|] (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_4() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { {|Cursor:[|break|];|} } [|while|] (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_5() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { [|break|]; } {|Cursor:[|while|]|} (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_6() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { [|do|] { [|break|]; } [|while|] (false);{|Cursor:|} break; } break; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_7() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: {|Cursor:[|while|]|} (true) { do { break; } while (false); [|break|]; } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_8() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: [|while|] (true) { do { break; } while (false); {|Cursor:[|break|];|} } break; } } for (int i = 0; i < 10; i++) { break; } } } } "); } // TestNestedExample1 9-13 are in SwitchStatementHighlighterTests.cs [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_14() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { [|break|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample1_15() { Test( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case 0: while (true) { do { break; } while (false); break; } break; } } [|for|] (int i = 0; i < 10; i++) { {|Cursor:[|break|];|} } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_1() { Test( @"class C { void M() { {|Cursor:[|foreach|]|} (var a in x) { if (a) { [|continue|]; } else { while (true) { do { continue; } while (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_2() { Test( @"class C { void M() { [|foreach|] (var a in x) { if (a) { {|Cursor:[|continue|];|} } else { while (true) { do { continue; } while (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_3() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { {|Cursor:[|do|]|} { [|continue|]; } [|while|] (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_4() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { {|Cursor:[|continue|];|} } [|while|] (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_5() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { [|continue|]; } {|Cursor:[|while|]|} (false); continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_6() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while {|Cursor:(false)|}; continue; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_7() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { [|do|] { [|continue|]; } [|while|] (false);{|Cursor:|} continue; } } for (int i = 0; i < 10; i++) { continue; } } } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_8() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { {|Cursor:[|while|]|} (true) { do { continue; } while (false); [|continue|]; } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_9() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { [|while|] (true) { do { continue; } while (false); {|Cursor:[|continue|];|} } } for (int i = 0; i < 10; i++) { continue; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_10() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while (false); continue; } } {|Cursor:[|for|]|} (int i = 0; i < 10; i++) { [|continue|]; } } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public void TestNestedExample2_11() { Test( @"class C { void M() { foreach (var a in x) { if (a) { continue; } else { while (true) { do { continue; } while (false); continue; } } [|for|] (int i = 0; i < 10; i++) { {|Cursor:[|continue|];|} } } } } "); } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace System.Globalization { internal partial class CultureData { // ICU constants const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name const string ICU_COLLATION_KEYWORD = "@collation="; /// <summary> /// This method uses the sRealName field (which is initialized by the constructor before this is called) to /// initialize the rest of the state of CultureData based on the underlying OS globalization library. /// </summary> private unsafe bool InitCultureData() { Debug.Assert(_sRealName != null); Debug.Assert(!GlobalizationMode.Invariant); string alternateSortName = string.Empty; string realNameBuffer = _sRealName; // Basic validation if (realNameBuffer.Contains('@')) { return false; // don't allow ICU variants to come in directly } // Replace _ (alternate sort) with @collation= for ICU int index = realNameBuffer.IndexOf('_'); if (index > 0) { if (index >= (realNameBuffer.Length - 1) // must have characters after _ || realNameBuffer.Substring(index + 1).Contains('_')) // only one _ allowed { return false; // fail } alternateSortName = realNameBuffer.Substring(index + 1); realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName; } // Get the locale name from ICU if (!GetLocaleName(realNameBuffer, out _sWindowsName)) { return false; // fail } // Replace the ICU collation keyword with an _ index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal); if (index >= 0) { _sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName; } else { _sName = _sWindowsName; } _sRealName = _sName; _iLanguage = this.ILANGUAGE; if (_iLanguage == 0) { _iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED; } _bNeutral = (this.SISO3166CTRYNAME.Length == 0); _sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName; // Remove the sort from sName unless custom culture if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage)) { _sName = _sWindowsName.Substring(0, index); } return true; } internal static bool GetLocaleName(string localeName, out string windowsName) { // Get the locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.Globalization.GetLocaleName(localeName, sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } internal static bool GetDefaultLocaleName(out string windowsName) { // Get the default (system) locale name from ICU StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); if (!Interop.Globalization.GetDefaultLocaleName(sb, sb.Capacity)) { StringBuilderCache.Release(sb); windowsName = null; return false; // fail } // Success - use the locale name returned which may be different than realNameBuffer (casing) windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls return true; } private string GetLocaleInfo(LocaleStringData type) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already"); return GetLocaleInfo(_sWindowsName, type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string GetLocaleInfo(string localeName, LocaleStringData type) { Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null"); switch (type) { case LocaleStringData.NegativeInfinitySymbol: // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) + GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol); } StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); return String.Empty; } return StringBuilderCache.GetStringAndRelease(sb); } private int GetLocaleInfo(LocaleNumberData type) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already"); switch (type) { case LocaleNumberData.CalendarType: // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar return 0; } int value = 0; bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value); if (!result) { // Failed, just use 0 Debug.Fail("[CultureData.GetLocaleInfo(LocaleNumberData)] failed"); } return value; } private int[] GetLocaleInfo(LocaleGroupingData type) { Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already"); int primaryGroupingSize = 0; int secondaryGroupingSize = 0; bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize); if (!result) { Debug.Fail("[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed"); } if (secondaryGroupingSize == 0) { return new int[] { primaryGroupingSize }; } return new int[] { primaryGroupingSize, secondaryGroupingSize }; } private string GetTimeFormatString() { return GetTimeFormatString(false); } private string GetTimeFormatString(bool shortFormat) { Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already"); StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY); bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity); if (!result) { // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); return String.Empty; } return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb)); } private int GetFirstDayOfWeek() { return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek); } private String[] GetTimeFormats() { string format = GetTimeFormatString(false); return new string[] { format }; } private String[] GetShortTimeFormats() { string format = GetTimeFormatString(true); return new string[] { format }; } private static CultureData GetCultureDataFromRegionName(String regionName) { // no support to lookup by region name, other than the hard-coded list in CultureData return null; } private static string GetLanguageDisplayName(string cultureName) { return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } private static string GetRegionDisplayName(string isoCountryCode) { // use the fallback which is to return NativeName return null; } private static CultureInfo GetUserDefaultCulture() { return CultureInfo.GetUserDefaultCulture(); } private static string ConvertIcuTimeFormatString(string icuFormatString) { StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY); bool amPmAdded = false; for (int i = 0; i < icuFormatString.Length; i++) { switch(icuFormatString[i]) { case ':': case '.': case 'H': case 'h': case 'm': case 's': sb.Append(icuFormatString[i]); break; case ' ': case '\u00A0': // Convert nonbreaking spaces into regular spaces sb.Append(' '); break; case 'a': // AM/PM if (!amPmAdded) { amPmAdded = true; sb.Append("tt"); } break; } } return StringBuilderCache.GetStringAndRelease(sb); } private static string LCIDToLocaleName(int culture) { Debug.Assert(!GlobalizationMode.Invariant); return LocaleData.LCIDToLocaleName(culture); } private static int LocaleNameToLCID(string cultureName) { Debug.Assert(!GlobalizationMode.Invariant); int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid); return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid; } private static int GetAnsiCodePage(string cultureName) { int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage); return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage; } private static int GetOemCodePage(string cultureName) { int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage); return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage; } private static int GetMacCodePage(string cultureName) { int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage); return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage; } private static int GetEbcdicCodePage(string cultureName) { int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage); return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage; } private static int GetGeoId(string cultureName) { int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId); return geoId == -1 ? CultureData.Invariant.IGEOID : geoId; } private static int GetDigitSubstitution(string cultureName) { int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution); return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution; } private static string GetThreeLetterWindowsLanguageName(string cultureName) { string langName = LocaleData.GetThreeLetterWindowsLangageName(cultureName); return langName == null ? "ZZZ" /* default lang name */ : langName; } private static CultureInfo[] EnumCultures(CultureTypes types) { Debug.Assert(!GlobalizationMode.Invariant); if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0) { return Array.Empty<CultureInfo>(); } int bufferLength = Interop.Globalization.GetLocales(null, 0); if (bufferLength <= 0) { return Array.Empty<CultureInfo>(); } Char [] chars = new Char[bufferLength]; bufferLength = Interop.Globalization.GetLocales(chars, bufferLength); if (bufferLength <= 0) { return Array.Empty<CultureInfo>(); } bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0; bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0; List<CultureInfo> list = new List<CultureInfo>(); if (enumNeutrals) { list.Add(CultureInfo.InvariantCulture); } int index = 0; while (index < bufferLength) { int length = (int) chars[index++]; if (index + length <= bufferLength) { CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length)); if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture)) { list.Add(ci); } } index += length; } return list.ToArray(); } private static string GetConsoleFallbackName(string cultureName) { return LocaleData.GetConsoleUICulture(cultureName); } internal bool IsFramework // not applicable on Linux based systems { get { return false; } } internal bool IsWin32Installed // not applicable on Linux based systems { get { return false; } } internal bool IsReplacementCulture // not applicable on Linux based systems { get { return false; } } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; namespace NUnit.Framework.Assertions { [TestFixture] public class ConditionAssertTests { [Test] public void IsTrue() { Assert.IsTrue(true); } [Test] public void IsTrueNullable() { bool? actual = true; Assert.IsTrue(actual); } [Test] public void IsTrueFails() { var expectedMessage = " Expected: True" + Environment.NewLine + " But was: False" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsTrue(false)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [TestCase(false, " But was: False")] [TestCase(null," But was: null")] public void IsTrueFailsForNullable(bool? actual, string expectedButWas) { var expectedMessage = " Expected: True" + Environment.NewLine + expectedButWas + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsTrue(actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsFalse() { Assert.IsFalse(false); } [Test] public void IsFalseNullable() { bool? actual = false; Assert.IsFalse(actual); } [Test] public void IsFalseFails() { var expectedMessage = " Expected: False" + Environment.NewLine + " But was: True" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsFalse(true)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [TestCase(true," But was: True")] [TestCase(null, " But was: null")] public void IsFalseFailsForNullable(bool? actual, string expectedButWas) { var expectedMessage = " Expected: False" + Environment.NewLine + expectedButWas + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsFalse(actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNull() { Assert.IsNull(null); } [Test] public void IsNullFails() { String s1 = "S1"; var expectedMessage = " Expected: null" + Environment.NewLine + " But was: \"S1\"" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNull(s1)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotNull() { String s1 = "S1"; Assert.IsNotNull(s1); } [Test] public void IsNotNullFails() { var expectedMessage = " Expected: not null" + Environment.NewLine + " But was: null" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotNull(null)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNaN() { Assert.IsNaN(double.NaN); } [Test] public void IsNaNFails() { var expectedMessage = " Expected: NaN" + Environment.NewLine + " But was: 10.0d" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNaN(10.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsEmpty() { Assert.IsEmpty( "", "Failed on empty String" ); Assert.IsEmpty( new int[0], "Failed on empty Array" ); Assert.IsEmpty((IEnumerable)new int[0], "Failed on empty IEnumerable"); Assert.IsEmpty( new ArrayList(), "Failed on empty ArrayList" ); Assert.IsEmpty( new Hashtable(), "Failed on empty Hashtable" ); } [Test] public void IsEmptyFailsOnString() { var expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: \"Hi!\"" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsEmpty( "Hi!" )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsEmptyFailsOnNullString() { var expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: null" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsEmpty( (string)null )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsEmptyFailsOnNonEmptyArray() { var expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: < 1, 2, 3 >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsEmpty( new int[] { 1, 2, 3 } )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsEmptyFailsOnNonEmptyIEnumerable() { var expectedMessage = " Expected: <empty>" + Environment.NewLine + " But was: < 1, 2, 3 >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsEmpty((IEnumerable)new int[] { 1, 2, 3 })); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotEmpty() { int[] array = new int[] { 1, 2, 3 }; Assert.IsNotEmpty( "Hi!", "Failed on String" ); Assert.IsNotEmpty( array, "Failed on Array" ); Assert.IsNotEmpty( (IEnumerable)array, "Failed on IEnumerable" ); ArrayList list = new ArrayList(array); Hashtable hash = new Hashtable(); hash.Add("array", array); Assert.IsNotEmpty(list, "Failed on ArrayList"); Assert.IsNotEmpty(hash, "Failed on Hashtable"); } [Test] public void IsNotEmptyFailsOnEmptyString() { var expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <string.Empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotEmpty( "" )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotEmptyFailsOnEmptyArray() { var expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotEmpty( new int[0] )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotEmptyFailsOnEmptyIEnumerable() { var expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotEmpty((IEnumerable)new int[0])); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotEmptyFailsOnEmptyArrayList() { var expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotEmpty(new ArrayList())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotEmptyFailsOnEmptyHashTable() { var expectedMessage = " Expected: not <empty>" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.IsNotEmpty(new Hashtable())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using FFmpeg.AutoGen; using osuTK; using osu.Framework.Graphics.Textures; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Logging; using osu.Framework.Platform; using AGffmpeg = FFmpeg.AutoGen.ffmpeg; namespace osu.Framework.Graphics.Video { /// <summary> /// Represents a video decoder that can be used convert video streams and files into textures. /// </summary> public unsafe class VideoDecoder : IDisposable { /// <summary> /// The duration of the video that is being decoded. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded. /// </summary> public double Duration => stream == null ? 0 : duration * timeBaseInSeconds * 1000; /// <summary> /// True if the decoder currently does not decode any more frames, false otherwise. /// </summary> public bool IsRunning => State == DecoderState.Running; /// <summary> /// True if the decoder has faulted after starting to decode. You can try to restart a failed decoder by invoking <see cref="StartDecoding"/> again. /// </summary> public bool IsFaulted => State == DecoderState.Faulted; /// <summary> /// The timestamp of the last frame that was decoded by this video decoder, or 0 if no frames have been decoded. /// </summary> public float LastDecodedFrameTime => lastDecodedFrameTime; /// <summary> /// The frame rate of the video stream this decoder is decoding. /// </summary> public double FrameRate => stream == null ? 0 : stream->avg_frame_rate.GetValue(); /// <summary> /// True if the decoder can seek, false otherwise. Determined by the stream this decoder was created with. /// </summary> public bool CanSeek => videoStream?.CanSeek == true; /// <summary> /// The current state of the decoding process. /// </summary> public DecoderState State { get; private set; } // libav-context-related private AVFormatContext* formatContext; private AVIOContext* ioContext; private AVStream* stream; private AVCodecParameters codecParams; private avio_alloc_context_read_packet readPacketCallback; private avio_alloc_context_seek seekCallback; private bool inputOpened; private bool isDisposed; private Stream videoStream; private double timeBaseInSeconds; private long duration; private SwsContext* convCtx; private bool convert = true; // active decoder state private volatile float lastDecodedFrameTime; private Task decodingTask; private CancellationTokenSource decodingTaskCancellationTokenSource; private double? skipOutputUntilTime; private readonly ConcurrentQueue<DecodedFrame> decodedFrames; private readonly ConcurrentQueue<Action> decoderCommands; private readonly ConcurrentQueue<Texture> availableTextures; private ObjectHandle<VideoDecoder> handle; private readonly FFmpegFuncs ffmpeg; internal bool Looping; /// <summary> /// Creates a new video decoder that decodes the given video file. /// </summary> /// <param name="filename">The path to the file that should be decoded.</param> public VideoDecoder(string filename) : this(File.OpenRead(filename)) { } /// <summary> /// Creates a new video decoder that decodes the given video stream. /// </summary> /// <param name="videoStream">The stream that should be decoded.</param> public VideoDecoder(Stream videoStream) { ffmpeg = CreateFuncs(); this.videoStream = videoStream; if (!videoStream.CanRead) throw new InvalidOperationException($"The given stream does not support reading. A stream used for a {nameof(VideoDecoder)} must support reading."); State = DecoderState.Ready; decodedFrames = new ConcurrentQueue<DecodedFrame>(); decoderCommands = new ConcurrentQueue<Action>(); availableTextures = new ConcurrentQueue<Texture>(); // TODO: use "real" object pool when there's some public pool supporting disposables handle = new ObjectHandle<VideoDecoder>(this, GCHandleType.Normal); } /// <summary> /// Seek the decoder to the given timestamp. This will fail if <see cref="CanSeek"/> is false. /// </summary> /// <param name="targetTimestamp">The timestamp to seek to.</param> public void Seek(double targetTimestamp) { if (!CanSeek) throw new InvalidOperationException("This decoder cannot seek because the underlying stream used to decode the video does not support seeking."); decoderCommands.Enqueue(() => { ffmpeg.av_seek_frame(formatContext, stream->index, (long)(targetTimestamp / timeBaseInSeconds / 1000.0), AGffmpeg.AVSEEK_FLAG_BACKWARD); skipOutputUntilTime = targetTimestamp; State = DecoderState.Ready; }); } /// <summary> /// Returns the given frames back to the decoder, allowing the decoder to reuse the textures contained in the frames to draw new frames. /// </summary> /// <param name="frames">The frames that should be returned to the decoder.</param> public void ReturnFrames(IEnumerable<DecodedFrame> frames) { foreach (var f in frames) { ((VideoTexture)f.Texture.TextureGL).FlushUploads(); availableTextures.Enqueue(f.Texture); } } /// <summary> /// Starts the decoding process. The decoding will happen asynchronously in a separate thread. The decoded frames can be retrieved by using <see cref="GetDecodedFrames"/>. /// </summary> public void StartDecoding() { if (decodingTask != null) throw new InvalidOperationException($"Cannot start decoding once already started. Call {nameof(StopDecoding)} first."); // only prepare for decoding if this is our first time starting the decoding process if (formatContext == null) { try { prepareDecoding(); } catch (Exception e) { Logger.Log($"VideoDecoder faulted: {e}"); State = DecoderState.Faulted; return; } } decodingTaskCancellationTokenSource = new CancellationTokenSource(); decodingTask = Task.Factory.StartNew(() => decodingLoop(decodingTaskCancellationTokenSource.Token), decodingTaskCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } /// <summary> /// Stops the decoding process. Optionally waits for the decoder thread to terminate. /// </summary> /// <param name="waitForDecoderExit">True if this method should wait for the decoder thread to terminate, false otherwise.</param> public void StopDecoding(bool waitForDecoderExit) { if (decodingTask == null) return; decodingTaskCancellationTokenSource.Cancel(); if (waitForDecoderExit) { try { decodingTask.Wait(); } catch { // Can throw an TaskCanceledException (inside of an AggregateException) // if the decoding task was enqueued but not running yet. } } decodingTask = null; decodingTaskCancellationTokenSource.Dispose(); decodingTaskCancellationTokenSource = null; State = DecoderState.Ready; } /// <summary> /// Gets all frames that have been decoded by the decoder up until the point in time when this method was called. /// Retrieving decoded frames using this method consumes them, ie calling this method again will never retrieve the same frame twice. /// </summary> /// <returns>The frames that have been decoded up until the point in time this method was called.</returns> public IEnumerable<DecodedFrame> GetDecodedFrames() { var frames = new List<DecodedFrame>(decodedFrames.Count); while (decodedFrames.TryDequeue(out var df)) frames.Add(df); return frames; } // https://en.wikipedia.org/wiki/YCbCr public Matrix3 GetConversionMatrix() { if (stream == null) return Matrix3.Zero; switch (stream->codec->colorspace) { case AVColorSpace.AVCOL_SPC_BT709: return new Matrix3(1.164f, 1.164f, 1.164f, 0.000f, -0.213f, 2.112f, 1.793f, -0.533f, 0.000f); case AVColorSpace.AVCOL_SPC_UNSPECIFIED: case AVColorSpace.AVCOL_SPC_SMPTE170M: case AVColorSpace.AVCOL_SPC_SMPTE240M: default: return new Matrix3(1.164f, 1.164f, 1.164f, 0.000f, -0.392f, 2.017f, 1.596f, -0.813f, 0.000f); } } [MonoPInvokeCallback(typeof(avio_alloc_context_read_packet))] private static int readPacket(void* opaque, byte* bufferPtr, int bufferSize) { var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque); if (!handle.GetTarget(out VideoDecoder decoder)) return 0; var span = new Span<byte>(bufferPtr, bufferSize); return decoder.videoStream.Read(span); } [MonoPInvokeCallback(typeof(avio_alloc_context_seek))] private static long streamSeekCallbacks(void* opaque, long offset, int whence) { var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque); if (!handle.GetTarget(out VideoDecoder decoder)) return -1; if (!decoder.videoStream.CanSeek) throw new InvalidOperationException("Tried seeking on a video sourced by a non-seekable stream."); switch (whence) { case StdIo.SEEK_CUR: decoder.videoStream.Seek(offset, SeekOrigin.Current); break; case StdIo.SEEK_END: decoder.videoStream.Seek(offset, SeekOrigin.End); break; case StdIo.SEEK_SET: decoder.videoStream.Seek(offset, SeekOrigin.Begin); break; case AGffmpeg.AVSEEK_SIZE: return decoder.videoStream.Length; default: return -1; } return decoder.videoStream.Position; } private void prepareFilters() { // only convert if needed if (stream->codec->pix_fmt == AVPixelFormat.AV_PIX_FMT_YUV420P) { convert = false; return; } // 1 = SWS_FAST_BILINEAR // https://www.ffmpeg.org/doxygen/3.1/swscale_8h_source.html#l00056 convCtx = ffmpeg.sws_getContext(stream->codec->width, stream->codec->height, stream->codec->pix_fmt, stream->codec->width, stream->codec->height, AVPixelFormat.AV_PIX_FMT_YUV420P, 1, null, null, null); } // sets up libavformat state: creates the AVFormatContext, the frames, etc. to start decoding, but does not actually start the decodingLoop private void prepareDecoding() { const int context_buffer_size = 4096; // the first call to FFmpeg will throw an exception if the libraries cannot be found // this will be safely handled in StartDecoding() var fcPtr = ffmpeg.avformat_alloc_context(); formatContext = fcPtr; readPacketCallback = readPacket; seekCallback = streamSeekCallbacks; // we shouldn't keep a reference to this buffer as it can be freed and replaced by the native libs themselves. // https://ffmpeg.org/doxygen/4.1/aviobuf_8c.html#a853f5149136a27ffba3207d8520172a5 var contextBuffer = (byte*)ffmpeg.av_malloc(context_buffer_size); ioContext = ffmpeg.avio_alloc_context(contextBuffer, context_buffer_size, 0, (void*)handle.Handle, readPacketCallback, null, seekCallback); formatContext->pb = ioContext; int openInputResult = ffmpeg.avformat_open_input(&fcPtr, "dummy", null, null); inputOpened = openInputResult >= 0; if (!inputOpened) throw new InvalidOperationException($"Error opening file or stream: {getErrorMessage(openInputResult)}"); int findStreamInfoResult = ffmpeg.avformat_find_stream_info(formatContext, null); if (findStreamInfoResult < 0) throw new InvalidOperationException($"Error finding stream info: {getErrorMessage(findStreamInfoResult)}"); var nStreams = formatContext->nb_streams; for (var i = 0; i < nStreams; ++i) { stream = formatContext->streams[i]; codecParams = *stream->codecpar; if (codecParams.codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO) { duration = stream->duration <= 0 ? formatContext->duration : stream->duration; timeBaseInSeconds = stream->time_base.GetValue(); var codecPtr = ffmpeg.avcodec_find_decoder(codecParams.codec_id); if (codecPtr == null) throw new InvalidOperationException($"Couldn't find codec with id: {codecParams.codec_id}"); int openCodecResult = ffmpeg.avcodec_open2(stream->codec, codecPtr, null); if (openCodecResult < 0) throw new InvalidOperationException($"Error trying to open codec with id {codecParams.codec_id}: {getErrorMessage(openCodecResult)}"); break; } } prepareFilters(); } private void decodingLoop(CancellationToken cancellationToken) { var packet = ffmpeg.av_packet_alloc(); const int max_pending_frames = 3; try { while (!cancellationToken.IsCancellationRequested) { switch (State) { case DecoderState.Ready: case DecoderState.Running: if (decodedFrames.Count < max_pending_frames) { decodeNextFrame(packet); } else { // wait until existing buffers are consumed. State = DecoderState.Ready; Thread.Sleep(1); } break; case DecoderState.EndOfStream: // While at the end of the stream, avoid attempting to read further as this comes with a non-negligible overhead. // A Seek() operation will trigger a state change, allowing decoding to potentially start again. Thread.Sleep(50); break; default: Debug.Fail($"Video decoder should never be in a \"{State}\" state during decode."); return; } while (!decoderCommands.IsEmpty) { if (cancellationToken.IsCancellationRequested) return; if (decoderCommands.TryDequeue(out var cmd)) cmd(); } } } catch (Exception e) { Logger.Log($"VideoDecoder faulted: {e}"); State = DecoderState.Faulted; } finally { ffmpeg.av_packet_free(&packet); if (State != DecoderState.Faulted) State = DecoderState.Stopped; } } private void decodeNextFrame(AVPacket* packet) { int readFrameResult = ffmpeg.av_read_frame(formatContext, packet); if (readFrameResult >= 0) { State = DecoderState.Running; if (packet->stream_index == stream->index) { int sendPacketResult = ffmpeg.avcodec_send_packet(stream->codec, packet); if (sendPacketResult == 0) { AVFrame* frame = ffmpeg.av_frame_alloc(); AVFrame* outFrame = null; var result = ffmpeg.avcodec_receive_frame(stream->codec, frame); if (result == 0) { var frameTime = (frame->best_effort_timestamp - stream->start_time) * timeBaseInSeconds * 1000; if (!skipOutputUntilTime.HasValue || skipOutputUntilTime.Value < frameTime) { skipOutputUntilTime = null; if (convert) { outFrame = ffmpeg.av_frame_alloc(); outFrame->format = (int)AVPixelFormat.AV_PIX_FMT_YUV420P; outFrame->width = stream->codec->width; outFrame->height = stream->codec->height; var ret = ffmpeg.av_frame_get_buffer(outFrame, 32); if (ret < 0) throw new InvalidOperationException($"Error allocating video frame: {getErrorMessage(ret)}"); ffmpeg.sws_scale(convCtx, frame->data, frame->linesize, 0, stream->codec->height, outFrame->data, outFrame->linesize); } else outFrame = frame; if (!availableTextures.TryDequeue(out var tex)) tex = new Texture(new VideoTexture(codecParams.width, codecParams.height)); var upload = new VideoTextureUpload(outFrame, ffmpeg.av_frame_free); tex.SetData(upload); decodedFrames.Enqueue(new DecodedFrame { Time = frameTime, Texture = tex }); } lastDecodedFrameTime = (float)frameTime; } // There are two cases: outFrame could be null in which case the above decode hasn't run, or the outFrame doesn't match the input frame, // in which case it won't be automatically freed by the texture upload. In both cases we need to free the input frame. if (outFrame != frame) ffmpeg.av_frame_free(&frame); } else Logger.Log($"Error {sendPacketResult} sending packet in VideoDecoder"); } ffmpeg.av_packet_unref(packet); } else if (readFrameResult == AGffmpeg.AVERROR_EOF) { if (Looping) { Seek(0); } else { // This marks the video stream as no longer relevant (until a future potential Seek operation). State = DecoderState.EndOfStream; } } else { State = DecoderState.Ready; Thread.Sleep(1); } } private string getErrorMessage(int errorCode) { const ulong buffer_size = 256; byte[] buffer = new byte[buffer_size]; int strErrorCode; fixed (byte* bufPtr = buffer) { strErrorCode = ffmpeg.av_strerror(errorCode, bufPtr, buffer_size); } if (strErrorCode < 0) return $"{errorCode} (av_strerror failed with code {strErrorCode})"; var messageLength = Math.Max(0, Array.IndexOf(buffer, (byte)0)); return Encoding.ASCII.GetString(buffer[..messageLength]); } protected virtual FFmpegFuncs CreateFuncs() { // other frameworks should handle native libraries themselves #if NET5_0 AGffmpeg.GetOrLoadLibrary = name => { int version = AGffmpeg.LibraryVersionMap[name]; string libraryName = null; // "lib" prefix and extensions are resolved by .net core switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: libraryName = $"{name}.{version}"; break; case RuntimeInfo.Platform.Windows: libraryName = $"{name}-{version}"; break; case RuntimeInfo.Platform.Linux: libraryName = name; break; } return NativeLibrary.Load(libraryName, System.Reflection.Assembly.GetEntryAssembly(), DllImportSearchPath.UseDllDirectoryForDependencies | DllImportSearchPath.SafeDirectories); }; #endif return new FFmpegFuncs { av_frame_alloc = AGffmpeg.av_frame_alloc, av_frame_free = AGffmpeg.av_frame_free, av_frame_unref = AGffmpeg.av_frame_unref, av_frame_get_buffer = AGffmpeg.av_frame_get_buffer, av_strdup = AGffmpeg.av_strdup, av_strerror = AGffmpeg.av_strerror, av_malloc = AGffmpeg.av_malloc, av_freep = AGffmpeg.av_freep, av_packet_alloc = AGffmpeg.av_packet_alloc, av_packet_unref = AGffmpeg.av_packet_unref, av_packet_free = AGffmpeg.av_packet_free, av_read_frame = AGffmpeg.av_read_frame, av_seek_frame = AGffmpeg.av_seek_frame, avcodec_find_decoder = AGffmpeg.avcodec_find_decoder, avcodec_open2 = AGffmpeg.avcodec_open2, avcodec_receive_frame = AGffmpeg.avcodec_receive_frame, avcodec_send_packet = AGffmpeg.avcodec_send_packet, avformat_alloc_context = AGffmpeg.avformat_alloc_context, avformat_close_input = AGffmpeg.avformat_close_input, avformat_find_stream_info = AGffmpeg.avformat_find_stream_info, avformat_open_input = AGffmpeg.avformat_open_input, avio_alloc_context = AGffmpeg.avio_alloc_context, avio_context_free = AGffmpeg.avio_context_free, sws_freeContext = AGffmpeg.sws_freeContext, sws_getContext = AGffmpeg.sws_getContext, sws_scale = AGffmpeg.sws_scale }; } #region Disposal ~VideoDecoder() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; decoderCommands.Clear(); StopDecoding(true); if (formatContext != null && inputOpened) { fixed (AVFormatContext** ptr = &formatContext) ffmpeg.avformat_close_input(ptr); } if (ioContext != null) { // free the context's buffer as `avio_context_free` doesn't do that by itself. ffmpeg.av_freep(&ioContext->buffer); fixed (AVIOContext** ptr = &ioContext) ffmpeg.avio_context_free(ptr); } seekCallback = null; readPacketCallback = null; videoStream.Dispose(); videoStream = null; if (convCtx != null) ffmpeg.sws_freeContext(convCtx); while (decodedFrames.TryDequeue(out var f)) f.Texture.Dispose(); while (availableTextures.TryDequeue(out var t)) t.Dispose(); handle.Dispose(); } #endregion /// <summary> /// Represents the possible states the decoder can be in. /// </summary> public enum DecoderState { /// <summary> /// The decoder is ready to begin decoding. This is the default state before the decoder starts operations. /// </summary> Ready = 0, /// <summary> /// The decoder is currently running and decoding frames. /// </summary> Running = 1, /// <summary> /// The decoder has faulted with an exception. /// </summary> Faulted = 2, /// <summary> /// The decoder has reached the end of the video data. /// </summary> EndOfStream = 3, /// <summary> /// The decoder has been completely stopped and cannot be resumed. /// </summary> Stopped = 4, } } }
namespace MusicCenter.Dal.Migrations { using System; using System.Data.Entity.Migrations; public partial class init : DbMigration { public override void Up() { CreateTable( "dbo.Album", c => new { Id = c.Int(nullable: false, identity: true), name = c.String(nullable: false), releaseDate = c.DateTime(nullable: false), duration = c.String(), label = c.String(), producer = c.String(), BandID = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Band", t => t.BandID) .Index(t => t.BandID); CreateTable( "dbo.Band", c => new { Id = c.Int(nullable: false, identity: true), email = c.String(nullable: false), name = c.String(nullable: false), description = c.String(), phoneNumber = c.String(), addDate = c.DateTime(nullable: false), bandCreationDate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), bandResolveDate = c.DateTime(precision: 7, storeType: "datetime2"), UserID = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserID) .Index(t => t.UserID); CreateTable( "dbo.Favourites", c => new { Id = c.Int(nullable: false), user_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Id) .ForeignKey("dbo.Users", t => t.user_Id) .Index(t => t.Id) .Index(t => t.user_Id); CreateTable( "dbo.Concert", c => new { Id = c.Int(nullable: false, identity: true), date = c.DateTime(nullable: false), address = c.String(nullable: false), description = c.String(), Latitude = c.String(), Longitude = c.String(), TourID = c.Int(), BandID = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Band", t => t.BandID) .ForeignKey("dbo.Tour", t => t.TourID) .Index(t => t.TourID) .Index(t => t.BandID); CreateTable( "dbo.Files", c => new { Id = c.Int(nullable: false, identity: true), name = c.String(nullable: false), path = c.String(nullable: false), UserID = c.Int(), BandID = c.Int(), TourID = c.Int(), ConcertID = c.Int(), AlbumID = c.Int(), IsAvatar = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Album", t => t.AlbumID) .ForeignKey("dbo.Band", t => t.BandID) .ForeignKey("dbo.Concert", t => t.ConcertID) .ForeignKey("dbo.Tour", t => t.TourID) .ForeignKey("dbo.Users", t => t.UserID) .Index(t => t.UserID) .Index(t => t.BandID) .Index(t => t.TourID) .Index(t => t.ConcertID) .Index(t => t.AlbumID); CreateTable( "dbo.Tour", c => new { Id = c.Int(nullable: false, identity: true), name = c.String(nullable: false), description = c.String(), BandID = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Band", t => t.BandID) .Index(t => t.BandID); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), password = c.String(), email = c.String(nullable: false), firstName = c.String(), lastName = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Message", c => new { Id = c.Int(nullable: false, identity: true), title = c.String(nullable: false), content = c.String(nullable: false), sentDate = c.DateTime(), isReaded = c.Boolean(nullable: false), UserID = c.Int(), BandID = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Band", t => t.BandID) .ForeignKey("dbo.Users", t => t.UserID) .Index(t => t.UserID) .Index(t => t.BandID); CreateTable( "dbo.Role", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Track", c => new { Id = c.Int(nullable: false, identity: true), name = c.String(nullable: false), duration = c.String(), url = c.String(), releaseDate = c.DateTime(nullable: false), BandID = c.Int(nullable: false), IsSingle = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Band", t => t.BandID) .Index(t => t.BandID); CreateTable( "dbo.Genre", c => new { Id = c.Int(nullable: false, identity: true), name = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.BandMember", c => new { Id = c.Int(nullable: false, identity: true), fullName = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AlbumFavourites", c => new { AlbumID = c.Int(nullable: false), FavouritesID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.AlbumID, t.FavouritesID }) .ForeignKey("dbo.Favourites", t => t.AlbumID, cascadeDelete: true) .ForeignKey("dbo.Album", t => t.FavouritesID, cascadeDelete: true) .Index(t => t.AlbumID) .Index(t => t.FavouritesID); CreateTable( "dbo.BandFavourites", c => new { BandID = c.Int(nullable: false), FavouritesID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.BandID, t.FavouritesID }) .ForeignKey("dbo.Favourites", t => t.BandID, cascadeDelete: true) .ForeignKey("dbo.Band", t => t.FavouritesID, cascadeDelete: true) .Index(t => t.BandID) .Index(t => t.FavouritesID); CreateTable( "dbo.BandMemberConcert", c => new { BandID = c.Int(nullable: false), ConcertID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.BandID, t.ConcertID }) .ForeignKey("dbo.Concert", t => t.BandID, cascadeDelete: true) .ForeignKey("dbo.Band", t => t.ConcertID, cascadeDelete: true) .Index(t => t.BandID) .Index(t => t.ConcertID); CreateTable( "dbo.MessageBand", c => new { MessageID = c.Int(nullable: false), BandID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.MessageID, t.BandID }) .ForeignKey("dbo.Message", t => t.MessageID, cascadeDelete: true) .ForeignKey("dbo.Band", t => t.BandID, cascadeDelete: true) .Index(t => t.MessageID) .Index(t => t.BandID); CreateTable( "dbo.MessageUser", c => new { MessageID = c.Int(nullable: false), UserID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.MessageID, t.UserID }) .ForeignKey("dbo.Message", t => t.MessageID, cascadeDelete: true) .ForeignKey("dbo.Users", t => t.UserID, cascadeDelete: true) .Index(t => t.MessageID) .Index(t => t.UserID); CreateTable( "dbo.RoleUser", c => new { RoleID = c.Int(nullable: false), UserID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.RoleID, t.UserID }) .ForeignKey("dbo.Role", t => t.RoleID, cascadeDelete: true) .ForeignKey("dbo.Users", t => t.UserID, cascadeDelete: true) .Index(t => t.RoleID) .Index(t => t.UserID); CreateTable( "dbo.ConcertFavourites", c => new { ConcertID = c.Int(nullable: false), FavouritesID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.ConcertID, t.FavouritesID }) .ForeignKey("dbo.Favourites", t => t.ConcertID, cascadeDelete: true) .ForeignKey("dbo.Concert", t => t.FavouritesID, cascadeDelete: true) .Index(t => t.ConcertID) .Index(t => t.FavouritesID); CreateTable( "dbo.TourFavourites", c => new { TourID = c.Int(nullable: false), FavouritesID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.TourID, t.FavouritesID }) .ForeignKey("dbo.Favourites", t => t.TourID, cascadeDelete: true) .ForeignKey("dbo.Tour", t => t.FavouritesID, cascadeDelete: true) .Index(t => t.TourID) .Index(t => t.FavouritesID); CreateTable( "dbo.AlbumTrack", c => new { AlbumID = c.Int(nullable: false), TrackID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.AlbumID, t.TrackID }) .ForeignKey("dbo.Track", t => t.AlbumID, cascadeDelete: true) .ForeignKey("dbo.Album", t => t.TrackID, cascadeDelete: true) .Index(t => t.AlbumID) .Index(t => t.TrackID); CreateTable( "dbo.AlbumGenre", c => new { AlbumID = c.Int(nullable: false), GenreID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.AlbumID, t.GenreID }) .ForeignKey("dbo.Genre", t => t.AlbumID, cascadeDelete: true) .ForeignKey("dbo.Album", t => t.GenreID, cascadeDelete: true) .Index(t => t.AlbumID) .Index(t => t.GenreID); CreateTable( "dbo.BandGenre", c => new { BandID = c.Int(nullable: false), GenreID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.BandID, t.GenreID }) .ForeignKey("dbo.Genre", t => t.BandID, cascadeDelete: true) .ForeignKey("dbo.Band", t => t.GenreID, cascadeDelete: true) .Index(t => t.BandID) .Index(t => t.GenreID); CreateTable( "dbo.TrackGenre", c => new { TrackID = c.Int(nullable: false), GenreID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.TrackID, t.GenreID }) .ForeignKey("dbo.Genre", t => t.TrackID, cascadeDelete: true) .ForeignKey("dbo.Track", t => t.GenreID, cascadeDelete: true) .Index(t => t.TrackID) .Index(t => t.GenreID); CreateTable( "dbo.TrackFavourites", c => new { TrackID = c.Int(nullable: false), FavouritesID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.TrackID, t.FavouritesID }) .ForeignKey("dbo.Favourites", t => t.TrackID, cascadeDelete: true) .ForeignKey("dbo.Track", t => t.FavouritesID, cascadeDelete: true) .Index(t => t.TrackID) .Index(t => t.FavouritesID); CreateTable( "dbo.BandToBandMember", c => new { BandID = c.Int(nullable: false), MemberID = c.Int(nullable: false), }) .PrimaryKey(t => new { t.BandID, t.MemberID }) .ForeignKey("dbo.Band", t => t.BandID, cascadeDelete: true) .ForeignKey("dbo.BandMember", t => t.MemberID, cascadeDelete: true) .Index(t => t.BandID) .Index(t => t.MemberID); } public override void Down() { DropForeignKey("dbo.Album", "BandID", "dbo.Band"); DropForeignKey("dbo.Band", "UserID", "dbo.Users"); DropForeignKey("dbo.BandToBandMember", "MemberID", "dbo.BandMember"); DropForeignKey("dbo.BandToBandMember", "BandID", "dbo.Band"); DropForeignKey("dbo.Favourites", "user_Id", "dbo.Users"); DropForeignKey("dbo.TrackFavourites", "FavouritesID", "dbo.Track"); DropForeignKey("dbo.TrackFavourites", "TrackID", "dbo.Favourites"); DropForeignKey("dbo.TrackGenre", "GenreID", "dbo.Track"); DropForeignKey("dbo.TrackGenre", "TrackID", "dbo.Genre"); DropForeignKey("dbo.BandGenre", "GenreID", "dbo.Band"); DropForeignKey("dbo.BandGenre", "BandID", "dbo.Genre"); DropForeignKey("dbo.AlbumGenre", "GenreID", "dbo.Album"); DropForeignKey("dbo.AlbumGenre", "AlbumID", "dbo.Genre"); DropForeignKey("dbo.Track", "BandID", "dbo.Band"); DropForeignKey("dbo.AlbumTrack", "TrackID", "dbo.Album"); DropForeignKey("dbo.AlbumTrack", "AlbumID", "dbo.Track"); DropForeignKey("dbo.TourFavourites", "FavouritesID", "dbo.Tour"); DropForeignKey("dbo.TourFavourites", "TourID", "dbo.Favourites"); DropForeignKey("dbo.ConcertFavourites", "FavouritesID", "dbo.Concert"); DropForeignKey("dbo.ConcertFavourites", "ConcertID", "dbo.Favourites"); DropForeignKey("dbo.Concert", "TourID", "dbo.Tour"); DropForeignKey("dbo.Files", "UserID", "dbo.Users"); DropForeignKey("dbo.RoleUser", "UserID", "dbo.Users"); DropForeignKey("dbo.RoleUser", "RoleID", "dbo.Role"); DropForeignKey("dbo.MessageUser", "UserID", "dbo.Users"); DropForeignKey("dbo.MessageUser", "MessageID", "dbo.Message"); DropForeignKey("dbo.Message", "UserID", "dbo.Users"); DropForeignKey("dbo.MessageBand", "BandID", "dbo.Band"); DropForeignKey("dbo.MessageBand", "MessageID", "dbo.Message"); DropForeignKey("dbo.Message", "BandID", "dbo.Band"); DropForeignKey("dbo.Favourites", "Id", "dbo.Users"); DropForeignKey("dbo.Files", "TourID", "dbo.Tour"); DropForeignKey("dbo.Tour", "BandID", "dbo.Band"); DropForeignKey("dbo.Files", "ConcertID", "dbo.Concert"); DropForeignKey("dbo.Files", "BandID", "dbo.Band"); DropForeignKey("dbo.Files", "AlbumID", "dbo.Album"); DropForeignKey("dbo.Concert", "BandID", "dbo.Band"); DropForeignKey("dbo.BandMemberConcert", "ConcertID", "dbo.Band"); DropForeignKey("dbo.BandMemberConcert", "BandID", "dbo.Concert"); DropForeignKey("dbo.BandFavourites", "FavouritesID", "dbo.Band"); DropForeignKey("dbo.BandFavourites", "BandID", "dbo.Favourites"); DropForeignKey("dbo.AlbumFavourites", "FavouritesID", "dbo.Album"); DropForeignKey("dbo.AlbumFavourites", "AlbumID", "dbo.Favourites"); DropIndex("dbo.BandToBandMember", new[] { "MemberID" }); DropIndex("dbo.BandToBandMember", new[] { "BandID" }); DropIndex("dbo.TrackFavourites", new[] { "FavouritesID" }); DropIndex("dbo.TrackFavourites", new[] { "TrackID" }); DropIndex("dbo.TrackGenre", new[] { "GenreID" }); DropIndex("dbo.TrackGenre", new[] { "TrackID" }); DropIndex("dbo.BandGenre", new[] { "GenreID" }); DropIndex("dbo.BandGenre", new[] { "BandID" }); DropIndex("dbo.AlbumGenre", new[] { "GenreID" }); DropIndex("dbo.AlbumGenre", new[] { "AlbumID" }); DropIndex("dbo.AlbumTrack", new[] { "TrackID" }); DropIndex("dbo.AlbumTrack", new[] { "AlbumID" }); DropIndex("dbo.TourFavourites", new[] { "FavouritesID" }); DropIndex("dbo.TourFavourites", new[] { "TourID" }); DropIndex("dbo.ConcertFavourites", new[] { "FavouritesID" }); DropIndex("dbo.ConcertFavourites", new[] { "ConcertID" }); DropIndex("dbo.RoleUser", new[] { "UserID" }); DropIndex("dbo.RoleUser", new[] { "RoleID" }); DropIndex("dbo.MessageUser", new[] { "UserID" }); DropIndex("dbo.MessageUser", new[] { "MessageID" }); DropIndex("dbo.MessageBand", new[] { "BandID" }); DropIndex("dbo.MessageBand", new[] { "MessageID" }); DropIndex("dbo.BandMemberConcert", new[] { "ConcertID" }); DropIndex("dbo.BandMemberConcert", new[] { "BandID" }); DropIndex("dbo.BandFavourites", new[] { "FavouritesID" }); DropIndex("dbo.BandFavourites", new[] { "BandID" }); DropIndex("dbo.AlbumFavourites", new[] { "FavouritesID" }); DropIndex("dbo.AlbumFavourites", new[] { "AlbumID" }); DropIndex("dbo.Track", new[] { "BandID" }); DropIndex("dbo.Message", new[] { "BandID" }); DropIndex("dbo.Message", new[] { "UserID" }); DropIndex("dbo.Tour", new[] { "BandID" }); DropIndex("dbo.Files", new[] { "AlbumID" }); DropIndex("dbo.Files", new[] { "ConcertID" }); DropIndex("dbo.Files", new[] { "TourID" }); DropIndex("dbo.Files", new[] { "BandID" }); DropIndex("dbo.Files", new[] { "UserID" }); DropIndex("dbo.Concert", new[] { "BandID" }); DropIndex("dbo.Concert", new[] { "TourID" }); DropIndex("dbo.Favourites", new[] { "user_Id" }); DropIndex("dbo.Favourites", new[] { "Id" }); DropIndex("dbo.Band", new[] { "UserID" }); DropIndex("dbo.Album", new[] { "BandID" }); DropTable("dbo.BandToBandMember"); DropTable("dbo.TrackFavourites"); DropTable("dbo.TrackGenre"); DropTable("dbo.BandGenre"); DropTable("dbo.AlbumGenre"); DropTable("dbo.AlbumTrack"); DropTable("dbo.TourFavourites"); DropTable("dbo.ConcertFavourites"); DropTable("dbo.RoleUser"); DropTable("dbo.MessageUser"); DropTable("dbo.MessageBand"); DropTable("dbo.BandMemberConcert"); DropTable("dbo.BandFavourites"); DropTable("dbo.AlbumFavourites"); DropTable("dbo.BandMember"); DropTable("dbo.Genre"); DropTable("dbo.Track"); DropTable("dbo.Role"); DropTable("dbo.Message"); DropTable("dbo.Users"); DropTable("dbo.Tour"); DropTable("dbo.Files"); DropTable("dbo.Concert"); DropTable("dbo.Favourites"); DropTable("dbo.Band"); DropTable("dbo.Album"); } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Runtime.InteropServices; namespace Axiom.Graphics { /// <summary> /// This class declares the usage of a single vertex buffer as a component /// of a complete <see cref="VertexDeclaration"/>. /// </summary> public class VertexElement : ICloneable { #region Fields /// <summary> /// The source vertex buffer, as bound to an index using <see cref="VertexBufferBinding"/>. /// </summary> protected ushort source; /// <summary> /// The offset in the buffer that this element starts at. /// </summary> protected int offset; /// <summary> /// The type of element. /// </summary> protected VertexElementType type; /// <summary> /// The meaning of the element. /// </summary> protected VertexElementSemantic semantic; /// <summary> /// Index of the item, only applicable for some elements like texture coords. /// </summary> protected int index; #endregion Fields #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="source">The source vertex buffer, as bound to an index using <see cref="VertexBufferBinding"/>.</param> /// <param name="offset">The offset in the buffer that this element starts at.</param> /// <param name="type">The type of element.</param> /// <param name="semantic">The meaning of the element.</param> public VertexElement(ushort source, int offset, VertexElementType type, VertexElementSemantic semantic) : this(source, offset, type, semantic, 0) {} /// <summary> /// Constructor. /// </summary> /// <param name="source">The source vertex buffer, as bound to an index using <see cref="VertexBufferBinding"/>.</param> /// <param name="offset">The offset in the buffer that this element starts at.</param> /// <param name="type">The type of element.</param> /// <param name="semantic">The meaning of the element.</param> /// <param name="index">Index of the item, only applicable for some elements like texture coords.</param> public VertexElement(ushort source, int offset, VertexElementType type, VertexElementSemantic semantic, int index) { this.source = source; this.offset = offset; this.type = type; this.semantic = semantic; this.index = index; } #endregion #region Methods /// <summary> /// Utility method for helping to calculate offsets. /// </summary> public static int GetTypeSize(VertexElementType type) { switch(type) { case VertexElementType.Color: return Marshal.SizeOf(typeof(int)); case VertexElementType.Float1: return Marshal.SizeOf(typeof(float)); case VertexElementType.Float2: return Marshal.SizeOf(typeof(float)) * 2; case VertexElementType.Float3: return Marshal.SizeOf(typeof(float)) * 3; case VertexElementType.Float4: return Marshal.SizeOf(typeof(float)) * 4; case VertexElementType.Short1: return Marshal.SizeOf(typeof(short)); case VertexElementType.Short2: return Marshal.SizeOf(typeof(short)) * 2; case VertexElementType.Short3: return Marshal.SizeOf(typeof(short)) * 3; case VertexElementType.Short4: return Marshal.SizeOf(typeof(short)) * 4; case VertexElementType.UByte4: return Marshal.SizeOf(typeof(byte)) * 4; } // end switch // keep the compiler happy return 0; } /// <summary> /// Utility method which returns the count of values in a given type. /// </summary> public static int GetTypeCount(VertexElementType type) { switch(type) { case VertexElementType.Color: return 1; case VertexElementType.Float1: return 1; case VertexElementType.Float2: return 2; case VertexElementType.Float3: return 3; case VertexElementType.Float4: return 4; case VertexElementType.Short1: return 1; case VertexElementType.Short2: return 2; case VertexElementType.Short3: return 3; case VertexElementType.Short4: return 4; case VertexElementType.UByte4: return 4; } // end switch // keep the compiler happy return 0; } /// <summary> /// Returns proper enum for a base type multiplied by a value. This is helpful /// when working with tex coords especially since you might not know the number /// of texture dimensions at runtime, and when creating the VertexBuffer you will /// have to get a VertexElementType based on that amount to creating the VertexElement. /// </summary> /// <param name="type">Data type.</param> /// <param name="count">Multiplier.</param> /// <returns> /// A <see cref="VertexElementType"/> that represents the requested type and count. /// </returns> /// <example> /// MultiplyTypeCount(VertexElementType.Float1, 3) returns VertexElementType.Float3. /// </example> public static VertexElementType MultiplyTypeCount(VertexElementType type, int count) { switch(type) { case VertexElementType.Float1: switch(count) { case 1: return VertexElementType.Float1; case 2: return VertexElementType.Float2; case 3: return VertexElementType.Float3; case 4: return VertexElementType.Float4; } break; case VertexElementType.Short1: switch(count) { case 1: return VertexElementType.Short1; case 2: return VertexElementType.Short2; case 3: return VertexElementType.Short3; case 4: return VertexElementType.Short4; } break; } throw new Exception("Cannot multiply base vertex element type: " + type.ToString()); } #endregion #region Properties /// <summary> /// /// </summary> public ushort Source { get { return source; } } /// <summary> /// Gets the offset into the buffer where this element starts. /// </summary> public int Offset { get { return offset; } } /// <summary> /// Gets the data format of this element. /// </summary> public VertexElementType Type { get { return type; } } /// <summary> /// Gets the meaning of this element. /// </summary> public VertexElementSemantic Semantic { get { return semantic; } } /// <summary> /// Gets the index of this element, only applicable for repeating elements (like texcoords). /// </summary> public int Index { get { return index; } } /// <summary> /// Gets the size of this element in bytes. /// </summary> public int Size { get { return GetTypeSize(type); } } #endregion #region ICloneable Members /// <summary> /// Simple memberwise clone since all local fields are value types. /// </summary> /// <returns></returns> public object Clone() { return this.MemberwiseClone(); } #endregion } }
// // Authors: // Alan McGovern alan.mcgovern@gmail.com // Ben Motmans <ben.motmans@gmail.com> // Nicholas Terry <nick.i.terry@gmail.com> // // Copyright (C) 2006 Alan McGovern // Copyright (C) 2007 Ben Motmans // Copyright (C) 2014 Nicholas Terry // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; using System.Net; using Mono.Nat.Upnp; using System.Diagnostics; using System.Net.Sockets; using System.Net.NetworkInformation; namespace Mono.Nat { internal class UpnpSearcher : ISearcher { private const int SearchPeriod = 5 * 60; // The time in seconds between each search static UpnpSearcher instance = new UpnpSearcher(); public static List<UdpClient> sockets = CreateSockets(); public static UpnpSearcher Instance { get { return instance; } } public event EventHandler<DeviceEventArgs> DeviceFound; public event EventHandler<DeviceEventArgs> DeviceLost; private List<INatDevice> devices; private Dictionary<IPAddress, DateTime> lastFetched; private DateTime nextSearch; private IPEndPoint searchEndpoint; UpnpSearcher() { devices = new List<INatDevice>(); lastFetched = new Dictionary<IPAddress, DateTime>(); //searchEndpoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900); searchEndpoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900); } static List<UdpClient> CreateSockets() { List<UdpClient> clients = new List<UdpClient>(); try { foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation address in n.GetIPProperties().UnicastAddresses) { if (address.Address.AddressFamily == AddressFamily.InterNetwork) { try { clients.Add(new UdpClient(new IPEndPoint(address.Address, 0))); } catch { continue; // Move on to the next address. } } } } } catch (Exception) { clients.Add(new UdpClient(0)); } return clients; } public void Search() { foreach (UdpClient s in sockets) { try { Search(s); } catch { // Ignore any search errors } } } void Search(UdpClient client) { nextSearch = DateTime.Now.AddSeconds(SearchPeriod); byte[] data = DiscoverDeviceMessage.EncodeSSDP(); // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2) for (int i = 0; i < 3; i++) client.Send(data, data.Length, searchEndpoint); } public IPEndPoint SearchEndpoint { get { return searchEndpoint; } } public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint) { // Convert it to a string for easy parsing string dataString = null; // No matter what, this method should never throw an exception. If something goes wrong // we should still be in a position to handle the next reply correctly. try { string urn; dataString = Encoding.UTF8.GetString(response); if (NatUtility.Verbose) NatUtility.Log("UPnP Response: {0}", dataString); /* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection. Any other device type is no good to us for this purpose. See the IGP overview paper page 5 for an overview of device types and their hierarchy. http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */ /* TODO: Currently we are assuming version 1 of the protocol. We should figure out which version it is and apply the correct URN. */ /* Some routers don't correctly implement the version ID on the URN, so we only search for the type prefix. */ string log = "UPnP Response: Router advertised a '{0}' service"; StringComparison c = StringComparison.OrdinalIgnoreCase; if (dataString.IndexOf("urn:schemas-upnp-org:service:WANIPConnection:", c) != -1) { urn = "urn:schemas-upnp-org:service:WANIPConnection:1"; NatUtility.Log(log, "urn:schemas-upnp-org:service:WANIPConnection:1"); } else if (dataString.IndexOf("urn:schemas-upnp-org:service:WANPPPConnection:", c) != -1) { urn = "urn:schemas-upnp-org:service:WANPPPConnection:1"; NatUtility.Log(log, "urn:schemas-upnp-org:service:WANPPPConnection:"); } else return; // We have an internet gateway device now UpnpNatDevice d = new UpnpNatDevice(localAddress, dataString, urn); if (devices.Contains(d)) { // We already have found this device, so we just refresh it to let people know it's // Still alive. If a device doesn't respond to a search, we dump it. devices[devices.IndexOf(d)].LastSeen = DateTime.Now; } else { // If we send 3 requests at a time, ensure we only fetch the services list once // even if three responses are received if (lastFetched.ContainsKey(endpoint.Address)) { DateTime last = lastFetched[endpoint.Address]; if ((DateTime.Now - last) < TimeSpan.FromSeconds(20)) return; } lastFetched[endpoint.Address] = DateTime.Now; // Once we've parsed the information we need, we tell the device to retrieve it's service list // Once we successfully receive the service list, the callback provided will be invoked. NatUtility.Log("Fetching service list: {0}", d.HostEndPoint); d.GetServicesList(DeviceSetupComplete); } } catch (Exception ex) { Trace.WriteLine("Unhandled exception when trying to decode a device's response Send me the following data: "); Trace.WriteLine("ErrorMessage:"); Trace.WriteLine(ex.Message); Trace.WriteLine("Data string:"); Trace.WriteLine(dataString); } } public DateTime NextSearch { get { return nextSearch; } } private void DeviceSetupComplete(INatDevice device) { lock (this.devices) { // We don't want the same device in there twice if (devices.Contains(device)) return; devices.Add(device); } OnDeviceFound(new DeviceEventArgs(device)); } private void OnDeviceFound(DeviceEventArgs args) { if (DeviceFound != null) DeviceFound(this, args); } } }
/* Copyright (c) 2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Text.RegularExpressions; using System.CodeDom.Compiler; using System.CodeDom; using PHP.Core; using PHP.Core.AST; using PHP.Core.Parsers; using PHP.Core.Emit; namespace PHP.Core.Reflection { internal enum Characteristic { StaticArgEvaluated, StaticArgReplaced, StaticAutoInclusion, Dynamic } #region InclusionMapping /// <summary> /// Defines an inclusion mapping. /// </summary> [Serializable] public struct InclusionMapping { /// <summary> /// Name identifying the mapping. /// </summary> public string Name { get { return name; } } private string name; /// <summary> /// Replacement. /// </summary> public string Replacement { get { return replacement; } } private string/*!*/ replacement; /// <summary> /// Pattern. /// </summary> public Regex Pattern { get { return pattern; } } private Regex/*!*/ pattern; /// <summary> /// Group name interpreted as the source root of application, <see cref="ApplicationConfiguration.CompilerSection.SourceRoot"/>. /// </summary> private const string SourceRootGroupName = "${SourceRoot}"; /// <summary> /// Creates an inclusion mapping. /// </summary> /// <exception cref="ArgumentException"><paramref name="pattern"/> is not a valid regular expression pattern.</exception> /// <exception cref="ArgumentNullException"><paramref name="pattern"/> or <paramref name="replacement"/> is a <B>null</B> reference.</exception> public InclusionMapping(string/*!*/ pattern, string/*!*/ replacement, string name) { if (pattern == null) throw new ArgumentNullException("pattern"); if (replacement == null) throw new ArgumentNullException("replacement"); this.pattern = new Regex(pattern, RegexOptions.IgnoreCase); this.name = name; this.replacement = replacement; } /// <summary> /// Translates expression (a parameter of include/require) according to the pattern specified in the configuration. /// </summary> /// <param name="expression">The expression to be translated via regexp pattern.</param> /// <param name="mappings">A list of mappings.</param> /// <param name="sourceRoot">The <see cref="ApplicationConfiguration.CompilerSection.SourceRoot"/> used to patch <see cref="InclusionMapping.Replacement"/> string.</param> internal static string TranslateExpression(IEnumerable<InclusionMapping>/*!*/ mappings, string/*!*/ expression, string sourceRoot) { Debug.Assert(mappings != null && expression != null); string trimmed_expression = expression.Trim(); foreach (InclusionMapping mapping in mappings) { // the regex not empty => perform translation: Match m = mapping.Pattern.Match(trimmed_expression); // regex matches: if (m.Success) return m.Result(mapping.Replacement.Replace(SourceRootGroupName, sourceRoot)); } // no regex does match: return null; } } #endregion #region InclusionGraphBuilder internal sealed class InclusionGraphBuilder : IDisposable { public CompilationContext/*!*/ Context { get { return context; } } private readonly CompilationContext/*!*/ context; public Dictionary<PhpSourceFile, CompilationUnit> Nodes { get { return nodes; } } private readonly Dictionary<PhpSourceFile, CompilationUnit> nodes = new Dictionary<PhpSourceFile, CompilationUnit>(); public List<StaticInclusion> PendingInclusions { get { return pendingInclusions; } } private readonly List<StaticInclusion> pendingInclusions = new List<StaticInclusion>(); public InclusionGraphBuilder(CompilationContext/*!*/ context) { this.context = context; Statistics.Inclusions.InitializeGraph(); } #region Graph Building Operations internal void NodeAdded(CompilationUnit/*!*/ compilationUnit) { Statistics.Inclusions.AddNode(compilationUnit); } internal void EdgeAdded(StaticInclusion/*!*/ staticInclusion) { Statistics.Inclusions.AddEdge(staticInclusion); } public void Dispose() { Statistics.Inclusions.BakeGraph(); } #endregion public bool AnalyzeDfsTree(PhpSourceFile/*!*/ rootSourceFile) { CompilationUnit root = GetNode(rootSourceFile); ScriptCompilationUnit rootScript = root as ScriptCompilationUnit; if (rootScript != null && rootScript.State == CompilationUnit.States.Initial) { Analyzer analyzer = null; try { // builds the tree of parsed units via DFS: ProcessNode(rootScript); // finishes pending inclusions via MFP: ProcessPendingInclusions(); analyzer = new Analyzer(context); // pre-analysis: rootScript.PreAnalyzeRecursively(analyzer); // member analysis: rootScript.AnalyzeMembersRecursively(analyzer); if (context.Errors.AnyFatalError) return false; // full analysis: rootScript.AnalyzeRecursively(analyzer); if (context.Errors.AnyFatalError) return false; // perform post analysis: analyzer.PostAnalyze(); if (context.Errors.AnyError) return false; // TODO: // define constructed types: analyzer.DefineConstructedTypeBuilders(); } catch (CompilerException) { root.State = CompilationUnit.States.Erroneous; return false; } if (context.Errors.AnyError) return false; } else if (root.State != CompilationUnit.States.Analyzed && root.State != CompilationUnit.States.Reflected) { return false; } return true; } public void EmitAllUnits(CodeGenerator/*!*/ codeGenerator) { #if DEBUG Console.WriteLine("Generating code ..."); #endif foreach (ScriptCompilationUnit unit in SelectNonReflectedUnits(nodes.Values)) { Debug.WriteLine("IG", "DefineBuilders: " + unit.SourceUnit.SourceFile); unit.DefineBuilders(context); } foreach (ScriptCompilationUnit unit in SelectNonReflectedUnits(nodes.Values)) { Debug.WriteLine("IG", "Emit: " + unit.SourceUnit.SourceFile); unit.Emit(codeGenerator); } foreach (ScriptCompilationUnit unit in SelectNonReflectedUnits(nodes.Values)) { Debug.WriteLine("IG", "Bake: " + unit.SourceUnit.SourceFile); unit.Bake(); } foreach (ScriptCompilationUnit unit in SelectNonReflectedUnits(nodes.Values)) { Debug.WriteLine("IG", "Persist: " + unit.SourceUnit.SourceFile); codeGenerator.Context.Manager.Persist(unit, codeGenerator.Context); } } /// <summary> /// Selects only units that are in other than 'Reflected' state. This prevents us from /// trying to build 'Reflected' units (which is of course impossible) /// </summary> private IEnumerable<ScriptCompilationUnit> SelectNonReflectedUnits(Dictionary<PhpSourceFile, CompilationUnit>.ValueCollection values) { foreach (CompilationUnit unit in values) if (unit.State != CompilationUnit.States.Reflected) yield return (ScriptCompilationUnit)unit; } public void CleanAllUnits(CompilationContext/*!*/ context, bool successful) { foreach (CompilationUnit unit in nodes.Values) unit.CleanUp(context, successful); } /// <summary> /// Gets the node of the graph associated with the specified source file. /// First, look up the table of processed nodes. /// If not there, check compiled units maintained by the manager. /// If it is not found in the manager's cache the source file is locked so that other compilers will /// wait until we finish compilation of the node. The new node is created if the compilation unit doesn't exist for it. /// </summary> internal CompilationUnit GetNode(PhpSourceFile/*!*/ sourceFile) { CompilationUnit result; if (!nodes.TryGetValue(sourceFile, out result)) { ScriptModule module; module = (ScriptModule)context.Manager.LockForCompiling(sourceFile, context); if (module != null) { result = module.CompilationUnit; } else { ScriptCompilationUnit scriptResult = new ScriptCompilationUnit(); scriptResult.SourceUnit = new SourceFileUnit(scriptResult, sourceFile, context.Config.Globalization.PageEncoding); result = scriptResult; } nodes.Add(sourceFile, result); NodeAdded(result); } return result; } private void ProcessNode(ScriptCompilationUnit/*!*/ node) { Debug.Assert(node.State == CompilationUnit.States.Initial); // parses the unit and fills its tables: node.Parse(context); // resolves outgoing edges: node.ResolveInclusions(this); // follow DFS tree edges: foreach (StaticInclusion edge in node.Inclusions) { switch (edge.Includee.State) { case CompilationUnit.States.Initial: Debug.Assert(edge.Includee is ScriptCompilationUnit); // recursive descent: ProcessNode((ScriptCompilationUnit)edge.Includee); // TODO: consider! node.MergeTables(edge); break; case CompilationUnit.States.Parsed: // edge closing a cycle: pendingInclusions.Add(edge); break; case CompilationUnit.States.Processed: // transverse edge to already processed subtree: node.MergeTables(edge); break; case CompilationUnit.States.Compiled: // descent edge to the compiled node: edge.Includee.Reflect(); node.MergeTables(edge); break; case CompilationUnit.States.Analyzed: case CompilationUnit.States.Reflected: // descent or transverse edge to already analyzed or compiled and reflected node: node.MergeTables(edge); break; default: Debug.Fail("Unexpected CU state"); throw null; } } node.State = CompilationUnit.States.Processed; } /// <summary> /// Minimal fixpoint algorithm. /// </summary> private void ProcessPendingInclusions() { while (pendingInclusions.Count > 0) { StaticInclusion inclusion = pendingInclusions[pendingInclusions.Count - 1]; pendingInclusions.RemoveAt(pendingInclusions.Count - 1); Debug.Assert(inclusion.Includer.State == CompilationUnit.States.Processed); Debug.Assert(inclusion.Includee.State == CompilationUnit.States.Processed); if (inclusion.Includer.MergeTables(inclusion) > 0) { foreach (StaticInclusion incoming in inclusion.Includer.Includers) pendingInclusions.Add(incoming); } } } } #endregion #region StaticInclusion public sealed class StaticInclusion { public ScriptCompilationUnit/*!*/ Includer { get { return includer; } } private readonly ScriptCompilationUnit/*!*/ includer; public CompilationUnit/*!*/ Includee { get { return includee; } } private readonly CompilationUnit/*!*/ includee; public Scope Scope { get { return scope; } } private readonly Scope scope; public InclusionTypes InclusionType { get { return inclusionType; } } private readonly InclusionTypes inclusionType; public bool IsConditional { get { return isConditional; } } private bool isConditional; public StaticInclusion(ScriptCompilationUnit/*!*/ includer, CompilationUnit/*!*/ includee, Scope scope, bool isConditional, InclusionTypes inclusionType) { this.scope = scope; this.inclusionType = inclusionType; this.includee = includee; this.includer = includer; this.isConditional = isConditional; } } #endregion }
/* * * DCSoft RTF DOM v1.0 * Author : Yuan yong fu. * Email : yyf9989@hotmail.com * blog site:http://www.cnblogs.com/xdesigner. * */ using System; namespace RtfDomParser { /// <summary> /// Document information /// </summary> [Serializable()] [System.Diagnostics.DebuggerTypeProxy(typeof(RTFInstanceDebugView))] public class RTFDocumentInfo { private System.Collections.Specialized.StringDictionary myInfo = new System.Collections.Specialized.StringDictionary(); /// <summary> /// get information specify name /// </summary> /// <param name="strName">name</param> /// <returns>value</returns> public string GetInfo( string strName ) { return myInfo[ strName ] ; } /// <summary> /// set information specify name /// </summary> /// <param name="strName">name</param> /// <param name="strValue">value</param> public void SetInfo( string strName , string strValue ) { myInfo[ strName ] = strValue ; } /// <summary> /// document title /// </summary> public string Title { get{ return myInfo["title"] ;} set{ myInfo["title"] = value;} } public string Subject { get{ return myInfo["subject"] ;} set{ myInfo["subject"] = value;} } public string Author { get{ return myInfo["author"] ;} set{ myInfo["author"] = value;} } public string Manager { get{ return myInfo["manager"] ;} set{ myInfo["manager"] = value;} } public string Company { get{ return myInfo["company"] ;} set{ myInfo["company"] = value;} } public string Operator { get{ return myInfo["operator"] ;} set{ myInfo["operator"] = value;} } public string Category { get{ return myInfo["category"] ;} set{ myInfo["categroy"] = value;} } public string Keywords { get{ return myInfo["keywords"] ;} set{ myInfo["keywords"] = value;} } public string Comment { get{ return myInfo["comment"] ;} set{ myInfo["comment"] = value;} } public string Doccomm { get{ return myInfo["doccomm"] ;} set{ myInfo["doccomm"] = value;} } public string HLinkbase { get{ return myInfo["hlinkbase"] ;} set{ myInfo["hlinkbase"] = value;} } /// <summary> /// total edit minutes /// </summary> public int edmins { get { if (myInfo.ContainsKey("edmins")) { string v = Convert.ToString(myInfo["edmins"]); int result = 0; if (int.TryParse(v, out result)) { return result; } } return 0; } set { myInfo["edmins"] = value.ToString(); } } /// <summary> /// version /// </summary> public string vern { get { return myInfo["vern"]; } set { myInfo["vern"] = value; } } /// <summary> /// number of pages /// </summary> public string nofpages { get { return myInfo["nofpages"]; } set { myInfo["nofpages"] = value; } } /// <summary> /// number of words /// </summary> public string nofwords { get { return myInfo["nofwords"]; } set { myInfo["nofwords"] = value; } } /// <summary> /// number of characters , include whitespace /// </summary> public string nofchars { get { return myInfo["nofchars"]; } set { myInfo["nofchars"] = value; } } /// <summary> /// number of characters , exclude white space /// </summary> public string nofcharsws { get { return myInfo["nofcharsws"]; } set { myInfo["nofcharsws"] = value; } } /// <summary> /// inner id /// </summary> public string id { get { return myInfo["id"]; } set { myInfo["id"] = value; } } private DateTime dtmCreatim = DateTime.Now ; /// <summary> /// creation time /// </summary> public DateTime Creatim { get{ return dtmCreatim ;} set{ dtmCreatim = value;} } private DateTime dtmRevtim = DateTime.Now ; /// <summary> /// modified time /// </summary> public DateTime Revtim { get{ return dtmRevtim ;} set{ dtmRevtim = value;} } private DateTime dtmPrintim = DateTime.Now ; /// <summary> /// last print time /// </summary> public DateTime Printim { get{ return dtmPrintim ;} set{ dtmPrintim = value;} } private DateTime dtmBuptim = DateTime.Now ; /// <summary> /// back up time /// </summary> public DateTime Buptim { get{ return dtmBuptim ;} set{ dtmBuptim = value;} } internal string[] StringItems { get { System.Collections.ArrayList list = new System.Collections.ArrayList(); foreach (string key in myInfo.Keys) { list.Add(key + "=" + myInfo[key]); } list.Add("Creatim="+this.Creatim.ToString("yyyy-MM-dd HH:mm:ss")); list.Add("Revtim="+ this.Revtim.ToString("yyyy-MM-dd HH:mm:ss")); list.Add("Printim="+ this.Printim.ToString("yyyy-MM-dd HH:mm:ss")); list.Add("Buptim="+ this.Buptim.ToString("yyyy-MM-dd HH:mm:ss")); return ( string[]) list.ToArray(typeof(string)); } } public void Clear() { myInfo.Clear(); dtmCreatim = System.DateTime.Now ; dtmRevtim = DateTime.Now ; dtmPrintim = DateTime.Now ; dtmBuptim = DateTime.Now ; } public void Write(RTFWriter writer) { writer.WriteStartGroup( ); writer.WriteKeyword("info"); foreach( string strKey in myInfo.Keys ) { writer.WriteStartGroup(); if (strKey == "edmins" || strKey == "vern" || strKey == "nofpages" || strKey == "nofwords" || strKey == "nofchars" || strKey == "nofcharsws" || strKey == "id") { writer.WriteKeyword(strKey + myInfo[strKey]); } else { writer.WriteKeyword(strKey); writer.WriteText(myInfo[strKey]); } writer.WriteEndGroup(); } writer.WriteStartGroup(); WriteTime( writer , "creatim" , dtmCreatim ); WriteTime( writer , "revtim" , dtmRevtim ); WriteTime( writer , "printim" , dtmPrintim ); WriteTime( writer , "buptim" , dtmBuptim ); writer.WriteEndGroup(); } private void WriteTime( RTFWriter writer , string name , DateTime Value ) { writer.WriteStartGroup(); writer.WriteKeyword( name ); writer.WriteKeyword( "yr" + Value.Year ); writer.WriteKeyword( "mo" + Value.Month ); writer.WriteKeyword( "dy" + Value.Day ); writer.WriteKeyword( "hr" + Value.Hour ); writer.WriteKeyword( "min" + Value.Minute ); writer.WriteKeyword( "sec" + Value.Second ); writer.WriteEndGroup(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkSecurityGroupsOperations operations. /// </summary> internal partial class NetworkSecurityGroupsOperations : IServiceOperations<NetworkManagementClient>, INetworkSecurityGroupsOperations { /// <summary> /// Initializes a new instance of the NetworkSecurityGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkSecurityGroupsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkSecurityGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<NetworkSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<NetworkSecurityGroup> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all network security groups in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network security groups in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkSecurityGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network security groups in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network security groups in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.DataStructures; using Alachisoft.NCache.Runtime; using Alachisoft.NCache.Caching.Queries; using System.Collections.Generic; using Alachisoft.NCache.Runtime.Caching; using Alachisoft.NCache.Runtime.Events; namespace Alachisoft.NCache.Web.Caching { internal class CacheImplBase { private string _clientID; internal CacheImplBase() { _clientID = System.Guid.NewGuid().ToString() + ":" + Environment.MachineName + ":" + System.Diagnostics.Process.GetCurrentProcess().Id; } protected internal virtual bool SerializationEnabled { get { return true; } } protected internal virtual TypeInfoMap TypeMap { get { return null; } set { } } public virtual long Count { get { return 0; } } public string ClientID { get { return _clientID; } } internal virtual void MakeTargetCacheActivePassive(bool makeActive) { } public virtual string Name { get { return null; } } public virtual void Dispose(bool disposing) { } public virtual void Add(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, Hashtable queryInfo, BitSet flagMap, EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter, long size) { } /// <summary> /// Add array of <see cref="CacheItem"/> to the cache. /// </summary> /// <param name="keys">The cache keys used to reference the items.</param> /// <param name="items">The items that are to be stored</param> /// <returns>keys that are added or that alredy exists in the cache and their status.</returns> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to add items to the cache with a sliding expiration of 5 minutes, a priority of /// high, and that notifies the application when the item is removed from the cache. /// /// First create a CacheItems. /// <code> /// string keys = {"ORD_23", "ORD_67"}; /// CacheItem items = new CacheItem[2] /// items[0] = new CacheItem(new Order()); /// items[0].SlidingExpiration = new TimeSpan(0,5,0); /// items[0].Priority = CacheItemPriority.High; /// items[0].ItemRemoveCallback = onRemove; /// /// items[1] = new CacheItem(new Order()); /// items[1].SlidingExpiration = new TimeSpan(0,5,0); /// items[1].Priority = CacheItemPriority.Low; /// items[1].ItemRemoveCallback = onRemove; /// </code> /// /// Then add CacheItem to the cache /// <code> /// /// NCache.Cache.Add(keys, items); /// /// Cache.Add(keys, items); /// /// </code> /// </example> public virtual IDictionary Add(string[] keys, CacheItem[] items, long[] sizes) { return null; } public virtual void Clear(BitSet flagMap) { } public virtual bool Contains(string key) { return false; } public virtual CompressedValueEntry Get(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { return null; } public virtual IDictionary Get(string[] keys, BitSet flagMap) { return null; } public virtual object GetCacheItem(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { return null; } public virtual void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, short onRemoveCallback, short onUpdateCallback, Hashtable queryInfo, BitSet flagMap, object lockId, LockAccessType accessType, EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter, long size) { } public virtual IDictionary Insert(string[] keys, CacheItem[] items, long[] sizes) { return null; } public virtual CompressedValueEntry Remove(string key, BitSet flagMap, object lockId, LockAccessType accessType) { return null; } public virtual void Delete(string key, BitSet flagMap, object lockId, LockAccessType accessType) { } public virtual bool SetAttributes(string key, CacheItemAttributes attribute) { return false; } public virtual IDictionary Remove(string[] keys, BitSet flagMap) { return null; } public virtual void Delete(string[] keys, BitSet flagMap) { } public virtual QueryResultSet Search(string query, IDictionary values) { return null; } public virtual QueryResultSet SearchEntries(string query, IDictionary values) { return null; } public virtual object SafeSerialize(object serializableObject, string serializationContext, ref BitSet flag, CacheImplBase cacheImpl, ref long size) { return null; } public virtual object SafeDeserialize(object serializedObject, string serializationContext, BitSet flag, CacheImplBase cacheImpl) { return null; } public virtual IEnumerator GetEnumerator() { return null; } public virtual EnumerationDataChunk GetNextChunk(EnumerationPointer pointer) { return null; } public virtual List<EnumerationDataChunk> GetNextChunk(List<EnumerationPointer> pointers) { return null; } public virtual void Unlock(string key) { } public virtual void Unlock(string key, object lockId) { } public virtual bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { lockHandle = null; return false; } internal virtual bool IsLocked(string key, ref LockHandle lockHandle) { return false; } public virtual void RegisterKeyNotificationCallback(string key, short updateCallbackid, short removeCallbackid, bool notifyOnItemExpiration) { } public virtual void UnRegisterKeyNotificationCallback(string key, short updateCallbackid, short removeCallbackid) { } public virtual void RegisterKeyNotificationCallback(string key, short update, short remove, EventDataFilter datafilter, bool notifyOnItemExpiration) { } public virtual void UnRegisterKeyNotificationCallback(string key, short update, short remove, EventType eventType) { } } }
namespace Palaso.UI.WindowsForms.WritingSystems { partial class WSSortControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this._testSortText = new System.Windows.Forms.TextBox(); this._testSortResult = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this._rulesValidationTimer = new System.Windows.Forms.Timer(this.components); this._testSortButton = new System.Windows.Forms.Button(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this._sortUsingComboBox = new System.Windows.Forms.ComboBox(); this.switcher_panel = new System.Windows.Forms.Panel(); this._sortrules_panel = new System.Windows.Forms.Panel(); this._languagecombo_panel = new System.Windows.Forms.TableLayoutPanel(); this.label2 = new System.Windows.Forms.Label(); this._languageComboBox = new System.Windows.Forms.ComboBox(); this._sortRulesTextBox = new System.Windows.Forms.TextBox(); this._helpLabel = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel3.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this.switcher_panel.SuspendLayout(); this._sortrules_panel.SuspendLayout(); this._languagecombo_panel.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel5.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 13); this.label1.TabIndex = 0; this.label1.Text = "&Sort:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(3, 29); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 13); this.label3.TabIndex = 0; this.label3.Text = "Te&xt to Sort:"; // // _testSortText // this._testSortText.AcceptsReturn = true; this._testSortText.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._testSortText.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._testSortText.Location = new System.Drawing.Point(3, 45); this._testSortText.Multiline = true; this._testSortText.Name = "_testSortText"; this._testSortText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._testSortText.Size = new System.Drawing.Size(426, 161); this._testSortText.TabIndex = 1; this._testSortText.Leave += new System.EventHandler(this.TextControl_Leave); this._testSortText.Enter += new System.EventHandler(this.TextControl_Enter); // // _testSortResult // this._testSortResult.BackColor = System.Drawing.SystemColors.Window; this._testSortResult.Dock = System.Windows.Forms.DockStyle.Fill; this._testSortResult.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._testSortResult.Location = new System.Drawing.Point(3, 225); this._testSortResult.Multiline = true; this._testSortResult.Name = "_testSortResult"; this._testSortResult.ReadOnly = true; this._testSortResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._testSortResult.Size = new System.Drawing.Size(426, 161); this._testSortResult.TabIndex = 1; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(3, 209); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(62, 13); this.label4.TabIndex = 0; this.label4.Text = "Sort Result:"; // // _rulesValidationTimer // this._rulesValidationTimer.Interval = 500; this._rulesValidationTimer.Tick += new System.EventHandler(this._rulesValidationTimer_Tick); // // _testSortButton // this._testSortButton.Anchor = System.Windows.Forms.AnchorStyles.Top; this._testSortButton.AutoSize = true; this._testSortButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._testSortButton.Location = new System.Drawing.Point(186, 3); this._testSortButton.Name = "_testSortButton"; this._testSortButton.Size = new System.Drawing.Size(60, 23); this._testSortButton.TabIndex = 0; this._testSortButton.Text = "&Test Sort"; this._testSortButton.UseVisualStyleBackColor = true; this._testSortButton.Click += new System.EventHandler(this._testSortButton_Click); // // tableLayoutPanel3 // this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel3.ColumnCount = 2; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 1, 0); this.tableLayoutPanel3.Controls.Add(this.switcher_panel, 1, 1); this.tableLayoutPanel3.Controls.Add(this._helpLabel, 1, 2); this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 3; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel3.Size = new System.Drawing.Size(187, 389); this.tableLayoutPanel3.TabIndex = 0; // // tableLayoutPanel4 // this.tableLayoutPanel4.AutoSize = true; this.tableLayoutPanel4.ColumnCount = 2; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.Controls.Add(this.label1, 0, 1); this.tableLayoutPanel4.Controls.Add(this._sortUsingComboBox, 1, 1); this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 2; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel4.Size = new System.Drawing.Size(181, 27); this.tableLayoutPanel4.TabIndex = 1; // // _sortUsingComboBox // this._sortUsingComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._sortUsingComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._sortUsingComboBox.FormattingEnabled = true; this._sortUsingComboBox.Location = new System.Drawing.Point(38, 3); this._sortUsingComboBox.Name = "_sortUsingComboBox"; this._sortUsingComboBox.Size = new System.Drawing.Size(140, 21); this._sortUsingComboBox.TabIndex = 2; this._sortUsingComboBox.SelectedIndexChanged += new System.EventHandler(this._sortUsingComboBox_SelectedIndexChanged); // // switcher_panel // this.switcher_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.switcher_panel.Controls.Add(this._sortrules_panel); this.switcher_panel.Dock = System.Windows.Forms.DockStyle.Fill; this.switcher_panel.Location = new System.Drawing.Point(3, 36); this.switcher_panel.Name = "switcher_panel"; this.switcher_panel.Size = new System.Drawing.Size(181, 337); this.switcher_panel.TabIndex = 1; // // _sortrules_panel // this._sortrules_panel.Controls.Add(this._languagecombo_panel); this._sortrules_panel.Controls.Add(this._sortRulesTextBox); this._sortrules_panel.Dock = System.Windows.Forms.DockStyle.Fill; this._sortrules_panel.Location = new System.Drawing.Point(0, 0); this._sortrules_panel.Name = "_sortrules_panel"; this._sortrules_panel.Size = new System.Drawing.Size(181, 337); this._sortrules_panel.TabIndex = 4; // // _languagecombo_panel // this._languagecombo_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._languagecombo_panel.ColumnCount = 1; this._languagecombo_panel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this._languagecombo_panel.Controls.Add(this.label2, 0, 0); this._languagecombo_panel.Controls.Add(this._languageComboBox, 0, 1); this._languagecombo_panel.Dock = System.Windows.Forms.DockStyle.Fill; this._languagecombo_panel.Location = new System.Drawing.Point(0, 0); this._languagecombo_panel.Name = "_languagecombo_panel"; this._languagecombo_panel.RowCount = 2; this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._languagecombo_panel.Size = new System.Drawing.Size(181, 337); this._languagecombo_panel.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(58, 13); this.label2.TabIndex = 0; this.label2.Text = "&Language:"; // // _languageComboBox // this._languageComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this._languageComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._languageComboBox.DropDownWidth = 156; this._languageComboBox.FormattingEnabled = true; this._languageComboBox.Location = new System.Drawing.Point(3, 16); this._languageComboBox.Name = "_languageComboBox"; this._languageComboBox.Size = new System.Drawing.Size(175, 21); this._languageComboBox.TabIndex = 1; this._languageComboBox.SelectedIndexChanged += new System.EventHandler(this._languageComboBox_SelectedIndexChanged); // // _sortRulesTextBox // this._sortRulesTextBox.AcceptsReturn = true; this._sortRulesTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this._sortRulesTextBox.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._sortRulesTextBox.Location = new System.Drawing.Point(0, 0); this._sortRulesTextBox.Multiline = true; this._sortRulesTextBox.Name = "_sortRulesTextBox"; this._sortRulesTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._sortRulesTextBox.Size = new System.Drawing.Size(181, 337); this._sortRulesTextBox.TabIndex = 0; this._sortRulesTextBox.Leave += new System.EventHandler(this._sortRulesTextBox_TextChanged); // // _helpLabel // this._helpLabel.AutoSize = true; this._helpLabel.Location = new System.Drawing.Point(3, 376); this._helpLabel.Name = "_helpLabel"; this._helpLabel.Size = new System.Drawing.Size(29, 13); this._helpLabel.TabIndex = 3; this._helpLabel.TabStop = true; this._helpLabel.Text = "Help"; this._helpLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnHelpLabelClicked); // // tableLayoutPanel2 // this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel2.ColumnCount = 1; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this._testSortResult, 0, 4); this.tableLayoutPanel2.Controls.Add(this.label4, 0, 3); this.tableLayoutPanel2.Controls.Add(this.label3, 0, 1); this.tableLayoutPanel2.Controls.Add(this._testSortText, 0, 2); this.tableLayoutPanel2.Controls.Add(this._testSortButton, 0, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(196, 3); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 5; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(432, 389); this.tableLayoutPanel2.TabIndex = 0; // // tableLayoutPanel5 // this.tableLayoutPanel5.ColumnCount = 2; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel3, 0, 0); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel2, 1, 0); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 1; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Size = new System.Drawing.Size(631, 395); this.tableLayoutPanel5.TabIndex = 3; // // WSSortControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tableLayoutPanel5); this.Name = "WSSortControl"; this.Size = new System.Drawing.Size(631, 395); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); this.switcher_panel.ResumeLayout(false); this._sortrules_panel.ResumeLayout(false); this._sortrules_panel.PerformLayout(); this._languagecombo_panel.ResumeLayout(false); this._languagecombo_panel.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel5.ResumeLayout(false); this.tableLayoutPanel5.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox _testSortText; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox _testSortResult; private System.Windows.Forms.Label label4; private System.Windows.Forms.Timer _rulesValidationTimer; private System.Windows.Forms.Button _testSortButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.Panel switcher_panel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel _languagecombo_panel; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox _languageComboBox; private System.Windows.Forms.TextBox _sortRulesTextBox; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.ComboBox _sortUsingComboBox; private System.Windows.Forms.LinkLabel _helpLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private System.Windows.Forms.Panel _sortrules_panel; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Presentation.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
namespace RestSharp.Authenticators.OAuth { using System; using System.Collections.Generic; using RestSharp.Authenticators.OAuth.Extensions; #if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC using RestSharp.Contrib; #endif /// <summary> /// A class to encapsulate OAuth authentication flow. /// <seealso cref="http://oauth.net/core/1.0#anchor9"/> /// </summary> internal class OAuthWorkflow { public virtual string Version { get; set; } public virtual string ConsumerKey { get; set; } public virtual string ConsumerSecret { get; set; } public virtual string Token { get; set; } public virtual string TokenSecret { get; set; } public virtual string CallbackUrl { get; set; } public virtual string Verifier { get; set; } public virtual string SessionHandle { get; set; } public virtual OAuthSignatureMethod SignatureMethod { get; set; } public virtual OAuthSignatureTreatment SignatureTreatment { get; set; } public virtual OAuthParameterHandling ParameterHandling { get; set; } public virtual string ClientUsername { get; set; } public virtual string ClientPassword { get; set; } /// <seealso cref="http://oauth.net/core/1.0#request_urls"/> public virtual string RequestTokenUrl { get; set; } /// <seealso cref="http://oauth.net/core/1.0#request_urls"/> public virtual string AccessTokenUrl { get; set; } /// <seealso cref="http://oauth.net/core/1.0#request_urls"/> public virtual string AuthorizationUrl { get; set; } /// <summary> /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an /// <see cref="IAuthenticator" /> for the purpose of requesting an /// unauthorized request token. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <seealso cref="http://oauth.net/core/1.0#anchor9"/> /// <returns></returns> public OAuthWebQueryInfo BuildRequestTokenInfo(string method) { return this.BuildRequestTokenInfo(method, null); } /// <summary> /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an /// <see cref="IAuthenticator" /> for the purpose of requesting an /// unauthorized request token. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> /// <seealso cref="http://oauth.net/core/1.0#anchor9"/> /// <returns></returns> public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters) { this.ValidateTokenRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); this.AddAuthParameters(parameters, timestamp, nonce); var signatureBase = OAuthTools.ConcatenateRequestElements(method, this.RequestTokenUrl, parameters); var signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, this.ConsumerSecret); var info = new OAuthWebQueryInfo { WebMethod = method, ParameterHandling = this.ParameterHandling, ConsumerKey = this.ConsumerKey, SignatureMethod = this.SignatureMethod.ToRequestValue(), SignatureTreatment = this.SignatureTreatment, Signature = signature, Timestamp = timestamp, Nonce = nonce, Version = this.Version ?? "1.0", Callback = OAuthTools.UrlEncodeRelaxed(this.CallbackUrl ?? string.Empty), TokenSecret = this.TokenSecret, ConsumerSecret = this.ConsumerSecret }; return info; } /// <summary> /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an /// <see cref="IAuthenticator" /> for the purpose of exchanging a request token /// for an access token authorized by the user at the Service Provider site. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <seealso cref="http://oauth.net/core/1.0#anchor9"/> public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method) { return this.BuildAccessTokenInfo(method, null); } /// <summary> /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an /// <see cref="IAuthenticator" /> for the purpose of exchanging a request token /// for an access token authorized by the user at the Service Provider site. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <seealso cref="http://oauth.net/core/1.0#anchor9"/> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParameterCollection parameters) { this.ValidateAccessRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } var uri = new Uri(this.AccessTokenUrl); var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); this.AddAuthParameters(parameters, timestamp, nonce); var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); var signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, this.ConsumerSecret, this.TokenSecret); var info = new OAuthWebQueryInfo { WebMethod = method, ParameterHandling = this.ParameterHandling, ConsumerKey = this.ConsumerKey, Token = this.Token, SignatureMethod = this.SignatureMethod.ToRequestValue(), SignatureTreatment = this.SignatureTreatment, Signature = signature, Timestamp = timestamp, Nonce = nonce, Version = this.Version ?? "1.0", Verifier = this.Verifier, Callback = this.CallbackUrl, TokenSecret = this.TokenSecret, ConsumerSecret = this.ConsumerSecret, }; return info; } /// <summary> /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an /// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials /// for an access token authorized by the user at the Service Provider site. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <seealso cref="http://tools.ietf.org/html/draft-dehora-farrell-oauth-accesstoken-creds-00#section-4"/> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> public virtual OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters) { this.ValidateClientAuthAccessRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } var uri = new Uri(this.AccessTokenUrl); var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); this.AddXAuthParameters(parameters, timestamp, nonce); var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); var signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, this.ConsumerSecret); var info = new OAuthWebQueryInfo { WebMethod = method, ParameterHandling = this.ParameterHandling, ClientMode = "client_auth", ClientUsername = this.ClientUsername, ClientPassword = this.ClientPassword, ConsumerKey = this.ConsumerKey, SignatureMethod = this.SignatureMethod.ToRequestValue(), SignatureTreatment = this.SignatureTreatment, Signature = signature, Timestamp = timestamp, Nonce = nonce, Version = this.Version ?? "1.0", TokenSecret = this.TokenSecret, ConsumerSecret = this.ConsumerSecret }; return info; } public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url) { this.ValidateProtectedResourceState(); if (parameters == null) { parameters = new WebParameterCollection(); } // Include url parameters in query pool var uri = new Uri(url); #if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC var urlParameters = HttpUtility.ParseQueryString(uri.Query); #else var urlParameters = uri.Query.ParseQueryString(); #endif #if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC foreach (var parameter in urlParameters.AllKeys) #else foreach (var parameter in urlParameters.Keys) #endif { #if PocketPC switch (method.ToUpper()) #else switch (method.ToUpperInvariant()) #endif { case "POST": parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter])); break; default: parameters.Add(parameter, urlParameters[parameter]); break; } } var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); this.AddAuthParameters(parameters, timestamp, nonce); var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters); var signature = OAuthTools.GetSignature( this.SignatureMethod, this.SignatureTreatment, signatureBase, this.ConsumerSecret, this.TokenSecret); var info = new OAuthWebQueryInfo { WebMethod = method, ParameterHandling = this.ParameterHandling, ConsumerKey = this.ConsumerKey, Token = this.Token, SignatureMethod = this.SignatureMethod.ToRequestValue(), SignatureTreatment = this.SignatureTreatment, Signature = signature, Timestamp = timestamp, Nonce = nonce, Version = this.Version ?? "1.0", Callback = this.CallbackUrl, ConsumerSecret = this.ConsumerSecret, TokenSecret = this.TokenSecret }; return info; } private void ValidateTokenRequestState() { if (this.RequestTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify a request token URL"); } if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } } private void ValidateAccessRequestState() { if (this.AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } if (this.Token.IsNullOrBlank()) { throw new ArgumentException("You must specify a token"); } } private void ValidateClientAuthAccessRequestState() { if (this.AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } if (this.ClientUsername.IsNullOrBlank() || this.ClientPassword.IsNullOrBlank()) { throw new ArgumentException("You must specify user credentials"); } } private void ValidateProtectedResourceState() { if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } } private void AddAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce) { var authParameters = new WebParameterCollection { new WebPair("oauth_consumer_key", this.ConsumerKey), new WebPair("oauth_nonce", nonce), new WebPair("oauth_signature_method", this.SignatureMethod.ToRequestValue()), new WebPair("oauth_timestamp", timestamp), new WebPair("oauth_version", this.Version ?? "1.0") }; if (!this.Token.IsNullOrBlank()) { authParameters.Add(new WebPair("oauth_token", this.Token)); } if (!this.CallbackUrl.IsNullOrBlank()) { authParameters.Add(new WebPair("oauth_callback", this.CallbackUrl)); } if (!this.Verifier.IsNullOrBlank()) { authParameters.Add(new WebPair("oauth_verifier", this.Verifier)); } if (!this.SessionHandle.IsNullOrBlank()) { authParameters.Add(new WebPair("oauth_session_handle", this.SessionHandle)); } foreach (var authParameter in authParameters) { parameters.Add(authParameter); } } private void AddXAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce) { var authParameters = new WebParameterCollection { new WebPair("x_auth_username", this.ClientUsername), new WebPair("x_auth_password", this.ClientPassword), new WebPair("x_auth_mode", "client_auth"), new WebPair("oauth_consumer_key", this.ConsumerKey), new WebPair("oauth_signature_method", this.SignatureMethod.ToRequestValue()), new WebPair("oauth_timestamp", timestamp), new WebPair("oauth_nonce", nonce), new WebPair("oauth_version", this.Version ?? "1.0") }; foreach (var authParameter in authParameters) { parameters.Add(authParameter); } } } }
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using Windows.Devices.Geolocation; using Windows.Networking.NetworkOperators; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using GalaSoft.MvvmLight.Views; using SharpTox.Core; using ToxRt.Helpers; using ToxRt.Model; using ToxRt.NavigationService; namespace ToxRt.ViewModel { public enum Status { Online, Offline, Away } public class MainViewModel : NavigableViewModelBase { #region Fields private String _localId; private ObservableCollection<Friend> _listFriends; private Profile _defaultProfile; private Tox _tox; private Status _userStatus = Status.Online; // for testing purpuse only private ObservableCollection<DHT_Node> _nodes; #endregion #region Properties public ObservableCollection<Friend> ListFriends { get { return _listFriends; } set { if (_listFriends == value) { return; } _listFriends = value; RaisePropertyChanged(); } } public String LocalId { get { return _localId; } set { if (_localId == value) { return; } _localId = value; RaisePropertyChanged(); } } public Profile DefaultProfile { get { return _defaultProfile; } set { if (_defaultProfile == value) { return; } _defaultProfile = value; RaisePropertyChanged(); } } public Status UserStatus { get { return _userStatus; } set { if (_userStatus == value) { return; } _userStatus = value; RaisePropertyChanged(); } } #endregion #region Commands private RelayCommand<Friend> _friendSelectedCommand; public RelayCommand<Friend> FriendSelectedCommand { get { return _friendSelectedCommand ?? (_friendSelectedCommand = new RelayCommand<Friend>( (friend) => InnerNavigationService.NavigateTo("MessagesView", friend))); } } private RelayCommand _loadedCommand; public RelayCommand LoadedCommand { get { return _loadedCommand ?? (_loadedCommand = new RelayCommand(async () => { //Load the default profile from the database DefaultProfile = DataService.GetDefaultProfile(); if (DefaultProfile == null) { //Create a default profile before starting DefaultProfile = new Profile() { ScreenName = "Tmp", StatusMessage = "Tmp", ToxId = "", ProfileLanguage = "English", ProfileTheme = "Default", AudioNotifications = 1, CloseToTray = 1, IsDefault = 1, ProfileName = Guid.NewGuid().ToString() }; DataService.InsertNewProfile(DefaultProfile); } //initiate tox --get those option parameter from the db var options = new ToxOptions(true, false); _tox = new Tox(options); _tox.OnFriendRequest += tox_OnFriendRequest; _tox.OnFriendMessage += tox_OnFriendMessage; //Load the nodes from the local db _nodes = new ObservableCollection<DHT_Node>(await DataService.LoadAllDhtNodes()); //try to bootstap from those node if (!Boostraping()) { //update the nodes from the wiki [At least for now] page and reboostraping UpdateNodes(); if (!Boostraping()) { Debug.WriteLine("Can't boostrap from the current nodes !"); } } _tox.Name = DefaultProfile.ScreenName; //Everything is loadede from the Sqlite database, no .tox files or anything _tox.StatusMessage = DefaultProfile.StatusMessage; _tox.Start(); LocalId = _tox.Id.ToString(); DefaultProfile.ToxId = LocalId; Debug.WriteLine("ID: {0}", LocalId); })); } } private RelayCommand _addFriendCommand; public RelayCommand AddFriendCommand { get { return _addFriendCommand ?? (_addFriendCommand = new RelayCommand( () => { InnerNavigationService.NavigateTo("AddFriendView", _tox); })); } } private RelayCommand _searchFriendCommand; public RelayCommand SearchFriendCommand { get { return _searchFriendCommand ?? (_searchFriendCommand = new RelayCommand( () => { })); } } private RelayCommand _changeStatusCommand; public RelayCommand ChangeStatusCommand { get { return _changeStatusCommand ?? (_changeStatusCommand = new RelayCommand( () => { //Use a flyout here })); } } private RelayCommand _addGroupeCommand; public RelayCommand AddGroupeCommand { get { return _addGroupeCommand ?? (_addGroupeCommand = new RelayCommand( () => { InnerNavigationService.NavigateTo("GroupeChatSettingsView"); })); } } private RelayCommand _removeSelectedFriendsCommand; public RelayCommand RemoveSelectedFriendsCommand { get { return _removeSelectedFriendsCommand ?? (_removeSelectedFriendsCommand = new RelayCommand( () => { })); } } private RelayCommand _loadProfileCommand; public RelayCommand LoadProfileCommand { get { return _loadProfileCommand ?? (_loadProfileCommand = new RelayCommand( () => { InnerNavigationService.NavigateTo("LoadProfileView"); })); } } private RelayCommand _settingsCommand; public RelayCommand SettingsCommand { get { return _settingsCommand ?? (_settingsCommand = new RelayCommand( () => { NavigationService.NavigateTo("SettingsView", DefaultProfile); })); } } private RelayCommand _creditCommand; public RelayCommand CreditCommand { get { return _creditCommand ?? (_creditCommand = new RelayCommand( () => { NavigationService.NavigateTo("CreditView"); })); } } #endregion #region Ctors and Methods public MainViewModel(INavigationService navigationService, IDataService dataService, IMessagesNavigationService innerNavigationService) : base(navigationService, dataService, innerNavigationService) { Messenger.Default.Register<NotificationMessage>(this, async (m) => { switch (m.Notification) { case "RefreshFriends": ListFriends = new ObservableCollection<Friend>(await DataService.GetAllFriends()); //Missing, The Avatar break; } }); //for test purpuse only ListFriends = new ObservableCollection<Friend>() { new Friend() { PicSource = "../Images/user.png", RealName = "Joseph Walsh", ScreenName = "Josheph", CurrentStatus = Status.Offline }, new Friend() { PicSource = "../Images/user.png", RealName = "Alan Deep", ScreenName = "Dii34", CurrentStatus = Status.Online } }; } private void tox_OnFriendMessage(object sender, ToxEventArgs.FriendMessageEventArgs e) { //get the name associated with the friendnumber string name = _tox.GetName(e.FriendNumber); //print the message to the console Debug.WriteLine("<{0}> {1}", name, e.Message); } private void tox_OnFriendRequest(object sender, ToxEventArgs.FriendRequestEventArgs e) { //automatically accept every friend request we receive _tox.AddFriendNoRequest(new ToxKey(ToxKeyType.Public, e.Id)); //Save the friend request in the database DataService.ReceiveFriendRequest(new FriendRequest() { ToxId = e.Id, RequestMessage = e.Message }); //show A Notification //Toast, Push } private bool Boostraping() { bool success = false; foreach (DHT_Node node in _nodes) success = success || _tox.BootstrapFromNode(new ToxNode(node.Ipv4, node.Port, new ToxKey(ToxKeyType.Public, node.ClientId))); return success; //make sure that at least one node is bootstraped succesfully } private void UpdateNodes() { } public override void Activate(object parameter) { if (parameter is Profile) { DefaultProfile = (Profile)parameter; } } public override void Deactivate(object parameter) { } public override void GoBack() { } #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.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.Hosting { using TypeInfo = System.Reflection.TypeInfo; /// <summary> /// Object pretty printer. /// </summary> public abstract partial class ObjectFormatter { internal ObjectFormatter() { } public string FormatObject(object obj) { return new Formatter(this, null).FormatObject(obj); } internal string FormatObject(object obj, ObjectFormattingOptions options) { return new Formatter(this, options).FormatObject(obj); } #region Reflection Helpers private static bool HasOverriddenToString(TypeInfo type) { if (type.IsInterface) { return false; } while (type.AsType() != typeof(object)) { if (type.GetDeclaredMethod("ToString", Type.EmptyTypes) != null) { return true; } type = type.BaseType.GetTypeInfo(); } return false; } private static DebuggerDisplayAttribute GetApplicableDebuggerDisplayAttribute(MemberInfo member) { // Includes inherited attributes. The debugger uses the first attribute if multiple are applied. var result = member.GetCustomAttributes<DebuggerDisplayAttribute>().FirstOrDefault(); if (result != null) { return result; } // TODO (tomat): which assembly should we look at for dd attributes? var type = member as TypeInfo; if (type != null) { foreach (DebuggerDisplayAttribute attr in type.Assembly.GetCustomAttributes<DebuggerDisplayAttribute>()) { if (IsApplicableAttribute(type, attr.Target.GetTypeInfo(), attr.TargetTypeName)) { return attr; } } } return null; } private static DebuggerTypeProxyAttribute GetApplicableDebuggerTypeProxyAttribute(TypeInfo type) { // includes inherited attributes. The debugger uses the first attribute if multiple are applied. var result = type.GetCustomAttributes<DebuggerTypeProxyAttribute>().FirstOrDefault(); if (result != null) { return result; } // TODO (tomat): which assembly should we look at for proxy attributes? foreach (DebuggerTypeProxyAttribute attr in type.Assembly.GetCustomAttributes<DebuggerTypeProxyAttribute>()) { if (IsApplicableAttribute(type, attr.Target.GetTypeInfo(), attr.TargetTypeName)) { return attr; } } return null; } private static bool IsApplicableAttribute(TypeInfo type, TypeInfo targetType, string targetTypeName) { return type != null && AreEquivalent(targetType, type) || targetTypeName != null && type.FullName == targetTypeName; } private static bool AreEquivalent(TypeInfo type, TypeInfo other) { // TODO: Unify NoPIA interfaces // https://github.com/dotnet/corefx/issues/2101 return type.Equals(other); } private static object GetDebuggerTypeProxy(object obj) { // use proxy type if defined: var type = obj.GetType().GetTypeInfo(); var debuggerTypeProxy = GetApplicableDebuggerTypeProxyAttribute(type); if (debuggerTypeProxy != null) { try { var proxyType = Type.GetType(debuggerTypeProxy.ProxyTypeName, throwOnError: false, ignoreCase: false); if (proxyType != null) { if (proxyType.GetTypeInfo().IsGenericTypeDefinition) { proxyType = proxyType.MakeGenericType(type.GenericTypeArguments); } return Activator.CreateInstance(proxyType, new object[] { obj }); } } catch (Exception) { // no-op, ignore proxy if it is implemented incorrectly or can't be loaded } } return null; } private static MemberInfo ResolveMember(object obj, string memberName, bool callableOnly) { TypeInfo type = obj.GetType().GetTypeInfo(); // case-sensitive: TypeInfo currentType = type; while (true) { if (!callableOnly) { var field = currentType.GetDeclaredField(memberName); if (field != null) { return field; } var property = currentType.GetDeclaredProperty(memberName); if (property != null) { var getter = property.GetMethod; if (getter != null) { return getter; } } } var method = currentType.GetDeclaredMethod(memberName, Type.EmptyTypes); if (method != null) { return method; } if (currentType.BaseType == null) { break; } currentType = currentType.BaseType.GetTypeInfo(); } // case-insensitive: currentType = type; while (true) { IEnumerable<MemberInfo> members; if (callableOnly) { members = type.DeclaredMethods; } else { members = ((IEnumerable<MemberInfo>)type.DeclaredFields).Concat(type.DeclaredProperties); } MemberInfo candidate = null; foreach (var member in members) { if (StringComparer.OrdinalIgnoreCase.Equals(memberName, member.Name)) { if (candidate != null) { return null; } MethodInfo method; if (member is FieldInfo) { candidate = member; } else if ((method = member as MethodInfo) != null) { if (method.GetParameters().Length == 0) { candidate = member; } } else { var getter = ((PropertyInfo)member).GetMethod; if (getter?.GetParameters().Length == 0) { candidate = member; } } } } if (candidate != null) { return candidate; } if (currentType.BaseType == null) { break; } currentType = currentType.BaseType.GetTypeInfo(); } return null; } private static object GetMemberValue(MemberInfo member, object obj, out Exception exception) { exception = null; try { FieldInfo field; MethodInfo method; if ((field = member as FieldInfo) != null) { return field.GetValue(obj); } if ((method = member as MethodInfo) != null) { return (method.ReturnType == typeof(void)) ? s_voidValue : method.Invoke(obj, SpecializedCollections.EmptyObjects); } var property = (PropertyInfo)member; if (property.GetMethod == null) { return null; } return property.GetValue(obj, SpecializedCollections.EmptyObjects); } catch (TargetInvocationException e) { exception = e.InnerException; } return null; } private static readonly object s_voidValue = new object(); #endregion #region String Builder Helpers private sealed class Builder { private readonly ObjectFormattingOptions _options; private readonly StringBuilder _sb; private readonly int _lineLengthLimit; private readonly int _lengthLimit; private readonly bool _insertEllipsis; private int _currentLimit; public Builder(int lengthLimit, ObjectFormattingOptions options, bool insertEllipsis) { Debug.Assert(lengthLimit <= options.MaxOutputLength); int lineLengthLimit = options.MaxLineLength; if (insertEllipsis) { lengthLimit = Math.Max(0, lengthLimit - options.Ellipsis.Length - 1); lineLengthLimit = Math.Max(0, lineLengthLimit - options.Ellipsis.Length - 1); } _lengthLimit = lengthLimit; _lineLengthLimit = lineLengthLimit; _currentLimit = Math.Min(lineLengthLimit, lengthLimit); _insertEllipsis = insertEllipsis; _options = options; _sb = new StringBuilder(); } public bool LimitReached { get { return _sb.Length == _lengthLimit; } } public int Remaining { get { return _lengthLimit - _sb.Length; } } // can be negative (the min value is -Ellipsis.Length - 1) private int CurrentRemaining { get { return _currentLimit - _sb.Length; } } public void AppendLine() { // remove line length limit so that we can insert a new line even // if the previous one hit maxed out the line limit: _currentLimit = _lengthLimit; Append(_options.NewLine); // recalc limit for the next line: _currentLimit = (int)Math.Min((long)_sb.Length + _lineLengthLimit, _lengthLimit); } private void AppendEllipsis() { if (_sb.Length > 0 && _sb[_sb.Length - 1] != ' ') { _sb.Append(' '); } _sb.Append(_options.Ellipsis); } public void Append(char c, int count = 1) { if (CurrentRemaining < 0) { return; } int length = Math.Min(count, CurrentRemaining); _sb.Append(c, length); if (_insertEllipsis && length < count) { AppendEllipsis(); } } public void Append(string str, int start = 0, int count = Int32.MaxValue) { if (str == null || CurrentRemaining < 0) { return; } count = Math.Min(count, str.Length - start); int length = Math.Min(count, CurrentRemaining); _sb.Append(str, start, length); if (_insertEllipsis && length < count) { AppendEllipsis(); } } public void AppendFormat(string format, params object[] args) { Append(String.Format(format, args)); } public void AppendGroupOpening() { Append('{'); } public void AppendGroupClosing(bool inline) { if (inline) { Append(" }"); } else { AppendLine(); Append('}'); AppendLine(); } } public void AppendCollectionItemSeparator(bool isFirst, bool inline) { if (isFirst) { if (inline) { Append(' '); } else { AppendLine(); } } else { if (inline) { Append(", "); } else { Append(','); AppendLine(); } } if (!inline) { Append(_options.MemberIndentation); } } internal void AppendInfiniteRecursionMarker() { AppendGroupOpening(); AppendCollectionItemSeparator(isFirst: true, inline: true); Append(_options.Ellipsis); AppendGroupClosing(inline: true); } public override string ToString() { return _sb.ToString(); } } #endregion #region Language Specific Formatting /// <summary> /// String that describes "void" return type in the language. /// </summary> internal abstract object VoidDisplayString { get; } /// <summary> /// String that describes "null" literal in the language. /// </summary> internal abstract string NullLiteral { get; } internal abstract string FormatLiteral(bool value); internal abstract string FormatLiteral(string value, bool quote, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(char value, bool quote, bool includeCodePoints = false, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(sbyte value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(byte value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(short value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(ushort value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(int value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(uint value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(long value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(ulong value, bool useHexadecimalNumbers = false); internal abstract string FormatLiteral(double value); internal abstract string FormatLiteral(float value); internal abstract string FormatLiteral(decimal value); internal abstract string FormatLiteral(DateTime value); // TODO (tomat): Use DebuggerDisplay.Type if specified? internal abstract string FormatGeneratedTypeName(Type type); internal abstract string FormatMemberName(MemberInfo member); internal abstract string GetPrimitiveTypeName(SpecialType type); /// <summary> /// Returns a method signature display string. Used to display stack frames. /// </summary> /// <returns>Null if the method is a compiler generated method that shouldn't be displayed to the user.</returns> internal virtual string FormatMethodSignature(MethodBase method) { // TODO: https://github.com/dotnet/roslyn/issues/5250 if (method.Name.IndexOfAny(s_generatedNameChars) >= 0 || method.DeclaringType.Name.IndexOfAny(s_generatedNameChars) >= 0 || method.GetCustomAttributes<DebuggerHiddenAttribute>().Any() || method.DeclaringType.GetTypeInfo().GetCustomAttributes<DebuggerHiddenAttribute>().Any()) { return null; } return $"{method.DeclaringType.ToString()}.{method.Name}({string.Join(", ", method.GetParameters().Select(p => p.ToString()))})"; } private static readonly char[] s_generatedNameChars = { '$', '<' }; internal abstract string GenericParameterOpening { get; } internal abstract string GenericParameterClosing { get; } /// <summary> /// Formats an array type name (vector or multidimensional). /// </summary> internal abstract string FormatArrayTypeName(Type arrayType, Array arrayOpt, ObjectFormattingOptions options); /// <summary> /// Returns true if the member shouldn't be displayed (e.g. it's a compiler generated field). /// </summary> internal virtual bool IsHiddenMember(MemberInfo member) => false; internal static ObjectDisplayOptions GetObjectDisplayOptions(bool useHexadecimalNumbers) { return useHexadecimalNumbers ? ObjectDisplayOptions.UseHexadecimalNumbers : ObjectDisplayOptions.None; } /// <summary> /// Returns null if the type is not considered primitive in the target language. /// </summary> private string FormatPrimitive(object obj, bool quoteStrings, bool includeCodePoints, bool useHexadecimalNumbers) { if (ReferenceEquals(obj, s_voidValue)) { return string.Empty; } if (obj == null) { return NullLiteral; } var type = obj.GetType(); if (type.GetTypeInfo().IsEnum) { return obj.ToString(); } switch (GetPrimitiveSpecialType(type)) { case SpecialType.System_Int32: return FormatLiteral((int)obj, useHexadecimalNumbers); case SpecialType.System_String: return FormatLiteral((string)obj, quoteStrings, useHexadecimalNumbers); case SpecialType.System_Boolean: return FormatLiteral((bool)obj); case SpecialType.System_Char: return FormatLiteral((char)obj, quoteStrings, includeCodePoints, useHexadecimalNumbers); case SpecialType.System_Int64: return FormatLiteral((long)obj, useHexadecimalNumbers); case SpecialType.System_Double: return FormatLiteral((double)obj); case SpecialType.System_Byte: return FormatLiteral((byte)obj, useHexadecimalNumbers); case SpecialType.System_Decimal: return FormatLiteral((decimal)obj); case SpecialType.System_UInt32: return FormatLiteral((uint)obj, useHexadecimalNumbers); case SpecialType.System_UInt64: return FormatLiteral((ulong)obj, useHexadecimalNumbers); case SpecialType.System_Single: return FormatLiteral((float)obj); case SpecialType.System_Int16: return FormatLiteral((short)obj, useHexadecimalNumbers); case SpecialType.System_UInt16: return FormatLiteral((ushort)obj, useHexadecimalNumbers); case SpecialType.System_DateTime: return FormatLiteral((DateTime)obj); case SpecialType.System_SByte: return FormatLiteral((sbyte)obj, useHexadecimalNumbers); case SpecialType.System_Object: case SpecialType.System_Void: case SpecialType.None: return null; default: throw ExceptionUtilities.Unreachable; } } internal static SpecialType GetPrimitiveSpecialType(Type type) { Debug.Assert(type != null); if (type == typeof(int)) { return SpecialType.System_Int32; } if (type == typeof(string)) { return SpecialType.System_String; } if (type == typeof(bool)) { return SpecialType.System_Boolean; } if (type == typeof(char)) { return SpecialType.System_Char; } if (type == typeof(long)) { return SpecialType.System_Int64; } if (type == typeof(double)) { return SpecialType.System_Double; } if (type == typeof(byte)) { return SpecialType.System_Byte; } if (type == typeof(decimal)) { return SpecialType.System_Decimal; } if (type == typeof(uint)) { return SpecialType.System_UInt32; } if (type == typeof(ulong)) { return SpecialType.System_UInt64; } if (type == typeof(float)) { return SpecialType.System_Single; } if (type == typeof(short)) { return SpecialType.System_Int16; } if (type == typeof(ushort)) { return SpecialType.System_UInt16; } if (type == typeof(DateTime)) { return SpecialType.System_DateTime; } if (type == typeof(sbyte)) { return SpecialType.System_SByte; } if (type == typeof(object)) { return SpecialType.System_Object; } if (type == typeof(void)) { return SpecialType.System_Void; } return SpecialType.None; } internal string FormatTypeName(Type type, ObjectFormattingOptions options) { string result = GetPrimitiveTypeName(GetPrimitiveSpecialType(type)); if (result != null) { return result; } result = FormatGeneratedTypeName(type); if (result != null) { return result; } if (type.IsArray) { return FormatArrayTypeName(type, arrayOpt: null, options: options); } var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType) { return FormatGenericTypeName(typeInfo, options); } if (typeInfo.DeclaringType != null) { return typeInfo.Name.Replace('+', '.'); } return typeInfo.Name; } private string FormatGenericTypeName(TypeInfo typeInfo, ObjectFormattingOptions options) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; // consolidated generic arguments (includes arguments of all declaring types): Type[] genericArguments = typeInfo.GenericTypeArguments; if (typeInfo.DeclaringType != null) { var nestedTypes = ArrayBuilder<TypeInfo>.GetInstance(); do { nestedTypes.Add(typeInfo); typeInfo = typeInfo.DeclaringType?.GetTypeInfo(); } while (typeInfo != null); int typeArgumentIndex = 0; for (int i = nestedTypes.Count - 1; i >= 0; i--) { AppendTypeInstantiation(builder, nestedTypes[i], genericArguments, ref typeArgumentIndex, options); if (i > 0) { builder.Append('.'); } } nestedTypes.Free(); } else { int typeArgumentIndex = 0; AppendTypeInstantiation(builder, typeInfo, genericArguments, ref typeArgumentIndex, options); } return pooledBuilder.ToStringAndFree(); } private void AppendTypeInstantiation(StringBuilder builder, TypeInfo typeInfo, Type[] genericArguments, ref int genericArgIndex, ObjectFormattingOptions options) { // generic arguments of all the outer types and the current type; int currentArgCount = (typeInfo.IsGenericTypeDefinition ? typeInfo.GenericTypeParameters.Length : typeInfo.GenericTypeArguments.Length) - genericArgIndex; if (currentArgCount > 0) { string name = typeInfo.Name; int backtick = name.IndexOf('`'); if (backtick > 0) { builder.Append(name.Substring(0, backtick)); } else { builder.Append(name); } builder.Append(GenericParameterOpening); for (int i = 0; i < currentArgCount; i++) { if (i > 0) { builder.Append(", "); } builder.Append(FormatTypeName(genericArguments[genericArgIndex++], options)); } builder.Append(GenericParameterClosing); } else { builder.Append(typeInfo.Name); } } #endregion } }
namespace Avalonia.Media { /// <summary> /// Predefined brushes. /// </summary> public static class Brushes { /// <summary> /// Gets an <see cref="Colors.AliceBlue"/> colored brush. /// </summary> public static ISolidColorBrush AliceBlue => KnownColor.AliceBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.AntiqueWhite"/> colored brush. /// </summary> public static ISolidColorBrush AntiqueWhite => KnownColor.AntiqueWhite.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Aqua"/> colored brush. /// </summary> public static ISolidColorBrush Aqua => KnownColor.Aqua.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Aquamarine"/> colored brush. /// </summary> public static ISolidColorBrush Aquamarine => KnownColor.Aquamarine.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Azure"/> colored brush. /// </summary> public static ISolidColorBrush Azure => KnownColor.Azure.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Beige"/> colored brush. /// </summary> public static ISolidColorBrush Beige => KnownColor.Beige.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Bisque"/> colored brush. /// </summary> public static ISolidColorBrush Bisque => KnownColor.Bisque.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Black"/> colored brush. /// </summary> public static ISolidColorBrush Black => KnownColor.Black.ToBrush(); /// <summary> /// Gets an <see cref="Colors.BlanchedAlmond"/> colored brush. /// </summary> public static ISolidColorBrush BlanchedAlmond => KnownColor.BlanchedAlmond.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Blue"/> colored brush. /// </summary> public static ISolidColorBrush Blue => KnownColor.Blue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.BlueViolet"/> colored brush. /// </summary> public static ISolidColorBrush BlueViolet => KnownColor.BlueViolet.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Brown"/> colored brush. /// </summary> public static ISolidColorBrush Brown => KnownColor.Brown.ToBrush(); /// <summary> /// Gets an <see cref="Colors.BurlyWood"/> colored brush. /// </summary> public static ISolidColorBrush BurlyWood => KnownColor.BurlyWood.ToBrush(); /// <summary> /// Gets an <see cref="Colors.CadetBlue"/> colored brush. /// </summary> public static ISolidColorBrush CadetBlue => KnownColor.CadetBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Chartreuse"/> colored brush. /// </summary> public static ISolidColorBrush Chartreuse => KnownColor.Chartreuse.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Chocolate"/> colored brush. /// </summary> public static ISolidColorBrush Chocolate => KnownColor.Chocolate.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Coral"/> colored brush. /// </summary> public static ISolidColorBrush Coral => KnownColor.Coral.ToBrush(); /// <summary> /// Gets an <see cref="Colors.CornflowerBlue"/> colored brush. /// </summary> public static ISolidColorBrush CornflowerBlue => KnownColor.CornflowerBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Cornsilk"/> colored brush. /// </summary> public static ISolidColorBrush Cornsilk => KnownColor.Cornsilk.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Crimson"/> colored brush. /// </summary> public static ISolidColorBrush Crimson => KnownColor.Crimson.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Cyan"/> colored brush. /// </summary> public static ISolidColorBrush Cyan => KnownColor.Cyan.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkBlue"/> colored brush. /// </summary> public static ISolidColorBrush DarkBlue => KnownColor.DarkBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkCyan"/> colored brush. /// </summary> public static ISolidColorBrush DarkCyan => KnownColor.DarkCyan.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkGoldenrod"/> colored brush. /// </summary> public static ISolidColorBrush DarkGoldenrod => KnownColor.DarkGoldenrod.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkGray"/> colored brush. /// </summary> public static ISolidColorBrush DarkGray => KnownColor.DarkGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkGreen"/> colored brush. /// </summary> public static ISolidColorBrush DarkGreen => KnownColor.DarkGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkKhaki"/> colored brush. /// </summary> public static ISolidColorBrush DarkKhaki => KnownColor.DarkKhaki.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkMagenta"/> colored brush. /// </summary> public static ISolidColorBrush DarkMagenta => KnownColor.DarkMagenta.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkOliveGreen"/> colored brush. /// </summary> public static ISolidColorBrush DarkOliveGreen => KnownColor.DarkOliveGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkOrange"/> colored brush. /// </summary> public static ISolidColorBrush DarkOrange => KnownColor.DarkOrange.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkOrchid"/> colored brush. /// </summary> public static ISolidColorBrush DarkOrchid => KnownColor.DarkOrchid.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkRed"/> colored brush. /// </summary> public static ISolidColorBrush DarkRed => KnownColor.DarkRed.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkSalmon"/> colored brush. /// </summary> public static ISolidColorBrush DarkSalmon => KnownColor.DarkSalmon.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkSeaGreen"/> colored brush. /// </summary> public static ISolidColorBrush DarkSeaGreen => KnownColor.DarkSeaGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkSlateBlue"/> colored brush. /// </summary> public static ISolidColorBrush DarkSlateBlue => KnownColor.DarkSlateBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkSlateGray"/> colored brush. /// </summary> public static ISolidColorBrush DarkSlateGray => KnownColor.DarkSlateGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkTurquoise"/> colored brush. /// </summary> public static ISolidColorBrush DarkTurquoise => KnownColor.DarkTurquoise.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DarkViolet"/> colored brush. /// </summary> public static ISolidColorBrush DarkViolet => KnownColor.DarkViolet.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DeepPink"/> colored brush. /// </summary> public static ISolidColorBrush DeepPink => KnownColor.DeepPink.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DeepSkyBlue"/> colored brush. /// </summary> public static ISolidColorBrush DeepSkyBlue => KnownColor.DeepSkyBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DimGray"/> colored brush. /// </summary> public static ISolidColorBrush DimGray => KnownColor.DimGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.DodgerBlue"/> colored brush. /// </summary> public static ISolidColorBrush DodgerBlue => KnownColor.DodgerBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Firebrick"/> colored brush. /// </summary> public static ISolidColorBrush Firebrick => KnownColor.Firebrick.ToBrush(); /// <summary> /// Gets an <see cref="Colors.FloralWhite"/> colored brush. /// </summary> public static ISolidColorBrush FloralWhite => KnownColor.FloralWhite.ToBrush(); /// <summary> /// Gets an <see cref="Colors.ForestGreen"/> colored brush. /// </summary> public static ISolidColorBrush ForestGreen => KnownColor.ForestGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Fuchsia"/> colored brush. /// </summary> public static ISolidColorBrush Fuchsia => KnownColor.Fuchsia.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Gainsboro"/> colored brush. /// </summary> public static ISolidColorBrush Gainsboro => KnownColor.Gainsboro.ToBrush(); /// <summary> /// Gets an <see cref="Colors.GhostWhite"/> colored brush. /// </summary> public static ISolidColorBrush GhostWhite => KnownColor.GhostWhite.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Gold"/> colored brush. /// </summary> public static ISolidColorBrush Gold => KnownColor.Gold.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Goldenrod"/> colored brush. /// </summary> public static ISolidColorBrush Goldenrod => KnownColor.Goldenrod.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Gray"/> colored brush. /// </summary> public static ISolidColorBrush Gray => KnownColor.Gray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Green"/> colored brush. /// </summary> public static ISolidColorBrush Green => KnownColor.Green.ToBrush(); /// <summary> /// Gets an <see cref="Colors.GreenYellow"/> colored brush. /// </summary> public static ISolidColorBrush GreenYellow => KnownColor.GreenYellow.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Honeydew"/> colored brush. /// </summary> public static ISolidColorBrush Honeydew => KnownColor.Honeydew.ToBrush(); /// <summary> /// Gets an <see cref="Colors.HotPink"/> colored brush. /// </summary> public static ISolidColorBrush HotPink => KnownColor.HotPink.ToBrush(); /// <summary> /// Gets an <see cref="Colors.IndianRed"/> colored brush. /// </summary> public static ISolidColorBrush IndianRed => KnownColor.IndianRed.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Indigo"/> colored brush. /// </summary> public static ISolidColorBrush Indigo => KnownColor.Indigo.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Ivory"/> colored brush. /// </summary> public static ISolidColorBrush Ivory => KnownColor.Ivory.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Khaki"/> colored brush. /// </summary> public static ISolidColorBrush Khaki => KnownColor.Khaki.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Lavender"/> colored brush. /// </summary> public static ISolidColorBrush Lavender => KnownColor.Lavender.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LavenderBlush"/> colored brush. /// </summary> public static ISolidColorBrush LavenderBlush => KnownColor.LavenderBlush.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LawnGreen"/> colored brush. /// </summary> public static ISolidColorBrush LawnGreen => KnownColor.LawnGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LemonChiffon"/> colored brush. /// </summary> public static ISolidColorBrush LemonChiffon => KnownColor.LemonChiffon.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightBlue"/> colored brush. /// </summary> public static ISolidColorBrush LightBlue => KnownColor.LightBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightCoral"/> colored brush. /// </summary> public static ISolidColorBrush LightCoral => KnownColor.LightCoral.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightCyan"/> colored brush. /// </summary> public static ISolidColorBrush LightCyan => KnownColor.LightCyan.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightGoldenrodYellow"/> colored brush. /// </summary> public static ISolidColorBrush LightGoldenrodYellow => KnownColor.LightGoldenrodYellow.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightGray"/> colored brush. /// </summary> public static ISolidColorBrush LightGray => KnownColor.LightGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightGreen"/> colored brush. /// </summary> public static ISolidColorBrush LightGreen => KnownColor.LightGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightPink"/> colored brush. /// </summary> public static ISolidColorBrush LightPink => KnownColor.LightPink.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightSalmon"/> colored brush. /// </summary> public static ISolidColorBrush LightSalmon => KnownColor.LightSalmon.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightSeaGreen"/> colored brush. /// </summary> public static ISolidColorBrush LightSeaGreen => KnownColor.LightSeaGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightSkyBlue"/> colored brush. /// </summary> public static ISolidColorBrush LightSkyBlue => KnownColor.LightSkyBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightSlateGray"/> colored brush. /// </summary> public static ISolidColorBrush LightSlateGray => KnownColor.LightSlateGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightSteelBlue"/> colored brush. /// </summary> public static ISolidColorBrush LightSteelBlue => KnownColor.LightSteelBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LightYellow"/> colored brush. /// </summary> public static ISolidColorBrush LightYellow => KnownColor.LightYellow.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Lime"/> colored brush. /// </summary> public static ISolidColorBrush Lime => KnownColor.Lime.ToBrush(); /// <summary> /// Gets an <see cref="Colors.LimeGreen"/> colored brush. /// </summary> public static ISolidColorBrush LimeGreen => KnownColor.LimeGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Linen"/> colored brush. /// </summary> public static ISolidColorBrush Linen => KnownColor.Linen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Magenta"/> colored brush. /// </summary> public static ISolidColorBrush Magenta => KnownColor.Magenta.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Maroon"/> colored brush. /// </summary> public static ISolidColorBrush Maroon => KnownColor.Maroon.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumAquamarine"/> colored brush. /// </summary> public static ISolidColorBrush MediumAquamarine => KnownColor.MediumAquamarine.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumBlue"/> colored brush. /// </summary> public static ISolidColorBrush MediumBlue => KnownColor.MediumBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumOrchid"/> colored brush. /// </summary> public static ISolidColorBrush MediumOrchid => KnownColor.MediumOrchid.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumPurple"/> colored brush. /// </summary> public static ISolidColorBrush MediumPurple => KnownColor.MediumPurple.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumSeaGreen"/> colored brush. /// </summary> public static ISolidColorBrush MediumSeaGreen => KnownColor.MediumSeaGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumSlateBlue"/> colored brush. /// </summary> public static ISolidColorBrush MediumSlateBlue => KnownColor.MediumSlateBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumSpringGreen"/> colored brush. /// </summary> public static ISolidColorBrush MediumSpringGreen => KnownColor.MediumSpringGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumTurquoise"/> colored brush. /// </summary> public static ISolidColorBrush MediumTurquoise => KnownColor.MediumTurquoise.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MediumVioletRed"/> colored brush. /// </summary> public static ISolidColorBrush MediumVioletRed => KnownColor.MediumVioletRed.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MidnightBlue"/> colored brush. /// </summary> public static ISolidColorBrush MidnightBlue => KnownColor.MidnightBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MintCream"/> colored brush. /// </summary> public static ISolidColorBrush MintCream => KnownColor.MintCream.ToBrush(); /// <summary> /// Gets an <see cref="Colors.MistyRose"/> colored brush. /// </summary> public static ISolidColorBrush MistyRose => KnownColor.MistyRose.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Moccasin"/> colored brush. /// </summary> public static ISolidColorBrush Moccasin => KnownColor.Moccasin.ToBrush(); /// <summary> /// Gets an <see cref="Colors.NavajoWhite"/> colored brush. /// </summary> public static ISolidColorBrush NavajoWhite => KnownColor.NavajoWhite.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Navy"/> colored brush. /// </summary> public static ISolidColorBrush Navy => KnownColor.Navy.ToBrush(); /// <summary> /// Gets an <see cref="Colors.OldLace"/> colored brush. /// </summary> public static ISolidColorBrush OldLace => KnownColor.OldLace.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Olive"/> colored brush. /// </summary> public static ISolidColorBrush Olive => KnownColor.Olive.ToBrush(); /// <summary> /// Gets an <see cref="Colors.OliveDrab"/> colored brush. /// </summary> public static ISolidColorBrush OliveDrab => KnownColor.OliveDrab.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Orange"/> colored brush. /// </summary> public static ISolidColorBrush Orange => KnownColor.Orange.ToBrush(); /// <summary> /// Gets an <see cref="Colors.OrangeRed"/> colored brush. /// </summary> public static ISolidColorBrush OrangeRed => KnownColor.OrangeRed.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Orchid"/> colored brush. /// </summary> public static ISolidColorBrush Orchid => KnownColor.Orchid.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PaleGoldenrod"/> colored brush. /// </summary> public static ISolidColorBrush PaleGoldenrod => KnownColor.PaleGoldenrod.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PaleGreen"/> colored brush. /// </summary> public static ISolidColorBrush PaleGreen => KnownColor.PaleGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PaleTurquoise"/> colored brush. /// </summary> public static ISolidColorBrush PaleTurquoise => KnownColor.PaleTurquoise.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PaleVioletRed"/> colored brush. /// </summary> public static ISolidColorBrush PaleVioletRed => KnownColor.PaleVioletRed.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PapayaWhip"/> colored brush. /// </summary> public static ISolidColorBrush PapayaWhip => KnownColor.PapayaWhip.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PeachPuff"/> colored brush. /// </summary> public static ISolidColorBrush PeachPuff => KnownColor.PeachPuff.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Peru"/> colored brush. /// </summary> public static ISolidColorBrush Peru => KnownColor.Peru.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Pink"/> colored brush. /// </summary> public static ISolidColorBrush Pink => KnownColor.Pink.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Plum"/> colored brush. /// </summary> public static ISolidColorBrush Plum => KnownColor.Plum.ToBrush(); /// <summary> /// Gets an <see cref="Colors.PowderBlue"/> colored brush. /// </summary> public static ISolidColorBrush PowderBlue => KnownColor.PowderBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Purple"/> colored brush. /// </summary> public static ISolidColorBrush Purple => KnownColor.Purple.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Red"/> colored brush. /// </summary> public static ISolidColorBrush Red => KnownColor.Red.ToBrush(); /// <summary> /// Gets an <see cref="Colors.RosyBrown"/> colored brush. /// </summary> public static ISolidColorBrush RosyBrown => KnownColor.RosyBrown.ToBrush(); /// <summary> /// Gets an <see cref="Colors.RoyalBlue"/> colored brush. /// </summary> public static ISolidColorBrush RoyalBlue => KnownColor.RoyalBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SaddleBrown"/> colored brush. /// </summary> public static ISolidColorBrush SaddleBrown => KnownColor.SaddleBrown.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Salmon"/> colored brush. /// </summary> public static ISolidColorBrush Salmon => KnownColor.Salmon.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SandyBrown"/> colored brush. /// </summary> public static ISolidColorBrush SandyBrown => KnownColor.SandyBrown.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SeaGreen"/> colored brush. /// </summary> public static ISolidColorBrush SeaGreen => KnownColor.SeaGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SeaShell"/> colored brush. /// </summary> public static ISolidColorBrush SeaShell => KnownColor.SeaShell.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Sienna"/> colored brush. /// </summary> public static ISolidColorBrush Sienna => KnownColor.Sienna.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Silver"/> colored brush. /// </summary> public static ISolidColorBrush Silver => KnownColor.Silver.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SkyBlue"/> colored brush. /// </summary> public static ISolidColorBrush SkyBlue => KnownColor.SkyBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SlateBlue"/> colored brush. /// </summary> public static ISolidColorBrush SlateBlue => KnownColor.SlateBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SlateGray"/> colored brush. /// </summary> public static ISolidColorBrush SlateGray => KnownColor.SlateGray.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Snow"/> colored brush. /// </summary> public static ISolidColorBrush Snow => KnownColor.Snow.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SpringGreen"/> colored brush. /// </summary> public static ISolidColorBrush SpringGreen => KnownColor.SpringGreen.ToBrush(); /// <summary> /// Gets an <see cref="Colors.SteelBlue"/> colored brush. /// </summary> public static ISolidColorBrush SteelBlue => KnownColor.SteelBlue.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Tan"/> colored brush. /// </summary> public static ISolidColorBrush Tan => KnownColor.Tan.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Teal"/> colored brush. /// </summary> public static ISolidColorBrush Teal => KnownColor.Teal.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Thistle"/> colored brush. /// </summary> public static ISolidColorBrush Thistle => KnownColor.Thistle.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Tomato"/> colored brush. /// </summary> public static ISolidColorBrush Tomato => KnownColor.Tomato.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Transparent"/> colored brush. /// </summary> public static ISolidColorBrush Transparent => KnownColor.Transparent.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Turquoise"/> colored brush. /// </summary> public static ISolidColorBrush Turquoise => KnownColor.Turquoise.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Violet"/> colored brush. /// </summary> public static ISolidColorBrush Violet => KnownColor.Violet.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Wheat"/> colored brush. /// </summary> public static ISolidColorBrush Wheat => KnownColor.Wheat.ToBrush(); /// <summary> /// Gets an <see cref="Colors.White"/> colored brush. /// </summary> public static ISolidColorBrush White => KnownColor.White.ToBrush(); /// <summary> /// Gets an <see cref="Colors.WhiteSmoke"/> colored brush. /// </summary> public static ISolidColorBrush WhiteSmoke => KnownColor.WhiteSmoke.ToBrush(); /// <summary> /// Gets an <see cref="Colors.Yellow"/> colored brush. /// </summary> public static ISolidColorBrush Yellow => KnownColor.Yellow.ToBrush(); /// <summary> /// Gets an <see cref="Colors.YellowGreen"/> colored brush. /// </summary> public static ISolidColorBrush YellowGreen => KnownColor.YellowGreen.ToBrush(); } }
#region WatiN Copyright (C) 2006-2009 Jeroen van Menen //Copyright 2006-2009 Jeroen van Menen // // 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 Copyright using System; using System.Collections; using System.Collections.Generic; using WatiN.Core.Comparers; using WatiN.Core.Constraints; using WatiN.Core.Interfaces; using WatiN.Core.Properties; using WatiN.Core.UtilityClasses; namespace WatiN.Core { /// <summary> /// Represents a read-only list of components that can be enumerated, searched and filtered. /// </summary> /// <typeparam name="TComponent">The component type</typeparam> /// <typeparam name="TCollection">The derived collection type</typeparam> public abstract class BaseComponentCollection<TComponent, TCollection> : IComponentCollection<TComponent> where TComponent : Component where TCollection : BaseComponentCollection<TComponent, TCollection> { private IList<TComponent> cache; /// <summary> /// Creates a base collection. /// </summary> protected BaseComponentCollection() { } /// <inheritdoc /> public virtual int Count { get { return Cache.Count; } } /// <inheritdoc /> public virtual void CopyTo(TComponent[] array, int arrayIndex) { Cache.CopyTo(array, arrayIndex); } /// <summary> /// Gets the element at the specified index in the collection. /// </summary> /// <param name="index">The zero-based index</param> /// <returns>The element</returns> public virtual TComponent this[int index] { get { return Cache[index]; } } /// <summary> /// Gets the number of elements in the collection. /// </summary> /// <value>The number of elements in the collection</value> [Obsolete("Use Count property instead.")] public virtual int Length { get { return Count; } } /// <inheritdoc /> public virtual bool Exists(Constraint findBy) { if (findBy == null) throw new ArgumentNullException("findBy"); var context = new ConstraintContext(); foreach (TComponent component in this) if (component.Matches(findBy, context)) return true; return false; } /// <inheritdoc /> public virtual bool Exists(Predicate<TComponent> predicate) { if (predicate == null) throw new ArgumentNullException("predicate"); return Exists(CreateConstraintFromPredicate(predicate)); } /// <inheritdoc /> public virtual TComponent First() { foreach (var component in this) return component; return null; } /// <inheritdoc /> public virtual TComponent First(Constraint findBy) { if (findBy == null) throw new ArgumentNullException("findBy"); var context = new ConstraintContext(); foreach (TComponent component in this) if (component.Matches(findBy, context)) return component; return null; } /// <inheritdoc /> public virtual TComponent First(Predicate<TComponent> predicate) { if (predicate == null) throw new ArgumentNullException("predicate"); return First(CreateConstraintFromPredicate(predicate)); } /// <summary> /// Returned a filtered view of the collection consisting only of the elements that /// match the given constraint. /// </summary> /// <param name="findBy">The constraint to match</param> /// <returns>The filtered element collection</returns> public virtual TCollection Filter(Constraint findBy) { if (findBy == null) throw new ArgumentNullException("findBy"); return CreateFilteredCollection(findBy); } /// <summary> /// Returned a filtered view of the collection consisting only of the elements that /// match the given predicate. /// </summary> /// <param name="predicate">The predicate to match</param> /// <returns>The filtered element collection</returns> public virtual TCollection Filter(Predicate<TComponent> predicate) { return Filter(CreateConstraintFromPredicate(predicate)); } /// <inheritdoc /> public virtual IEnumerator<TComponent> GetEnumerator() { return Cache.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Creates a filtered instance of the collection. /// </summary> /// <param name="findBy">The constraint, not null</param> /// <returns>The element collection</returns> protected abstract TCollection CreateFilteredCollection(Constraint findBy); /// <summary> /// Gets the elements of the collection. /// </summary> /// <returns>The collection elements</returns> protected abstract IEnumerable<TComponent> GetElements(); /// <summary> /// Creates a new constraint from a given component-based predicate. /// </summary> /// <param name="predicate">The predicate</param> /// <returns>The constraint</returns> protected Constraint CreateConstraintFromPredicate(Predicate<TComponent> predicate) { return new ComponentConstraint(new PredicateComparer<TComponent, Component>(predicate)); } /// <summary> /// Gets a lazily-populated list of all components within the collection. /// </summary> protected IList<TComponent> Cache { get { if (cache == null) cache = new LazyList<TComponent>(GetElements()); return cache; } } IComponentCollection<TComponent> IComponentCollection<TComponent>.Filter(Constraint findBy) { return Filter(findBy); } IComponentCollection<TComponent> IComponentCollection<TComponent>.Filter(Predicate<TComponent> predicate) { return Filter(predicate); } #region Hidden / Unsupported List Methods bool ICollection<TComponent>.IsReadOnly { get { return true; } } int IList<TComponent>.IndexOf(TComponent item) { ThrowCollectionDoesNotSupportSearchingByEquality(); return 0; } bool ICollection<TComponent>.Contains(TComponent item) { ThrowCollectionDoesNotSupportSearchingByEquality(); return false; } void IList<TComponent>.Insert(int index, TComponent item) { ThrowCollectionIsReadOnly(); } void IList<TComponent>.RemoveAt(int index) { ThrowCollectionIsReadOnly(); } TComponent IList<TComponent>.this[int index] { get { return this[index]; } set { ThrowCollectionIsReadOnly(); } } void ICollection<TComponent>.Add(TComponent item) { ThrowCollectionIsReadOnly(); } void ICollection<TComponent>.Clear() { ThrowCollectionIsReadOnly(); } bool ICollection<TComponent>.Remove(TComponent item) { ThrowCollectionIsReadOnly(); return false; } private static void ThrowCollectionDoesNotSupportSearchingByEquality() { throw new NotSupportedException(Resources.BaseComponentCollection_DoesNotSupportSearchingByEquality); } private static void ThrowCollectionIsReadOnly() { throw new NotSupportedException(Resources.BaseComponentCollection_CollectionIsReadonly); } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using Msbuild.Tests.Utilities; using System; using System.IO; using Xunit; namespace Microsoft.DotNet.Cli.Remove.Reference.Tests { public class GivenDotnetRemoveReference : TestBase { private const string HelpText = @".NET Remove Project to Project reference Command Usage: dotnet remove <PROJECT> reference [options] [args] Arguments: <PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one. Options: -h|--help Show help information -f|--framework <FRAMEWORK> Remove reference only when targetting a specific framework Additional Arguments: Project to project references to remove "; const string FrameworkNet451Arg = "-f net451"; const string ConditionFrameworkNet451 = "== 'net451'"; const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0"; const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'"; static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" }; private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "") { return new TestSetup( TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName) .CreateInstance(callingMethod: callingMethod, identifier: identifier) .WithSourceFiles() .Root .FullName); } private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { return new ProjDir(TestAssetsManager.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).Path); } private ProjDir NewLib([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var dir = NewDir(callingMethod: callingMethod, identifier: identifier); try { string newArgs = $"classlib -o \"{dir.Path}\""; new NewCommandShim() .WithWorkingDirectory(dir.Path) .ExecuteWithCapturedOutput(newArgs) .Should().Pass(); } catch (System.ComponentModel.Win32Exception e) { throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{dir.Path}`\nException:\n{e}"); } return dir; } private static void SetTargetFrameworks(ProjDir proj, string[] frameworks) { var csproj = proj.CsProj(); csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks)); csproj.Save(); } private ProjDir NewLibWithFrameworks([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var ret = NewLib(callingMethod: callingMethod, identifier: identifier); SetTargetFrameworks(ret, DefaultFrameworks); return ret; } private ProjDir GetLibRef(TestSetup setup) { return new ProjDir(setup.LibDir); } private ProjDir AddLibRef(TestSetup setup, ProjDir proj, string additionalArgs = "") { var ret = GetLibRef(setup); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"{additionalArgs} \"{ret.CsProjPath}\"") .Should().Pass(); return ret; } private ProjDir AddValidRef(TestSetup setup, ProjDir proj, string frameworkArg = "") { var ret = new ProjDir(setup.ValidRefDir); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"{frameworkArg} \"{ret.CsProjPath}\"") .Should().Pass(); return ret; } [Theory] [InlineData("--help")] [InlineData("-h")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new RemoveReferenceCommand().Execute(helpArg); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"remove {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new AddReferenceCommand() .WithProject("one two three") .Execute("proj.csproj"); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be("Unrecognized command or argument 'two'"); cmd.StdOut.Should().Be("Specify --help for a list of available options and commands."); } [Theory] [InlineData("idontexist.csproj")] [InlineData("ihave?inv@lid/char\\acters")] public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName) { var setup = Setup(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find project or directory `{projName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage() { string projName = "Broken/Broken.csproj"; var setup = Setup(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be("Project `Broken/Broken.csproj` is invalid."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne"); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(workingDir) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Found more than one project in `{workingDir + Path.DirectorySeparatorChar}`. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find any project in `{setup.TestRoot + Path.DirectorySeparatorChar}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void ItRemovesRefWithoutCondAndPrintsStatus() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = AddLibRef(setup, lib); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void ItRemovesRefWithCondAndPrintsStatus() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = AddLibRef(setup, lib, FrameworkNet451Arg); int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(libref.Name, ConditionFrameworkNet451).Should().Be(0); } [Fact] public void WhenTwoDifferentRefsArePresentItDoesNotRemoveBoth() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = AddLibRef(setup, lib); var validref = AddValidRef(setup, lib); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void WhenRefWithoutCondIsNotThereItPrintsMessage() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = GetLibRef(setup); string csprojContetntBefore = lib.CsProjContent(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{libref.CsProjPath}` could not be found."); lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore); } [Fact] public void WhenRefWithCondIsNotThereItPrintsMessage() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = GetLibRef(setup); string csprojContetntBefore = lib.CsProjContent(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{libref.CsProjPath}` could not be found."); lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore); } [Fact] public void WhenRefWithAndWithoutCondArePresentAndRemovingNoCondItDoesNotRemoveOther() { var lib = NewLibWithFrameworks(); var setup = Setup(); var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg); var librefNoCond = AddLibRef(setup, lib); var csprojBefore = lib.CsProj(); int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition(); int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{librefNoCond.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(0); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenRefWithAndWithoutCondArePresentAndRemovingCondItDoesNotRemoveOther() { var lib = NewLibWithFrameworks(); var setup = Setup(); var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg); var librefNoCond = AddLibRef(setup, lib); var csprojBefore = lib.CsProj(); int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition(); int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{librefCond.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore); csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(1); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(0); } [Fact] public void WhenRefWithDifferentCondIsPresentItDoesNotRemoveIt() { var lib = NewLibWithFrameworks(); var setup = Setup(); var librefCondNet451 = AddLibRef(setup, lib, FrameworkNet451Arg); var librefCondNetCoreApp10 = AddLibRef(setup, lib, FrameworkNetCoreApp10Arg); var csprojBefore = lib.CsProj(); int condNet451Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); int condNetCoreApp10Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{librefCondNet451.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condNet451Before - 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNet451.Name, ConditionFrameworkNet451).Should().Be(0); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10).Should().Be(condNetCoreApp10Before); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNetCoreApp10.Name, ConditionFrameworkNetCoreApp10).Should().Be(1); } [Fact] public void WhenDuplicateReferencesArePresentItRemovesThemAll() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithDoubledRef")); var libref = GetLibRef(setup); string removedText = $@"Project reference `{setup.LibCsprojRelPath}` removed. Project reference `{setup.LibCsprojRelPath}` removed."; int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"\"{libref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(removedText); var csproj = proj.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void WhenPassingRefWithRelPathItRemovesRefWithAbsolutePath() { var setup = Setup(); var lib = GetLibRef(setup); var libref = AddValidRef(setup, lib); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(lib.Path) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void WhenPassingRefWithRelPathToProjectItRemovesRefWithPathRelToProject() { var setup = Setup(); var lib = GetLibRef(setup); var libref = AddValidRef(setup, lib); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void WhenPassingRefWithAbsolutePathItRemovesRefWithRelPath() { var setup = Setup(); var lib = GetLibRef(setup); var libref = AddValidRef(setup, lib); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); } [Fact] public void WhenPassingMultipleReferencesItRemovesThemAll() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = AddLibRef(setup, lib); var validref = AddValidRef(setup, lib); string outputText = $@"Project reference `{Path.Combine(TestSetup.ProjectName, "Lib", setup.LibCsprojName)}` removed. Project reference `{Path.Combine(TestSetup.ProjectName, setup.ValidRefCsprojRelPath)}` removed."; int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0); csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0); } [Fact] public void WhenPassingMultipleReferencesAndOneOfThemDoesNotExistItRemovesOne() { var lib = NewLibWithFrameworks(); var setup = Setup(); var libref = GetLibRef(setup); var validref = AddValidRef(setup, lib); string OutputText = $@"Project reference `{setup.LibCsprojPath}` could not be found. Project reference `{Path.Combine(TestSetup.ProjectName, setup.ValidRefCsprojRelPath)}` removed."; int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new RemoveReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1); csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0); } } }