context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Schema { internal class JsonSchemaBuilder { private JsonReader _reader; private readonly IList<JsonSchema> _stack; private readonly JsonSchemaResolver _resolver; private JsonSchema _currentSchema; private void Push(JsonSchema value) { _currentSchema = value; _stack.Add(value); _resolver.LoadedSchemas.Add(value); } private JsonSchema Pop() { JsonSchema poppedSchema = _currentSchema; _stack.RemoveAt(_stack.Count - 1); _currentSchema = _stack.LastOrDefault(); return poppedSchema; } private JsonSchema CurrentSchema { get { return _currentSchema; } } public JsonSchemaBuilder(JsonSchemaResolver resolver) { _stack = new List<JsonSchema>(); _resolver = resolver; } internal JsonSchema Parse(JsonReader reader) { _reader = reader; if (reader.TokenType == JsonToken.None) _reader.Read(); return BuildSchema(); } private JsonSchema BuildSchema() { if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); _reader.Read(); // empty schema object if (_reader.TokenType == JsonToken.EndObject) { Push(new JsonSchema()); return Pop(); } string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); // schema reference if (propertyName == JsonSchemaConstants.ReferencePropertyName) { string id = (string)_reader.Value; // skip to the end of the current object while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { if (_reader.TokenType == JsonToken.StartObject) throw new Exception("Found StartObject within the schema reference with the Id '{0}'" .FormatWith(CultureInfo.InvariantCulture, id)); } JsonSchema referencedSchema = _resolver.GetSchema(id); if (referencedSchema == null) throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id)); return referencedSchema; } // regular ol' schema object Push(new JsonSchema()); ProcessSchemaProperty(propertyName); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); ProcessSchemaProperty(propertyName); } return Pop(); } private void ProcessSchemaProperty(string propertyName) { switch (propertyName) { case JsonSchemaConstants.TypePropertyName: CurrentSchema.Type = ProcessType(); break; case JsonSchemaConstants.IdPropertyName: CurrentSchema.Id = (string) _reader.Value; break; case JsonSchemaConstants.TitlePropertyName: CurrentSchema.Title = (string) _reader.Value; break; case JsonSchemaConstants.DescriptionPropertyName: CurrentSchema.Description = (string)_reader.Value; break; case JsonSchemaConstants.PropertiesPropertyName: ProcessProperties(); break; case JsonSchemaConstants.ItemsPropertyName: ProcessItems(); break; case JsonSchemaConstants.AdditionalPropertiesPropertyName: ProcessAdditionalProperties(); break; case JsonSchemaConstants.PatternPropertiesPropertyName: ProcessPatternProperties(); break; case JsonSchemaConstants.RequiredPropertyName: CurrentSchema.Required = (bool)_reader.Value; break; case JsonSchemaConstants.RequiresPropertyName: CurrentSchema.Requires = (string) _reader.Value; break; case JsonSchemaConstants.IdentityPropertyName: ProcessIdentity(); break; case JsonSchemaConstants.MinimumPropertyName: CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MaximumPropertyName: CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.ExclusiveMinimumPropertyName: CurrentSchema.ExclusiveMinimum = (bool)_reader.Value; break; case JsonSchemaConstants.ExclusiveMaximumPropertyName: CurrentSchema.ExclusiveMaximum = (bool)_reader.Value; break; case JsonSchemaConstants.MaximumLengthPropertyName: CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MinimumLengthPropertyName: CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MaximumItemsPropertyName: CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MinimumItemsPropertyName: CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.DivisibleByPropertyName: CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.DisallowPropertyName: CurrentSchema.Disallow = ProcessType(); break; case JsonSchemaConstants.DefaultPropertyName: ProcessDefault(); break; case JsonSchemaConstants.HiddenPropertyName: CurrentSchema.Hidden = (bool) _reader.Value; break; case JsonSchemaConstants.ReadOnlyPropertyName: CurrentSchema.ReadOnly = (bool) _reader.Value; break; case JsonSchemaConstants.FormatPropertyName: CurrentSchema.Format = (string) _reader.Value; break; case JsonSchemaConstants.PatternPropertyName: CurrentSchema.Pattern = (string) _reader.Value; break; case JsonSchemaConstants.OptionsPropertyName: ProcessOptions(); break; case JsonSchemaConstants.EnumPropertyName: ProcessEnum(); break; case JsonSchemaConstants.ExtendsPropertyName: ProcessExtends(); break; default: _reader.Skip(); break; } } private void ProcessExtends() { CurrentSchema.Extends = BuildSchema(); } private void ProcessEnum() { if (_reader.TokenType != JsonToken.StartArray) throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Enum = new List<JToken>(); while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { JToken value = JToken.ReadFrom(_reader); CurrentSchema.Enum.Add(value); } } private void ProcessOptions() { CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer()); switch (_reader.TokenType) { case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); string label = null; JToken value = null; while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); switch (propertyName) { case JsonSchemaConstants.OptionValuePropertyName: value = JToken.ReadFrom(_reader); break; case JsonSchemaConstants.OptionLabelPropertyName: label = (string) _reader.Value; break; default: throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } } if (value == null) throw new Exception("No value specified for JSON schema option."); if (CurrentSchema.Options.ContainsKey(value)) throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value)); CurrentSchema.Options.Add(value, label); } break; default: throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessDefault() { CurrentSchema.Default = JToken.ReadFrom(_reader); } private void ProcessIdentity() { CurrentSchema.Identity = new List<string>(); switch (_reader.TokenType) { case JsonToken.String: CurrentSchema.Identity.Add(_reader.Value.ToString()); break; case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Identity.Add(_reader.Value.ToString()); } break; default: throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessAdditionalProperties() { if (_reader.TokenType == JsonToken.Boolean) CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value; else CurrentSchema.AdditionalProperties = BuildSchema(); } private void ProcessPatternProperties() { Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>(); if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected start object token."); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); if (patternProperties.ContainsKey(propertyName)) throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); patternProperties.Add(propertyName, BuildSchema()); } CurrentSchema.PatternProperties = patternProperties; } private void ProcessItems() { CurrentSchema.Items = new List<JsonSchema>(); switch (_reader.TokenType) { case JsonToken.StartObject: CurrentSchema.Items.Add(BuildSchema()); break; case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { CurrentSchema.Items.Add(BuildSchema()); } break; default: throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessProperties() { IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>(); if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); if (properties.ContainsKey(propertyName)) throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); properties.Add(propertyName, BuildSchema()); } CurrentSchema.Properties = properties; } private JsonSchemaType? ProcessType() { switch (_reader.TokenType) { case JsonToken.String: return MapType(_reader.Value.ToString()); case JsonToken.StartArray: // ensure type is in blank state before ORing values JsonSchemaType? type = JsonSchemaType.None; while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); type = type | MapType(_reader.Value.ToString()); } return type; default: throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } internal static JsonSchemaType MapType(string type) { JsonSchemaType mappedType; if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); return mappedType; } internal static string MapType(JsonSchemaType type) { return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using NHibernate; using NHibernate.Criterion; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.NHibernate { public class NHibernateInventoryData: IInventoryDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private NHibernateManager manager; public NHibernateManager Manager { get { return manager; } } /// <summary> /// The plugin being loaded /// </summary> /// <returns>A string containing the plugin name</returns> public string Name { get { return "NHibernate Inventory Data Interface"; } } /// <summary> /// The plugins version /// </summary> /// <returns>A string containing the plugin version</returns> public string Version { get { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } public void Initialise() { m_log.Info("[NHibernateInventoryData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException (Name); } /// <summary> /// Initialises the interface /// </summary> public void Initialise(string connect) { m_log.InfoFormat("[NHIBERNATE] Initializing NHibernateInventoryData"); manager = new NHibernateManager(connect, "InventoryStore"); } /// <summary> /// Closes the interface /// </summary> public void Dispose() { } /***************************************************************** * * Basic CRUD operations on Data * ****************************************************************/ // READ /// <summary> /// Returns an inventory item by its UUID /// </summary> /// <param name="item">The UUID of the item to be returned</param> /// <returns>A class containing item information</returns> public InventoryItemBase getInventoryItem(UUID item) { try { m_log.InfoFormat("[NHIBERNATE] getInventoryItem {0}", item); return (InventoryItemBase)manager.Get(typeof(InventoryItemBase), item); } catch { m_log.ErrorFormat("Couldn't find inventory item: {0}", item); return null; } } /// <summary> /// Creates a new inventory item based on item /// </summary> /// <param name="item">The item to be created</param> public void addInventoryItem(InventoryItemBase item) { if (!ExistsItem(item.ID)) { manager.Insert(item); } else { m_log.ErrorFormat("[NHIBERNATE] Attempted to add Inventory Item {0} that already exists, updating instead", item.ID); updateInventoryItem(item); } } /// <summary> /// Updates an inventory item with item (updates based on ID) /// </summary> /// <param name="item">The updated item</param> public void updateInventoryItem(InventoryItemBase item) { if (ExistsItem(item.ID)) { manager.Update(item); } else { m_log.ErrorFormat("[NHIBERNATE] Attempted to add Inventory Item {0} that already exists", item.ID); } } /// <summary> /// /// </summary> /// <param name="item"></param> public void deleteInventoryItem(UUID itemID) { InventoryItemBase item = (InventoryItemBase)manager.Get(typeof(InventoryItemBase), itemID); if (item != null) { manager.Delete(item); } else { m_log.ErrorFormat("[NHIBERNATE] Error deleting InventoryItemBase {0}", itemID); } } public InventoryItemBase queryInventoryItem(UUID itemID) { return null; } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return null; } /// <summary> /// Returns an inventory folder by its UUID /// </summary> /// <param name="folder">The UUID of the folder to be returned</param> /// <returns>A class containing folder information</returns> public InventoryFolderBase getInventoryFolder(UUID folder) { try { return (InventoryFolderBase)manager.Get(typeof(InventoryFolderBase), folder); } catch { m_log.ErrorFormat("[NHIBERNATE] Couldn't find inventory item: {0}", folder); return null; } } /// <summary> /// Creates a new inventory folder based on folder /// </summary> /// <param name="folder">The folder to be created</param> public void addInventoryFolder(InventoryFolderBase folder) { if (!ExistsFolder(folder.ID)) { manager.Insert(folder); } else { m_log.ErrorFormat("[NHIBERNATE] Attempted to add Inventory Folder {0} that already exists, updating instead", folder.ID); updateInventoryFolder(folder); } } /// <summary> /// Updates an inventory folder with folder (updates based on ID) /// </summary> /// <param name="folder">The updated folder</param> public void updateInventoryFolder(InventoryFolderBase folder) { if (ExistsFolder(folder.ID)) { manager.Update(folder); } else { m_log.ErrorFormat("[NHIBERNATE] Attempted to add Inventory Folder {0} that already exists", folder.ID); } } /// <summary> /// /// </summary> /// <param name="folder"></param> public void deleteInventoryFolder(UUID folderID) { InventoryFolderBase item = (InventoryFolderBase)manager.Get(typeof(InventoryFolderBase), folderID); if (item != null) { manager.Delete(item); } else { m_log.ErrorFormat("[NHIBERNATE] Error deleting InventoryFolderBase {0}", folderID); } manager.Delete(folderID); } // useful private methods private bool ExistsItem(UUID uuid) { return (getInventoryItem(uuid) != null) ? true : false; } private bool ExistsFolder(UUID uuid) { return (getInventoryFolder(uuid) != null) ? true : false; } public void Shutdown() { // TODO: DataSet commit } // Move seems to be just update public void moveInventoryFolder(InventoryFolderBase folder) { updateInventoryFolder(folder); } public void moveInventoryItem(InventoryItemBase item) { updateInventoryItem(item); } /// <summary> /// Returns a list of inventory items contained within the specified folder /// </summary> /// <param name="folderID">The UUID of the target folder</param> /// <returns>A List of InventoryItemBase items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { // try { ICriteria criteria = manager.GetSession().CreateCriteria(typeof(InventoryItemBase)); criteria.Add(Expression.Eq("Folder", folderID)); List<InventoryItemBase> list = new List<InventoryItemBase>(); foreach (InventoryItemBase item in criteria.List()) { list.Add(item); } return list; // } // catch // { // return new List<InventoryItemBase>(); // } } public List<InventoryFolderBase> getUserRootFolders(UUID user) { return new List<InventoryFolderBase>(); } // see InventoryItemBase.getUserRootFolder public InventoryFolderBase getUserRootFolder(UUID user) { ICriteria criteria = manager.GetSession().CreateCriteria(typeof(InventoryFolderBase)); criteria.Add(Expression.Eq("ParentID", UUID.Zero)); criteria.Add(Expression.Eq("Owner", user)); foreach (InventoryFolderBase folder in criteria.List()) { return folder; } m_log.ErrorFormat("No Inventory Root Folder Found for: {0}", user); return null; } /// <summary> /// Append a list of all the child folders of a parent folder /// </summary> /// <param name="folders">list where folders will be appended</param> /// <param name="parentID">ID of parent</param> private void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID) { ICriteria criteria = manager.GetSession().CreateCriteria(typeof(InventoryFolderBase)); criteria.Add(Expression.Eq("ParentID", parentID)); foreach (InventoryFolderBase item in criteria.List()) { folders.Add(item); } } /// <summary> /// Returns a list of inventory folders contained in the folder 'parentID' /// </summary> /// <param name="parentID">The folder to get subfolders for</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); getInventoryFolders(ref folders, parentID); return folders; } // See IInventoryDataPlugin public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { if (parentID == UUID.Zero) { // Zero UUID is not a real parent folder. return new List<InventoryFolderBase>(); } List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); getInventoryFolders(ref folders, parentID); for (int i = 0; i < folders.Count; i++) getInventoryFolders(ref folders, folders[i].ID); return folders; } public List<InventoryItemBase> fetchActiveGestures (UUID avatarID) { return null; } } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F08_Region (editable child object).<br/> /// This is a generated base class of <see cref="F08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="F09_CityObjects"/> of type <see cref="F09_CityColl"/> (1:M relation to <see cref="F10_City"/>)<br/> /// This class is an item of <see cref="F07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class F08_Region : BusinessBase<F08_Region> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Country_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID"); /// <summary> /// Gets the Regions ID. /// </summary> /// <value>The Regions ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name"); /// <summary> /// Gets or sets the Regions Name. /// </summary> /// <value>The Regions Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<F09_Region_Child> F09_Region_SingleObjectProperty = RegisterProperty<F09_Region_Child>(p => p.F09_Region_SingleObject, "F09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the F09 Region Single Object ("parent load" child property). /// </summary> /// <value>The F09 Region Single Object.</value> public F09_Region_Child F09_Region_SingleObject { get { return GetProperty(F09_Region_SingleObjectProperty); } private set { LoadProperty(F09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<F09_Region_ReChild> F09_Region_ASingleObjectProperty = RegisterProperty<F09_Region_ReChild>(p => p.F09_Region_ASingleObject, "F09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the F09 Region ASingle Object ("parent load" child property). /// </summary> /// <value>The F09 Region ASingle Object.</value> public F09_Region_ReChild F09_Region_ASingleObject { get { return GetProperty(F09_Region_ASingleObjectProperty); } private set { LoadProperty(F09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<F09_CityColl> F09_CityObjectsProperty = RegisterProperty<F09_CityColl>(p => p.F09_CityObjects, "F09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the F09 City Objects ("parent load" child property). /// </summary> /// <value>The F09 City Objects.</value> public F09_CityColl F09_CityObjects { get { return GetProperty(F09_CityObjectsProperty); } private set { LoadProperty(F09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="F08_Region"/> object.</returns> internal static F08_Region NewF08_Region() { return DataPortal.CreateChild<F08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="F08_Region"/> object from the given F08_RegionDto. /// </summary> /// <param name="data">The <see cref="F08_RegionDto"/>.</param> /// <returns>A reference to the fetched <see cref="F08_Region"/> object.</returns> internal static F08_Region GetF08_Region(F08_RegionDto data) { F08_Region obj = new F08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.LoadProperty(F09_CityObjectsProperty, F09_CityColl.NewF09_CityColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(F09_Region_SingleObjectProperty, DataPortal.CreateChild<F09_Region_Child>()); LoadProperty(F09_Region_ASingleObjectProperty, DataPortal.CreateChild<F09_Region_ReChild>()); LoadProperty(F09_CityObjectsProperty, DataPortal.CreateChild<F09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F08_Region"/> object from the given <see cref="F08_RegionDto"/>. /// </summary> /// <param name="data">The F08_RegionDto to use.</param> private void Fetch(F08_RegionDto data) { // Value properties LoadProperty(Region_IDProperty, data.Region_ID); LoadProperty(Region_NameProperty, data.Region_Name); // parent properties parent_Country_ID = data.Parent_Country_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Loads child <see cref="F09_Region_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F09_Region_Child child) { LoadProperty(F09_Region_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="F09_Region_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F09_Region_ReChild child) { LoadProperty(F09_Region_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="F08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F06_Country parent) { var dto = new F08_RegionDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Region_Name = Region_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IF08_RegionDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(Region_IDProperty, resultDto.Region_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="F08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new F08_RegionDto(); dto.Region_ID = Region_ID; dto.Region_Name = Region_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IF08_RegionDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="F08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IF08_RegionDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Region_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using System.Web; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Blogger; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class BloggerTestSuite : BaseLiveTestClass { /// <summary> /// test Uri for google calendarURI /// </summary> protected string bloggerURI; ////////////////////////////////////////////////////////////////////// /// <summary>default empty constructor</summary> ////////////////////////////////////////////////////////////////////// public BloggerTestSuite() { } ////////////////////////////////////////////////////////////////////// /// <summary>the setup method</summary> ////////////////////////////////////////////////////////////////////// [SetUp] public override void InitTest() { base.InitTest(); GDataGAuthRequestFactory authFactory = this.factory as GDataGAuthRequestFactory; if (authFactory != null) { authFactory.Handler = this.strAuthHandler; } FeedCleanup(this.bloggerURI, this.userName, this.passWord, VersionDefaults.Major); } ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// <summary>the end it all method</summary> ////////////////////////////////////////////////////////////////////// [TearDown] public override void EndTest() { Tracing.ExitTracing(); FeedCleanup(this.bloggerURI, this.userName, this.passWord, VersionDefaults.Major); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>private void ReadConfigFile()</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("bloggerURI")) { this.bloggerURI = (string) unitTestConfiguration["bloggerURI"]; Tracing.TraceInfo("Read bloggerURI value: " + this.bloggerURI); } } ///////////////////////////////////////////////////////////////////////////// public override string ServiceName { get { return "blogger"; } } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void GoogleAuthenticationTest() { Tracing.TraceMsg("Entering Blogger AuthenticationTest"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); int iCount; if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); BloggerFeed blogFeed = service.Query(query); ObjectModelHelper.DumpAtomObject(blogFeed,CreateDumpFileName("AuthenticationTest")); iCount = blogFeed.Entries.Count; String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (blogFeed != null && blogFeed.Entries.Count > 0) { BloggerEntry entry = ObjectModelHelper.CreateAtomEntry(1) as BloggerEntry; // blogger does not like labels yet. entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Categories.Clear(); entry.IsDraft = true; entry.Updated = Utilities.EmptyDate; entry.Published = Utilities.EmptyDate; BloggerEntry newEntry = blogFeed.Insert(entry); iCount++; Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... BloggerQuery singleQuery = new BloggerQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); BloggerFeed newFeed = service.Query(singleQuery); BloggerEntry sameGuy = newFeed.Entries[0] as BloggerEntry; Tracing.TraceMsg("retrieved blogger entry"); Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.IsDraft); } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have one more entry, it has: " + blogFeed.Entries.Count); if (blogFeed != null && blogFeed.Entries.Count > 0) { // look for the one with dinner time... foreach (AtomEntry entry in blogFeed.Entries) { Tracing.TraceMsg("Entrie title: " + entry.Title.Text); if (String.Compare(entry.Title.Text, strTitle)==0) { entry.Content.Content = "Maybe stay until breakfast"; entry.Content.Type = "text"; entry.Update(); Tracing.TraceMsg("Updated entry"); } } } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have one more entry, it has: " + blogFeed.Entries.Count); if (blogFeed != null && blogFeed.Entries.Count > 0) { // look for the one with dinner time... foreach (AtomEntry entry in blogFeed.Entries) { Tracing.TraceMsg("Entrie title: " + entry.Title.Text); if (String.Compare(entry.Title.Text, strTitle)==0) { entry.Delete(); iCount--; Tracing.TraceMsg("deleted entry"); } } } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have the same count again, it has: " + blogFeed.Entries.Count); service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>checks for xhtml persistence</summary> ////////////////////////////////////////////////////////////////////// [Ignore ("Currently broken on the server")] [Test] public void BloggerXHTMLTest() { Tracing.TraceMsg("Entering BloggerXHTMLTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed feed = service.Query(query); String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (feed != null) { // get the first entry String xhtmlContent = "<div><b>this is an xhtml test text</b></div>"; AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Content.Type = "xhtml"; entry.Content.Content = xhtmlContent; AtomEntry newEntry = feed.Insert(entry); Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... FeedQuery singleQuery = new FeedQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); AtomFeed newFeed = service.Query(singleQuery); AtomEntry sameGuy = newFeed.Entries[0]; Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.Content.Type.Equals("xhtml")); Assert.IsTrue(sameGuy.Content.Content.Equals(xhtmlContent)); } service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>checks for xhtml persistence</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerHTMLTest() { Tracing.TraceMsg("Entering BloggerHTMLTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed feed = service.Query(query); String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (feed != null) { // get the first entry String htmlContent = "<div>&lt;b&gt;this is an html test text&lt;/b&gt;</div>"; AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Content.Type = "html"; entry.Content.Content = htmlContent; AtomEntry newEntry = feed.Insert(entry); Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... FeedQuery singleQuery = new FeedQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); AtomFeed newFeed = service.Query(singleQuery); AtomEntry sameGuy = newFeed.Entries[0]; Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.Content.Type.Equals("html")); String input = HttpUtility.HtmlDecode(htmlContent); String output = HttpUtility.HtmlDecode(sameGuy.Content.Content); Assert.IsTrue(input.Equals(output), "The input string should be equal the output string"); } service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests if we can access a public feed</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerPublicFeedTest() { Tracing.TraceMsg("Entering BloggerPublicFeedTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); String publicURI = (String) this.externalHosts[0]; if (publicURI != null) { service.RequestFactory = this.factory; query.Uri = new Uri(publicURI); AtomFeed feed = service.Query(query); if (feed != null) { // look for the one with dinner time... foreach (AtomEntry entry in feed.Entries) { Assert.IsTrue(entry.ReadOnly, "The entry should be readonly"); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests if we can access a public feed</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerVersion2Test() { Tracing.TraceMsg("Entering BloggerVersion2Test"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); string title = "V1" + Guid.NewGuid().ToString(); service.ProtocolMajor = 1; service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); // insert a new entry in version 1 AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = title; entry.IsDraft = true; entry.ProtocolMajor = 12; AtomEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry); Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor); Assert.IsTrue(entry.IsDraft); Assert.IsTrue(returnedEntry.IsDraft); BloggerFeed feed = service.Query(query); Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor); if (feed != null) { Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries"); Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries"); } service.ProtocolMajor = 2; feed = service.Query(query); Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor); if (feed != null) { Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries"); Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries"); foreach (BloggerEntry e in feed.Entries) { if (e.Title.Text == title) { Assert.IsTrue(e.ProtocolMajor == 2); Assert.IsTrue(e.IsDraft); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests the etag functionallity for updates</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerETagTest() { Tracing.TraceMsg("Entering BloggerETagTest"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); service.ProtocolMajor = 2; string title = "V1" + Guid.NewGuid().ToString(); service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); // insert a new entry in version 1 AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = title; entry.IsDraft = true; BloggerEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry) as BloggerEntry; Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor); Assert.IsTrue(entry.IsDraft); Assert.IsTrue(returnedEntry.IsDraft); Assert.IsTrue(returnedEntry.Etag != null); string etagOld = returnedEntry.Etag; returnedEntry.Content.Content = "This is a test"; BloggerEntry newEntry = returnedEntry.Update() as BloggerEntry; Assert.IsTrue(newEntry.Etag != null); Assert.IsTrue(newEntry.Etag != etagOld); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerStressTest() { Tracing.TraceMsg("Entering Blogger GoogleStressTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed blogFeed = service.Query(query); ObjectModelHelper.DumpAtomObject(blogFeed,CreateDumpFileName("AuthenticationTest")); if (blogFeed != null) { for (int i=0; i< 30; i++) { AtomEntry entry = ObjectModelHelper.CreateAtomEntry(i); entry.Categories.Clear(); entry.Title.Text = "Title " + i; entry.Content.Content = "Some text..."; entry.Content.Type = "html"; blogFeed.Insert(entry); } } } } ///////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////// }
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using MongoDB.Bson; using NUnit.Framework; namespace MongoDB.UnitTests.Bson { [TestFixture] public class TestBsonWriter : BsonTestBase { private char euro = '\u20ac'; private string WriteStringAndGetHex(string val) { var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); writer.Write(val, false); return BitConverter.ToString(ms.ToArray()); } [Test] public void TestCalculateSizeOfComplexDoc() { var doc = new Document(); doc.Add("a", "a"); doc.Add("b", 1); var sub = new Document().Add("c_1", 1).Add("c_2", DateTime.Now); doc.Add("c", sub); var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); Assert.AreEqual(51, writer.CalculateSizeObject(doc)); } [Test] public void TestCalculateSizeOfEmptyDoc() { var doc = new Document(); var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); Assert.AreEqual(5, writer.CalculateSizeObject(doc)); } [Test] public void TestCalculateSizeOfSimpleDoc() { var doc = new Document {{"a", "a"}, {"b", 1}}; var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); //BsonDocument bdoc = BsonConvert.From(doc); Assert.AreEqual(21, writer.CalculateSizeObject(doc)); } [Test] public void TestLocalDateTimeIsWrittenAsUtcTime() { var localtzoffset = TimeZoneInfo.Local.BaseUtcOffset.Hours; var dateTime = new DateTime(2010, 1, 1, 11, 0, 0, DateTimeKind.Local); var utcTime = new DateTime(2010, 1, 1, 11 - localtzoffset, 0, 0, DateTimeKind.Utc); var base64 = Serialize(new Document("time", dateTime)); var expected = Serialize(new Document("time", utcTime)); Assert.AreEqual(expected, base64); } [Test] public void TestNullsDontThrowExceptions() { var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); var doc = new Document().Add("n", null); try { writer.WriteObject(doc); } catch(NullReferenceException) { Assert.Fail("Null Reference Exception was thrown on trying to serialize a null value"); } } [Test] public void TestWriteArrayDoc() { const string expected = "2000000002300002000000610002310002000000620002320002000000630000"; var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); var str = new[] {"a", "b", "c"}; writer.WriteValue(BsonType.Array, str); var hexdump = BitConverter.ToString(ms.ToArray()); hexdump = hexdump.Replace("-", ""); Assert.AreEqual(expected, hexdump); } [Test] public void TestWriteDocument() { var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); const string expected = "1400000002746573740005000000746573740000"; var doc = new Document().Add("test", "test"); writer.WriteObject(doc); var hexdump = BitConverter.ToString(ms.ToArray()); hexdump = hexdump.Replace("-", ""); Assert.AreEqual(expected, hexdump); } [Test] public void TestWriteMultibyteString() { var val = new StringBuilder().Append(euro, 3).ToString(); var expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0')); Assert.AreEqual(expected, WriteStringAndGetHex(val)); } [Test] public void TestWriteMultibyteStringLong() { var val = new StringBuilder().Append("ww").Append(euro, 180).ToString(); var expected = BitConverter.ToString(Encoding.UTF8.GetBytes(val + '\0')); Assert.AreEqual(expected, WriteStringAndGetHex(val)); } [Test] public void TestWriteSingle() { var expected = "000000E0FFFFEF47"; var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); var val = Single.MaxValue; writer.WriteValue(BsonType.Number, val); var hexdump = BitConverter.ToString(ms.ToArray()); hexdump = hexdump.Replace("-", ""); Assert.AreEqual(expected, hexdump); } [Test] public void TestWriteString() { var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); const string expected = "54-65-73-74-73-2E-69-6E-73-65-72-74-73-00"; writer.Write("Tests.inserts", false); var hexdump = BitConverter.ToString(ms.ToArray()); Assert.AreEqual(expected, hexdump); } [Test] public void TestWriteSymbol() { var expected = "0700000073796D626F6C00"; var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); MongoSymbol val = "symbol"; Assert.IsTrue(String.IsInterned(val) != null); writer.WriteValue(BsonType.Symbol, val); var hexdump = BitConverter.ToString(ms.ToArray()).Replace("-", ""); Assert.AreEqual(expected, hexdump); } [Test] public void TestWriteUtcTimeByDefault() { var dateTime = new DateTime(2010, 1, 1, 10, 0, 0, DateTimeKind.Utc); var base64 = Serialize(new Document("time", dateTime)); Assert.AreEqual("EwAAAAl0aW1lAADJU+klAQAAAA==", base64); } [Test] [ExpectedException(typeof(ArgumentException), UserMessage = "Shouldn't be able to write large document")] public void TestWritingTooLargeDocument() { var ms = new MemoryStream(); var writer = new BsonWriter(ms, new BsonDocumentDescriptor()); var b = new Binary(new byte[BsonInfo.MaxDocumentSize]); var big = new Document().Add("x", b); writer.WriteObject(big); } [Test] public void TestWriteBytesAsBinary() { var bson = Serialize(new Document("bytes", new byte[] {10, 12})); Assert.AreEqual("FwAAAAVieXRlcwAGAAAAAgIAAAAKDAA=",bson); } [Test] public void TestWriteTimeSpanAsLong() { var span = TimeSpan.FromSeconds(123456); var bson = Serialize(new Document("span", span)); Assert.AreEqual("EwAAABJzcGFuAACggnEfAQAAAA==",bson); } [Test] public void TestWriteUriAsString() { var uri = new Uri("http://www.microsoft.com"); var bson = Serialize(new Document("uri", uri)); Assert.AreEqual("KAAAAAJ1cmkAGgAAAGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS8AAA==",bson); } [Test] public void TestWriteMongoRegex() { var regex = new MongoRegex("expression", MongoRegexOption.IgnoreCase | MongoRegexOption.IgnorePatternWhitespace | MongoRegexOption.Multiline); var bson = Serialize(new Document("regex", regex)); Assert.AreEqual("GwAAAAtyZWdleABleHByZXNzaW9uAGltZwAA",bson); } [Test] public void TestWriteNetRegex() { var regex = new Regex("expression", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline); var bson = Serialize(new Document("regex", regex)); Assert.AreEqual("GwAAAAtyZWdleABleHByZXNzaW9uAGltZwAA", bson); } [Test] public void TestCanWriteNagativeDates() { var bson = Serialize(new Document("date", new DateTime(1960, 1, 1))); Assert.AreEqual("EwAAAAlkYXRlAIBFaoO2////AA==",bson); } } }
#define SUPPORTS_XBOX_GAMEPADS #define SUPPORTS_TOUCH_SCREEN using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Gui; using Microsoft.Xna.Framework.Input; namespace FlatRedBall.Input { /// <summary> /// Containing functionality for keyboard, mouse, and joystick input. /// </summary> public static partial class InputManager { #region Fields static Dictionary<int, bool> mControllerConnectedStatus; #if SUPPORTS_XBOX_GAMEPADS static Xbox360GamePad[] mXbox360GamePads; #endif static bool mUpdateXbox360GamePads = true; static TouchScreen mTouchScreen; // The ClearInput method should not only // clear input for this frame, but it should // prevent pushes from happening next frame. To // do this properly, a variable needs to be set on // whether pushes should be ignored. However, this // variable will prevent pushes NEXT frame, not this // frame. So there will need to be two variables. One // which determines whether to ignore pushes this frame, // and one which will be used to set that variable - one that // determines whether to ignore pushes next frame. internal static bool mIgnorePushesNextFrame = false; internal static bool mIgnorePushesThisFrame = false; static bool mCurrentFrameInputSuspended; static Mouse mMouse; #region XML Docs /// <summary> /// Reference to an IInputReceiver which will have its ReceiveInput method called every frame. /// </summary> /// <remarks> /// If this reference is not null, the reference's ReceiveInput method is called in the InputManager.GetInputState method. /// <seealso cref="FlatRedBall.Gui.IInputReceiver"/> /// </remarks> #endregion static FlatRedBall.Gui.IInputReceiver mReceivingInput; // When a user clicks on an element which is an IInputReceiver, // it is set as the object which receieves input. Whenever the // user clicks the mouse, the InputManager's receivingInput gets set. // To prevent the immediate resetting of the receivingInput, this bool // is set to true, then resetted next frame. If this is true, ignore clicks // for setting the receivingInput to null; static bool mReceivingInputJustSet;// = false; static Keyboard mKeyboard; #endregion #region Properties public static int NumberOfConnectedGamePads { get { int count = 0; for (int i = 0; i < Xbox360GamePads.Length; i++) { if (Xbox360GamePads[i].IsConnected) { count++; } } return count; } } /// <summary> /// Whether to perform every-frame update logic on all gamepads. /// </summary> public static bool UpdateXbox360GamePads { get { return mUpdateXbox360GamePads; } set { mUpdateXbox360GamePads = value; } } #if SUPPORTS_XBOX_GAMEPADS /// <summary> /// Returns an array of Xbox360GamePads. /// </summary> /// <remarks> /// This name was created when the Xbox360 was the only controller type supported by XNA. Since then, many devices /// implement X Input, and newer hardware such as Xbox One also appear in this array when connected. /// </remarks> public static Xbox360GamePad[] Xbox360GamePads => mXbox360GamePads; static Xbox360GamePad[] mConnectedXbox360GamePads; public static Xbox360GamePad[] ConnectedXbox360GamePads => mConnectedXbox360GamePads; #endif public static TouchScreen TouchScreen => mTouchScreen; public static Mouse Mouse { get { return mMouse; } // Vic on December 6, 2009 said: // Do we need a setter for the mouse? // I don't think we do, and this may have // just been really old code that never got // wiped out. //set { mMouse = value; } } public static bool CurrentFrameInputSuspended { get { return mCurrentFrameInputSuspended; } set { mCurrentFrameInputSuspended = value; } } public static Keyboard Keyboard { get { return mKeyboard; } set { mKeyboard = value; } } public static IInputReceiverKeyboard InputReceiverKeyboard { get; set; } [Obsolete("Use the InputReceiver property instead")] public static IInputReceiver ReceivingInput { get { return InputReceiver; } set { InputReceiver = value; } } public static IInputReceiver InputReceiver { get { return mReceivingInput; } set { if (value != mReceivingInput) { // Set this to null to prevent IInputReceiver oldReceiver = mReceivingInput; mReceivingInput = value; if (oldReceiver != null) { oldReceiver.LoseFocus(); } } mReceivingInputJustSet = true; if (mReceivingInput != null) { mReceivingInput.OnGainFocus(); } } } public static bool ReceivingInputJustSet { get { return mReceivingInputJustSet; } set { mReceivingInputJustSet = value; } } public static bool BackPressed { get; internal set; } #endregion #region Events public class ControllerConnectionEventArgs : EventArgs { public ControllerConnectionEventArgs() : base() {} public ControllerConnectionEventArgs(int playerIndex, bool connected) : this() { PlayerIndex = playerIndex; Connected = connected; } /// <summary> /// The index of the gamepad which connected or disconnected. This is 0-based, so values are 0 to 3 inclusive. /// </summary> public int PlayerIndex { get; set; } /// <summary> /// Whether the gamepad was connected. If false, the gamepad was disconnected. /// </summary> public bool Connected { get; set; } } public delegate void ControllerConnectionHandler(object sender, ControllerConnectionEventArgs e); /// <summary> /// Event raised whenever an Xbox360Controller is connected or disonnected. /// </summary> public static event ControllerConnectionHandler ControllerConnectionEvent; #endregion #region Methods #region Public Methods static InputManager() { } public static void CheckControllerConnectionChange() { int padNumber; #if !MONODROID padNumber = 4; #else padNumber = 1; #endif for (int i = 0; i < padNumber; i++) { if (mXbox360GamePads[i].IsConnected != mControllerConnectedStatus[i]) { if (ControllerConnectionEvent != null) ControllerConnectionEvent(null, new ControllerConnectionEventArgs(i, mXbox360GamePads[i].IsConnected)); mControllerConnectedStatus[i] = mXbox360GamePads[i].IsConnected; mConnectedXbox360GamePads = Xbox360GamePads.Where(item => item.IsConnected).ToArray(); } } if(mConnectedXbox360GamePads == null) { mConnectedXbox360GamePads = Xbox360GamePads.Where(item => item.IsConnected).ToArray(); } } public static void BackHandled() { BackPressed = false; } public static void ClearAllInput() { Keyboard.Clear(); Mouse.Clear(); ClearXbox360GamePadInput(); mIgnorePushesNextFrame = true; } public static bool IsKeyConsumedByInputReceiver(Keys key) { return mReceivingInput != null && mReceivingInput.IgnoredKeys.Contains(key) == false; } // made public for unit tests public static void Initialize(IntPtr windowHandle) { mKeyboard = new Keyboard(); InputReceiverKeyboard = mKeyboard; mMouse = new Mouse(windowHandle); #if SUPPORTS_TOUCH_SCREEN InitializeTouchScreen(); #endif #if SUPPORTS_XBOX_GAMEPADS InitializeXbox360GamePads(); #endif } #endregion public static void Update() { mCurrentFrameInputSuspended = false; mIgnorePushesThisFrame = mIgnorePushesNextFrame; mIgnorePushesNextFrame = false; if (mMouse.Active) { mMouse.Update(TimeManager.SecondDifference, TimeManager.CurrentTime); } mKeyboard.Update(); UpdateInputReceiver(); #if SUPPORTS_TOUCH_SCREEN mTouchScreen.Update(); #endif #if SUPPORTS_XBOX_GAMEPADS PerformXbox360GamePadUpdate(); #endif } private static void UpdateInputReceiver() { // Need to call the ReceiveInput method after testing out typed keys // Nov 8, 2020 - now we disable input when the window has no focus. Not sure if we want to make that controlled by a variable if (InputReceiver != null && FlatRedBallServices.Game.IsActive) { InputReceiver.OnFocusUpdate(); // OnFocusUpdate could set the InputReceiver to null, so handle that: InputReceiver?.ReceiveInput(); if (Keyboard.AutomaticallyPushEventsToInputReceiver) { var shift = InputReceiverKeyboard.IsShiftDown; var ctrl = InputReceiverKeyboard.IsCtrlDown; var alt = InputReceiverKeyboard.IsAltDown; foreach (var key in InputReceiverKeyboard.KeysTyped) { InputManager.InputReceiver?.HandleKeyDown(key, shift, alt, ctrl); } var stringTyped = InputReceiverKeyboard.GetStringTyped(); if (stringTyped != null) { for (int i = 0; i < stringTyped.Length; i++) { // receiver could get nulled out by itself when something like enter is pressed InputReceiver?.HandleCharEntered(stringTyped[i]); } } } } } private static void InitializeTouchScreen() { mTouchScreen = new TouchScreen(); mTouchScreen.Initialize(); } private static void ClearXbox360GamePadInput() { #if SUPPORTS_XBOX_GAMEPADS for (int i = 0; i < mXbox360GamePads.Length; i++) { mXbox360GamePads[i].Clear(); } #endif } private static void InitializeXbox360GamePads() { #if SUPPORTS_XBOX_GAMEPADS mXbox360GamePads = new Xbox360GamePad[] { new Xbox360GamePad(Microsoft.Xna.Framework.PlayerIndex.One), new Xbox360GamePad(Microsoft.Xna.Framework.PlayerIndex.Two), new Xbox360GamePad(Microsoft.Xna.Framework.PlayerIndex.Three), new Xbox360GamePad(Microsoft.Xna.Framework.PlayerIndex.Four) }; #endif mControllerConnectedStatus = new Dictionary<int, bool>(); mControllerConnectedStatus.Add(0, false); mControllerConnectedStatus.Add(1, false); mControllerConnectedStatus.Add(2, false); mControllerConnectedStatus.Add(3, false); } static partial void PlatformSpecificXbox360GamePadUpdate(); private static void PerformXbox360GamePadUpdate() { // Dec 18, 2021 - why do we check this before making updates. // If we do it before, we'll miss the first frame of the game // if gamepads are connected: //CheckControllerConnectionChange(); if (mUpdateXbox360GamePads) { BackPressed = false; #if SUPPORTS_XBOX_GAMEPADS mXbox360GamePads[0].Update(); #if !MONODROID mXbox360GamePads[1].Update(); mXbox360GamePads[2].Update(); mXbox360GamePads[3].Update(); #endif #endif PlatformSpecificXbox360GamePadUpdate(); } CheckControllerConnectionChange(); } #endregion } }
using System; using Raksha.Crypto.Parameters; using Raksha.Crypto.Utilities; namespace Raksha.Crypto.Engines { /** * HC-256 is a software-efficient stream cipher created by Hongjun Wu. It * generates keystream from a 256-bit secret key and a 256-bit initialization * vector. * <p> * http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf * </p><p> * Its brother, HC-128, is a third phase candidate in the eStream contest. * The algorithm is patent-free. No attacks are known as of today (April 2007). * See * * http://www.ecrypt.eu.org/stream/hcp3.html * </p> */ public class HC256Engine : IStreamCipher { private uint[] p = new uint[1024]; private uint[] q = new uint[1024]; private uint cnt = 0; private uint Step() { uint j = cnt & 0x3FF; uint ret; if (cnt < 1024) { uint x = p[(j - 3 & 0x3FF)]; uint y = p[(j - 1023 & 0x3FF)]; p[j] += p[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + q[((x ^ y) & 0x3FF)]; x = p[(j - 12 & 0x3FF)]; ret = (q[x & 0xFF] + q[((x >> 8) & 0xFF) + 256] + q[((x >> 16) & 0xFF) + 512] + q[((x >> 24) & 0xFF) + 768]) ^ p[j]; } else { uint x = q[(j - 3 & 0x3FF)]; uint y = q[(j - 1023 & 0x3FF)]; q[j] += q[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + p[((x ^ y) & 0x3FF)]; x = q[(j - 12 & 0x3FF)]; ret = (p[x & 0xFF] + p[((x >> 8) & 0xFF) + 256] + p[((x >> 16) & 0xFF) + 512] + p[((x >> 24) & 0xFF) + 768]) ^ q[j]; } cnt = cnt + 1 & 0x7FF; return ret; } private byte[] key, iv; private bool initialised; private void Init() { if (key.Length != 32 && key.Length != 16) throw new ArgumentException("The key must be 128/256 bits long"); if (iv.Length < 16) throw new ArgumentException("The IV must be at least 128 bits long"); if (key.Length != 32) { byte[] k = new byte[32]; Array.Copy(key, 0, k, 0, key.Length); Array.Copy(key, 0, k, 16, key.Length); key = k; } if (iv.Length < 32) { byte[] newIV = new byte[32]; Array.Copy(iv, 0, newIV, 0, iv.Length); Array.Copy(iv, 0, newIV, iv.Length, newIV.Length - iv.Length); iv = newIV; } cnt = 0; uint[] w = new uint[2560]; for (int i = 0; i < 32; i++) { w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3))); } for (int i = 0; i < 32; i++) { w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3))); } for (uint i = 16; i < 2560; i++) { uint x = w[i - 2]; uint y = w[i - 15]; w[i] = (RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10)) + w[i - 7] + (RotateRight(y, 7) ^ RotateRight(y, 18) ^ (y >> 3)) + w[i - 16] + i; } Array.Copy(w, 512, p, 0, 1024); Array.Copy(w, 1536, q, 0, 1024); for (int i = 0; i < 4096; i++) { Step(); } cnt = 0; } public string AlgorithmName { get { return "HC-256"; } } /** * Initialise a HC-256 cipher. * * @param forEncryption whether or not we are for encryption. Irrelevant, as * encryption and decryption are the same. * @param params the parameters required to set up the cipher. * @throws ArgumentException if the params argument is * inappropriate (ie. the key is not 256 bit long). */ public void Init( bool forEncryption, ICipherParameters parameters) { ICipherParameters keyParam = parameters; if (parameters is ParametersWithIV) { iv = ((ParametersWithIV)parameters).GetIV(); keyParam = ((ParametersWithIV)parameters).Parameters; } else { iv = new byte[0]; } if (keyParam is KeyParameter) { key = ((KeyParameter)keyParam).GetKey(); Init(); } else { throw new ArgumentException( "Invalid parameter passed to HC256 init - " + parameters.GetType().Name, "parameters"); } initialised = true; } private byte[] buf = new byte[4]; private int idx = 0; private byte GetByte() { if (idx == 0) { Pack.UInt32_To_LE(Step(), buf); } byte ret = buf[idx]; idx = idx + 1 & 0x3; return ret; } public void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + len) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + len) > output.Length) throw new DataLengthException("output buffer too short"); for (int i = 0; i < len; i++) { output[outOff + i] = (byte)(input[inOff + i] ^ GetByte()); } } public void Reset() { idx = 0; Init(); } public byte ReturnByte(byte input) { return (byte)(input ^ GetByte()); } private static uint RotateRight(uint x, int bits) { return (x >> bits) | (x << -bits); } } }
using System; using System.Reflection; using ColossalFramework; using ICities; using TrafficManager.CustomAI; using TrafficManager.Traffic; using TrafficManager.TrafficLight; using TrafficManager.UI; using UnityEngine; using Object = UnityEngine.Object; namespace TrafficManager { public class LoadingExtension : LoadingExtensionBase { public static LoadingExtension Instance; public static bool IsPathManagerCompatibile = true; public CustomPathManager CustomPathManager { get; set; } public bool DespawnEnabled { get; set; } public bool DetourInited { get; set; } public bool NodeSimulationLoaded { get; set; } public RedirectCallsState[] RevertMethods { get; set; } public TrafficManagerMode ToolMode { get; set; } public TrafficLightTool TrafficLightTool { get; set; } public UIBase UI { get; set; } public LoadingExtension() { } public override void OnCreated(ILoading loading) { SelfDestruct.DestructOldInstances(this); base.OnCreated(loading); Log.Message("Setting ToolMode"); ToolMode = TrafficManagerMode.None; Log.Message("Init RevertMethods"); RevertMethods = new RedirectCallsState[8]; Log.Message("Setting Despawn to False"); DespawnEnabled = true; Log.Message("Init DetourInited"); DetourInited = false; Log.Message("Init Custom PathManager"); CustomPathManager = new CustomPathManager(); } public override void OnReleased() { base.OnReleased(); if (ToolMode != TrafficManagerMode.None) { ToolMode = TrafficManagerMode.None; UITrafficManager.UIState = UIState.None; DestroyTool(); } } public override void OnLevelLoaded(LoadMode mode) { Log.Message("OnLevelLoaded calling base method"); base.OnLevelLoaded(mode); Log.Message("OnLevelLoaded Returned from base, calling custom code."); switch (mode) { case LoadMode.NewGame: OnNewGame(); break; case LoadMode.LoadGame: OnLoaded(); break; } if (mode == LoadMode.NewGame || mode == LoadMode.LoadGame) { if (Instance == null) { Log.Message("Instance is NULL. Set Instance to this."); if (Singleton<PathManager>.instance.GetType() != typeof (PathManager)) { Log.Message("Traffic++ Detected. Disable Pathfinder"); IsPathManagerCompatibile = false; } Instance = this; } if (IsPathManagerCompatibile) { Log.Message("Pathfinder Compatible. Setting up CustomPathManager and SimManager."); var pathManagerInstance = typeof (Singleton<PathManager>).GetField("sInstance", BindingFlags.Static | BindingFlags.NonPublic); var stockPathManager = PathManager.instance; Log.Message($"Got stock PathManager instance {stockPathManager.GetName()}"); CustomPathManager = stockPathManager.gameObject.AddComponent<CustomPathManager>(); Log.Message("Added CustomPathManager to gameObject List"); if (CustomPathManager == null) { Log.Error("CustomPathManager null. Error creating it."); return; } CustomPathManager.UpdateWithPathManagerValues(stockPathManager); Log.Message("UpdateWithPathManagerValues success"); pathManagerInstance?.SetValue(null, CustomPathManager); Log.Message("Getting Current SimulationManager"); var simManager = typeof (SimulationManager).GetField("m_managers", BindingFlags.Static | BindingFlags.NonPublic)? .GetValue(null) as FastList<ISimulationManager>; Log.Message("Removing Stock PathManager"); simManager?.Remove(stockPathManager); Log.Message("Adding Custom PathManager"); simManager?.Add(CustomPathManager); Object.Destroy(stockPathManager, 10f); } Log.Message("Adding Controls to UI."); UI = ToolsModifierControl.toolController.gameObject.AddComponent<UIBase>(); TrafficPriority.LeftHandDrive = Singleton<SimulationManager>.instance.m_metaData.m_invertTraffic == SimulationMetaData.MetaBool.True; } } public override void OnLevelUnloading() { // TODO: revert detours base.OnLevelUnloading(); //if (Instance == null) //{ // Log.Message("Instance is NULL. Set Instance to this."); // if (Singleton<PathManager>.instance.GetType() != typeof(PathManager)) // { // Log.Message("Traffic++ Detected. Disable Pathfinder"); // IsPathManagerCompatibile = false; // } // Instance = this; //} //try //{ // RedirectionHelper.RevertRedirect(typeof(CarAI).GetMethod("CalculateSegmentPosition", // BindingFlags.NonPublic | BindingFlags.Instance, // null, // new[] // { // typeof (ushort), typeof (Vehicle).MakeByRefType(), typeof (PathUnit.Position), // typeof (PathUnit.Position), typeof (uint), typeof (byte), typeof (PathUnit.Position), // typeof (uint), typeof (byte), typeof (Vector3).MakeByRefType(), // typeof (Vector3).MakeByRefType(), typeof (float).MakeByRefType() // }, // null), LoadingExtension.Instance.RevertMethods[0]); // RedirectionHelper.RevertRedirect(typeof (RoadBaseAI).GetMethod("SimulationStep", // new[] {typeof (ushort), typeof (NetNode).MakeByRefType()}), // LoadingExtension.Instance.RevertMethods[1]); // Log.Message("Redirecting Human AI Calls"); // RedirectionHelper.RevertRedirect(typeof(HumanAI).GetMethod("CheckTrafficLights", // BindingFlags.NonPublic | BindingFlags.Instance, // null, // new[] { typeof(ushort), typeof(ushort) }, // null), // LoadingExtension.Instance.RevertMethods[2]); // if (IsPathManagerCompatibile) // { // RedirectionHelper.RevertRedirect( // typeof(CarAI).GetMethod("SimulationStep", // new[] { // typeof (ushort), // typeof (Vehicle).MakeByRefType(), // typeof (Vector3) // }), // Instance.RevertMethods[3]); // Log.Message("Redirecting PassengerCarAI Simulation Step Calls"); // RedirectionHelper.RevertRedirect( // typeof(PassengerCarAI).GetMethod("SimulationStep", // new[] { typeof(ushort), typeof(Vehicle).MakeByRefType(), typeof(Vector3) }), // Instance.RevertMethods[4]); // Log.Message("Redirecting CargoTruckAI Simulation Step Calls"); // RedirectionHelper.RevertRedirect( // typeof(CargoTruckAI).GetMethod("SimulationStep", // new[] { typeof(ushort), typeof(Vehicle).MakeByRefType(), typeof(Vector3) }), // Instance.RevertMethods[5]); // Log.Message("Redirection CarAI Calculate Segment Position calls for non-Traffic++"); // RedirectionHelper.RevertRedirect(typeof(CarAI).GetMethod("CalculateSegmentPosition", // BindingFlags.NonPublic | BindingFlags.Instance, // null, // new[] // { // typeof (ushort), typeof (Vehicle).MakeByRefType(), typeof (PathUnit.Position), // typeof (uint), // typeof (byte), typeof (Vector3).MakeByRefType(), typeof (Vector3).MakeByRefType(), // typeof (float).MakeByRefType() // }, // null), // Instance.RevertMethods[6]); // LoadingExtension.Instance.DetourInited = false; // Log.Message("Pathfinder Compatible. Setting up CustomPathManager and SimManager."); // var pathManagerInstance = typeof(Singleton<PathManager>).GetField("sInstance", // BindingFlags.Static | BindingFlags.NonPublic); // var stockPathManager = PathManager.instance; // CustomPathManager = stockPathManager.gameObject.GetComponent<CustomPathManager>(); // //CustomPathManager.UpdateWithPathManagerValues(stockPathManager); // pathManagerInstance?.SetValue(null, CustomPathManager); // Log.Message("Getting Current SimulationManager"); // var simManager = // typeof(SimulationManager).GetField("m_managers", BindingFlags.Static | BindingFlags.NonPublic)? // .GetValue(null) as FastList<ISimulationManager>; // Log.Message("Removing Stock PathManager"); // simManager?.Remove(CustomPathManager); // Log.Message("Adding Custom PathManager"); // simManager?.Add(stockPathManager); // } //} //catch (Exception e) //{ // Log.Error("Error unloading. " + e.Message); //} try { TrafficPriority.PrioritySegments.Clear(); CustomRoadAI.NodeDictionary.Clear(); TrafficLightsManual.ManualSegments.Clear(); TrafficLightsTimed.TimedScripts.Clear(); Instance.NodeSimulationLoaded = false; } catch (Exception e) { Log.Error("Exception unloading mod. " + e.Message); // ignored - prevents collision with other mods } } protected virtual void OnNewGame() { Log.Message("New Game Started"); } protected virtual void OnLoaded() { Log.Message("Loaded save game."); } public void SetToolMode(TrafficManagerMode mode) { if (mode == ToolMode) return; //UI.toolMode = mode; ToolMode = mode; if (mode != TrafficManagerMode.None) { DestroyTool(); EnableTool(); } else { DestroyTool(); } } public void EnableTool() { if (TrafficLightTool == null) { TrafficLightTool = ToolsModifierControl.toolController.gameObject.GetComponent<TrafficLightTool>() ?? ToolsModifierControl.toolController.gameObject.AddComponent<TrafficLightTool>(); } ToolsModifierControl.toolController.CurrentTool = TrafficLightTool; ToolsModifierControl.SetTool<TrafficLightTool>(); } private void DestroyTool() { if (TrafficLightTool != null) { ToolsModifierControl.toolController.CurrentTool = ToolsModifierControl.GetTool<DefaultTool>(); ToolsModifierControl.SetTool<DefaultTool>(); Object.Destroy(TrafficLightTool); TrafficLightTool = null; } } } }
using System; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Fields; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Links; using Sitecore.Resources.Media; namespace Glass.Mapper.Sc.DataMappers { /// <summary> /// Class SitecoreFieldImageMapper /// </summary> public class SitecoreFieldImageMapper : AbstractSitecoreFieldMapper { private IMediaUrlOptionsResolver _mediaUrlOptionsResolver; /// <summary> /// Initializes a new instance of the <see cref="SitecoreFieldImageMapper"/> class. /// </summary> public SitecoreFieldImageMapper(): this (new MediaUrlOptionsResolver()) { } public SitecoreFieldImageMapper(IMediaUrlOptionsResolver mediaUrlOptionsResolver) : base(typeof(Image)) { _mediaUrlOptionsResolver = mediaUrlOptionsResolver; } /// <summary> /// Gets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { if (field.Value.IsNullOrEmpty()) { return null; } Image img = new Image(); ImageField scImg = new ImageField(field); var mediaUrlOptions = _mediaUrlOptionsResolver.GetMediaUrlOptions(config.MediaUrlOptions); MapToImage(img, scImg, mediaUrlOptions); return img; } public static void MapToImage(Image img, ImageField field, MediaUrlOptions mediaUrlOptions) { int height = 0; int.TryParse(field.Height, out height); int width = 0; int.TryParse(field.Width, out width); int hSpace = 0; int.TryParse(field.HSpace, out hSpace); int vSpace = 0; int.TryParse(field.VSpace, out vSpace); img.Alt = field.Alt; img.Border = field.Border; img.Class = field.Class; img.Height = height; img.HSpace = hSpace; img.MediaId = field.MediaID.Guid; img.MediaExists = field.MediaItem != null; if (field.MediaItem != null) { img.Src = SitecoreVersionAbstractions.GetMediaUrl(field.MediaItem, mediaUrlOptions); var fieldTitle = field.MediaItem.Fields["Title"]; if (fieldTitle != null) img.Title = fieldTitle.Value; } img.VSpace = vSpace; img.Width = width; img.Language = field.MediaLanguage; } public static void MapToImage(Image img, MediaItem imageItem) { /* int height = 0; int.TryParse(imageItem..Height, out height); int width = 0; int.TryParse(imageItem.Width, out width); int hSpace = 0; int.TryParse(imageItem.HSpace, out hSpace); int vSpace = 0; int.TryParse(imageItem.VSpace, out vSpace);*/ img.Alt = imageItem.Alt; img.Title = imageItem.Title; // img.Border = imageItem.Border; // img.Class = imageItem.Class; // img.Height = height; // img.HSpace = hSpace; img.MediaId = imageItem.ID.Guid; img.Src = SitecoreVersionAbstractions.GetMediaUrl(imageItem); // img.VSpace = vSpace; // img.Width = width; } /// <summary> /// Sets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <exception cref="Glass.Mapper.MapperException">No item with ID {0}. Can not update Media Item field.Formatted(newId)</exception> public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { Image img = value as Image; var item = field.Item; if (field == null) return; ImageField scImg = new ImageField(field); MapToField(scImg, img, item); } public static void MapToField(ImageField field, Image image, Item item) { if (image == null) { field.Clear(); return; } if (field.MediaID.Guid != image.MediaId) { //this only handles empty guids, but do we need to remove the link before adding a new one? if (image.MediaId == Guid.Empty) { ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, field.MediaItem.Database.Name, field.MediaID, field.MediaItem.Paths.Path); field.RemoveLink(link); } else { ID newId = new ID(image.MediaId); Item target = item.Database.GetItem(newId); if (target != null) { field.MediaID = newId; ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); field.UpdateLink(link); } else throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId)); } } if (image.Height > 0) field.Height = image.Height.ToString(); if (image.Width > 0) field.Width = image.Width.ToString(); if (image.HSpace > 0) field.HSpace = image.HSpace.ToString(); if (image.VSpace > 0) field.VSpace = image.VSpace.ToString(); if (field.Alt.HasValue() || image.Alt.HasValue()) field.Alt = image.Alt ?? string.Empty; if (field.Border.HasValue() || image.Border.HasValue()) field.Border = image.Border ?? string.Empty; if (field.Class.HasValue() || image.Class.HasValue()) field.Class = image.Class ?? string.Empty; } /// <summary> /// Sets the field value. /// </summary> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.String.</returns> /// <exception cref="System.NotImplementedException"></exception> public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { throw new NotImplementedException(); } /// <summary> /// Gets the field value. /// </summary> /// <param name="fieldValue">The field value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> /// <exception cref="System.NotImplementedException"></exception> public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { var item = context.Service.Database.GetItem(new ID(fieldValue)); if (item == null) { return null; } var imageItem = new MediaItem(item); var image = new Image(); MapToImage(image, imageItem); return image; } } }
using Xunit; namespace NeinLinq.Tests; public class SelectorTranslatorTest { [Fact] public void Translate_NullArgument_Throws() { var error = Assert.Throws<ArgumentNullException>(() => SelectorTranslator.Translate<Model, ModelView>(null!)); Assert.Equal("selector", error.ParamName); } [Fact] public void Apply_NullArgument_Throws() { Expression<Func<Model, ModelView>> s = _ => new ModelView { Id = 1 }; Expression<Func<Model, ModelView>> t = _ => new ModelView { Id = 1 }; var leftError = Assert.Throws<ArgumentNullException>(() => SelectorTranslator.Apply(null!, t)); var rightError = Assert.Throws<ArgumentNullException>(() => SelectorTranslator.Apply(s, null!)); Assert.Equal("left", leftError.ParamName); Assert.Equal("right", rightError.ParamName); } [Fact] public void Apply_NullInit_Throws() { Expression<Func<Model, ModelView>> s = _ => new ModelView { Id = 1 }; Expression<Func<Model, ModelView>> t = _ => new ModelView { Id = 1 }; var leftError = Assert.Throws<NotSupportedException>(() => SelectorTranslator.Apply(_ => null!, t)); var rightError = Assert.Throws<NotSupportedException>(() => SelectorTranslator.Apply(s, _ => null!)); Assert.Equal("Only member init expressions and new expressions are supported yet.", leftError.Message); Assert.Equal("Only member init expressions and new expressions are supported yet.", rightError.Message); } [Fact] public void Apply_InitWithParam_Throws() { Expression<Func<Model, ModelView>> s = _ => new ModelView { Id = 1 }; Expression<Func<Model, ModelView>> t = _ => new ModelView { Id = 1 }; var leftError = Assert.Throws<NotSupportedException>(() => SelectorTranslator.Apply(_ => new ModelView(1), t)); var rightError = Assert.Throws<NotSupportedException>(() => SelectorTranslator.Apply(s, _ => new ModelView(1))); Assert.Equal("Only parameterless constructors are supported yet.", leftError.Message); Assert.Equal("Only parameterless constructors are supported yet.", rightError.Message); } [Fact] public void Apply_Merges() { Expression<Func<Model, ModelView>> s = d => new ModelView { Id = d.Id }; Expression<Func<Model, ModelView>> t = d => new ModelView { Name = d.Name }; var select = s.Apply(t); var result = CreateQuery().OfType<Model>().Where(m => !(m is SpecialModel)).Select(select); Assert.Collection(result, v => { Assert.Equal(1, v.Id); Assert.Equal("Asdf", v.Name); }, v => { Assert.Equal(2, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(3, v.Id); Assert.Equal("Qwer", v.Name); }); } [Fact] public void Apply_EmptyInit_Merges() { Expression<Func<Model, ModelView>> s = _ => new ModelView(); Expression<Func<Model, ModelView>> t = _ => new ModelView(); var select = s.Apply(t); var result = CreateQuery().OfType<Model>().Where(m => !(m is SpecialModel)).Select(select); Assert.Collection(result, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); }); } [Fact] public void Apply_EmptyNotEmptyInit_Merges() { Expression<Func<Model, ModelView>> s = _ => new ModelView(); Expression<Func<Model, ModelView>> t = d => new ModelView { Id = d.Id + 5, Name = d.Name }; var select = s.Apply(t); var result = CreateQuery().OfType<Model>().Where(m => !(m is SpecialModel)).Select(select); Assert.Collection(result, v => { Assert.Equal(6, v.Id); Assert.Equal("Asdf", v.Name); }, v => { Assert.Equal(7, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(8, v.Id); Assert.Equal("Qwer", v.Name); } ); } [Fact] public void Apply_NotEmptyEmptyInit_Merges() { Expression<Func<Model, ModelView>> s = _ => new ModelView(); Expression<Func<Model, ModelView>> t = d => new ModelView { Id = d.Id + 5, Name = d.Name }; var select = t.Apply(s); var result = CreateQuery().OfType<Model>().Where(m => !(m is SpecialModel)).Select(select); Assert.Collection(result, v => { Assert.Equal(6, v.Id); Assert.Equal("Asdf", v.Name); }, v => { Assert.Equal(7, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(8, v.Id); Assert.Equal("Qwer", v.Name); } ); } [Fact] public void Source_Substitutes() { Expression<Func<Model, ModelView>> s = d => new ModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Source<SpecialModel>(); var result = CreateQuery().OfType<SpecialModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(4, v.Id); Assert.Equal("Asdf", v.Name); }, v => { Assert.Equal(5, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(6, v.Id); Assert.Equal("Qwer", v.Name); }); } [Fact] public void SourcePath_NullArgument_Throws() { Expression<Func<ParentModel, ParentModelView>> s = _ => new ParentModelView(); var error = Assert.Throws<ArgumentNullException>(() => s.Translate().Source((Expression<Func<ChildModel, ParentModel>>)null!)); Assert.Equal("path", error.ParamName); } [Fact] public void SourcePath_Substitutes() { Expression<Func<ParentModel, ParentModelView>> s = d => new ParentModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Source<ChildModel>(d => d.Parent); var result = CreateQuery().OfType<ChildModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(8, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(9, v.Id); Assert.Equal("Qwer", v.Name); }, v => { Assert.Equal(7, v.Id); Assert.Equal("Asdf", v.Name); }); } [Fact] public void SourceTranslation_NullArgument_Throws() { Expression<Func<ChildModel, ChildModelView>> s = _ => new ChildModelView(); var error = Assert.Throws<ArgumentNullException>(() => s.Translate().Source((Expression<Func<ParentModel, Func<ChildModel, ChildModelView>, ChildModelView>>)null!)); Assert.Equal("translation", error.ParamName); } [Fact] public void SourceTranslation_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Source<ParentModel>((d, v) => d.Children.Select(v).First()); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(10, v.Id); Assert.Equal("Asdf", v.Name); }, v => { Assert.Equal(11, v.Id); Assert.Equal("Narf", v.Name); }, v => { Assert.Equal(12, v.Id); Assert.Equal("Qwer", v.Name); }); } [Fact] public void SourceCollectionTranslation_NullArgument_Throws() { Expression<Func<ChildModel, ChildModelView>> s = _ => new ChildModelView(); var error = Assert.Throws<ArgumentNullException>(() => s.Translate().Source((Expression<Func<ParentModel, Func<ChildModel, ChildModelView>, IEnumerable<ChildModelView>>>)null!)); Assert.Equal("translation", error.ParamName); } [Fact] public void SourceCollectionTranslation_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Source<ParentModel>((d, v) => d.Children.Select(v)); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => Assert.Collection(v, w => { Assert.Equal(10, w.Id); Assert.Equal("Asdf", w.Name); }, w => { Assert.Equal(11, w.Id); Assert.Equal("Narf", w.Name); }), v => Assert.Collection(v, w => { Assert.Equal(11, w.Id); Assert.Equal("Narf", w.Name); }, w => { Assert.Equal(12, w.Id); Assert.Equal("Qwer", w.Name); }), v => Assert.Collection(v, w => { Assert.Equal(12, w.Id); Assert.Equal("Qwer", w.Name); }, w => { Assert.Equal(10, w.Id); Assert.Equal("Asdf", w.Name); })); } [Fact] public void Result_NullInit_Throws() { Expression<Func<SpecialModel, ModelView>> s = _ => null!; var error = Assert.Throws<NotSupportedException>(() => s.Translate().Result<SpecialModelView>()); Assert.Equal("Only member init expressions are supported yet.", error.Message); } [Fact] public void Result_InitWithParam_Throws() { Expression<Func<SpecialModel, ModelView>> s = _ => new ModelView(1) { Name = "Narf" }; var error = Assert.Throws<NotSupportedException>(() => s.Translate().Result<SpecialModelView>()); Assert.Equal("Only parameterless constructors are supported yet.", error.Message); } [Fact] public void Result_Substitutes() { Expression<Func<SpecialModel, ModelView>> s = d => new ModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Result<SpecialModelView>(); var result = CreateQuery().OfType<SpecialModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(4, v.Id); Assert.Equal("Asdf", v.Name); Assert.Null(v.Description); }, v => { Assert.Equal(5, v.Id); Assert.Equal("Narf", v.Name); Assert.Null(v.Description); }, v => { Assert.Equal(6, v.Id); Assert.Equal("Qwer", v.Name); Assert.Null(v.Description); }); } [Fact] public void ResultPath_NullArgument_Throws() { Expression<Func<ChildModel, ParentModelView>> s = _ => new ParentModelView(); var error = Assert.Throws<ArgumentNullException>(() => s.Translate().Result((Expression<Func<ChildModelView, ParentModelView>>)null!)); Assert.Equal("path", error.ParamName); } [Fact] public void ResultPath_NullInit_Throws() { Expression<Func<ChildModel, ParentModelView>> s = _ => new ParentModelView(); var error = Assert.Throws<NotSupportedException>(() => s.Translate().Result<ChildModelView>(_ => null!)); Assert.Equal("Only member expressions are supported yet.", error.Message); } [Fact] public void ResultPath_Substitutes() { Expression<Func<ChildModel, ParentModelView>> s = d => new ParentModelView { Id = d.Parent!.Id, Name = d.Parent.Name }; var select = s.Translate().Result<ChildModelView>(d => d.Parent); var result = CreateQuery().OfType<ChildModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(8, v.Parent.Id); Assert.Equal("Narf", v.Parent.Name); }, v => { Assert.Equal(9, v.Parent.Id); Assert.Equal("Qwer", v.Parent.Name); }, v => { Assert.Equal(7, v.Parent.Id); Assert.Equal("Asdf", v.Parent.Name); }); } [Fact] public void ResultTranslation_NullArgument_Throws() { Expression<Func<ParentModel, IEnumerable<ChildModelView>>> s = _ => Array.Empty<ChildModelView>(); var error = Assert.Throws<ArgumentNullException>(() => s.Translate().Result((Expression<Func<ParentModel, Func<ParentModel, IEnumerable<ChildModelView>>, ParentModelView>>)null!)); Assert.Equal("translation", error.ParamName); } [Fact] public void ResultTranslation_Substitutes() { Expression<Func<ParentModel, IEnumerable<ChildModelView>>> s = d => d.Children!.Select(e => new ChildModelView { Id = e.Id, Name = e.Name }); var select = s.Translate().Result((d, v) => new ParentModelView { FirstChild = v(d).First() }); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(10, v.FirstChild.Id); Assert.Equal("Asdf", v.FirstChild.Name); }, v => { Assert.Equal(11, v.FirstChild.Id); Assert.Equal("Narf", v.FirstChild.Name); }, v => { Assert.Equal(12, v.FirstChild.Id); Assert.Equal("Qwer", v.FirstChild.Name); }); } [Fact] public void Cross_Substitutes() { Expression<Func<Model, ModelView>> s = d => new ModelView { Id = d.Id, Name = d.Name }; Expression<Func<SpecialModel, SpecialModelView>> t = d => new SpecialModelView { Description = d.Description }; var select = s.Translate().Cross<SpecialModel>().Apply(t); var result = CreateQuery().OfType<SpecialModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(4, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal("Asdf", v.Description); }, v => { Assert.Equal(5, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal("Narf", v.Description); }, v => { Assert.Equal(6, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal("Qwer", v.Description); }); } [Fact] public void CrossPath_Substitutes() { Expression<Func<ParentModel, ParentModelView>> s = d => new ParentModelView { Id = d.Id, Name = d.Name }; Expression<Func<ChildModel, ChildModelView>> t = d => new ChildModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Cross<ChildModel>(d => d.Parent).Apply(d => d.Parent, t); var result = CreateQuery().OfType<ChildModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(10, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal(8, v.Parent.Id); Assert.Equal("Narf", v.Parent.Name); }, v => { Assert.Equal(11, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal(9, v.Parent.Id); Assert.Equal("Qwer", v.Parent.Name); }, v => { Assert.Equal(12, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal(7, v.Parent.Id); Assert.Equal("Asdf", v.Parent.Name); }); } [Fact] public void CrossTranslation_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; Expression<Func<ParentModel, ParentModelView>> t = d => new ParentModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Cross<ParentModel>((d, v) => d.Children.Select(v).First()).Apply((d, v) => new ParentModelView { FirstChild = v(d) }, t); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(7, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal(10, v.FirstChild.Id); Assert.Equal("Asdf", v.FirstChild.Name); }, v => { Assert.Equal(8, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal(11, v.FirstChild.Id); Assert.Equal("Narf", v.FirstChild.Name); }, v => { Assert.Equal(9, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal(12, v.FirstChild.Id); Assert.Equal("Qwer", v.FirstChild.Name); }); } [Fact] public void CrossCollectionTranslation_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; Expression<Func<ParentModel, ParentModelView>> t = d => new ParentModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().Cross<ParentModel>((d, v) => d.Children.Select(v)).Apply((d, v) => new ParentModelView { FirstChild = v(d).First() }, t); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(7, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal(10, v.FirstChild.Id); Assert.Equal("Asdf", v.FirstChild.Name); }, v => { Assert.Equal(8, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal(11, v.FirstChild.Id); Assert.Equal("Narf", v.FirstChild.Name); }, v => { Assert.Equal(9, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal(12, v.FirstChild.Id); Assert.Equal("Qwer", v.FirstChild.Name); }); } [Fact] public void To_Substitutes() { Expression<Func<Model, ModelView>> s = d => new ModelView { Id = d.Id, Name = d.Name }; Expression<Func<SpecialModel, SpecialModelView>> t = d => new SpecialModelView { Description = d.Description }; var select = s.Translate().To(t); var result = CreateQuery().OfType<SpecialModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(4, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal("Asdf", v.Description); }, v => { Assert.Equal(5, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal("Narf", v.Description); }, v => { Assert.Equal(6, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal("Qwer", v.Description); }); } [Fact] public void To_WithoutValue_Substitutes() { Expression<Func<Model, ModelView>> s = d => new ModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().To<SpecialModel, SpecialModelView>(); var result = CreateQuery().OfType<SpecialModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(4, v.Id); Assert.Equal("Asdf", v.Name); Assert.Null(v.Description); }, v => { Assert.Equal(5, v.Id); Assert.Equal("Narf", v.Name); Assert.Null(v.Description); }, v => { Assert.Equal(6, v.Id); Assert.Equal("Qwer", v.Name); Assert.Null(v.Description); }); } [Fact] public void ToPath_Substitutes() { Expression<Func<ParentModel, ParentModelView>> s = d => new ParentModelView { Id = d.Id, Name = d.Name }; Expression<Func<ChildModel, ChildModelView>> t = d => new ChildModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().To(d => d.Parent, d => d.Parent, t); var result = CreateQuery().OfType<ChildModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(10, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal(8, v.Parent.Id); Assert.Equal("Narf", v.Parent.Name); }, v => { Assert.Equal(11, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal(9, v.Parent.Id); Assert.Equal("Qwer", v.Parent.Name); }, v => { Assert.Equal(12, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal(7, v.Parent.Id); Assert.Equal("Asdf", v.Parent.Name); }); } [Fact] public void ToPath_WithoutValue_Substitutes() { Expression<Func<ParentModel, ParentModelView>> s = d => new ParentModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().To<ChildModel, ChildModelView>(d => d.Parent, d => d.Parent); var result = CreateQuery().OfType<ChildModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(8, v.Parent.Id); Assert.Equal("Narf", v.Parent.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(9, v.Parent.Id); Assert.Equal("Qwer", v.Parent.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(7, v.Parent.Id); Assert.Equal("Asdf", v.Parent.Name); }); } [Fact] public void ToTranslation_NullArgument_Throws() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; var error = Assert.Throws<ArgumentNullException>(() => s.Translate().To((Expression<Func<ParentModel, Func<ChildModel, ChildModelView>, ParentModelView>>)null!)); Assert.Equal("translation", error.ParamName); } [Fact] public void ToTranslation_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; Expression<Func<ParentModel, ParentModelView>> t = d => new ParentModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().To((d, v) => new ParentModelView { FirstChild = d.Children.Select(v).First() }, t); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(7, v.Id); Assert.Equal("Asdf", v.Name); Assert.Equal(10, v.FirstChild.Id); Assert.Equal("Asdf", v.FirstChild.Name); }, v => { Assert.Equal(8, v.Id); Assert.Equal("Narf", v.Name); Assert.Equal(11, v.FirstChild.Id); Assert.Equal("Narf", v.FirstChild.Name); }, v => { Assert.Equal(9, v.Id); Assert.Equal("Qwer", v.Name); Assert.Equal(12, v.FirstChild.Id); Assert.Equal("Qwer", v.FirstChild.Name); }); } [Fact] public void ToTranslation_WithoutValue_Substitutes() { Expression<Func<ChildModel, ChildModelView>> s = d => new ChildModelView { Id = d.Id, Name = d.Name }; var select = s.Translate().To<ParentModel, ParentModelView>((d, v) => new ParentModelView { FirstChild = d.Children.Select(v).First() }); var result = CreateQuery().OfType<ParentModel>().Select(select); Assert.Collection(result, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(10, v.FirstChild.Id); Assert.Equal("Asdf", v.FirstChild.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(11, v.FirstChild.Id); Assert.Equal("Narf", v.FirstChild.Name); }, v => { Assert.Equal(0, v.Id); Assert.Null(v.Name); Assert.Equal(12, v.FirstChild.Id); Assert.Equal("Qwer", v.FirstChild.Name); }); } private static IQueryable<IModel> CreateQuery() { var d = new[] { new Model { Id = 1, Name = "Asdf" }, new Model { Id = 2, Name = "Narf" }, new Model { Id = 3, Name = "Qwer" } }; var s = new[] { new SpecialModel { Id = 4, Name = "Asdf", Description = "Asdf" }, new SpecialModel { Id = 5, Name = "Narf", Description = "Narf" }, new SpecialModel { Id = 6, Name = "Qwer", Description = "Qwer" } }; var p = new[] { new ParentModel { Id = 7, Name = "Asdf" }, new ParentModel { Id = 8, Name = "Narf" }, new ParentModel { Id = 9, Name = "Qwer" } }; var c = new[] { new ChildModel { Id = 10, Name = "Asdf", Parent = p[1] }, new ChildModel { Id = 11, Name = "Narf", Parent = p[2] }, new ChildModel { Id = 12, Name = "Qwer", Parent = p[0] } }; p[0].Children = new[] { c[0], c[1] }; p[1].Children = new[] { c[1], c[2] }; p[2].Children = new[] { c[2], c[0] }; return d.Concat<IModel>(s).Concat(p).Concat(c).AsQueryable(); } private interface IModel { int Id { get; set; } string Name { get; set; } } private class Model : IModel { public int Id { get; set; } public string Name { get; set; } = null!; } private class SpecialModel : Model { public string Description { get; set; } = null!; } private class ParentModel : IModel { public int Id { get; set; } public string Name { get; set; } = null!; public ICollection<ChildModel> Children { get; set; } = null!; } private class ChildModel : IModel { public int Id { get; set; } public string Name { get; set; } = null!; public ParentModel Parent { get; set; } = null!; } private class ModelView { public int Id { get; set; } public string Name { get; set; } = null!; public ModelView() { } public ModelView(int id) { Id = id; } } private class SpecialModelView : ModelView { public string Description { get; set; } = null!; } private class ParentModelView { public int Id { get; set; } public string Name { get; set; } = null!; public ChildModelView FirstChild { get; set; } = null!; public IEnumerable<ChildModelView> Children { get; set; } = null!; } private class ChildModelView { public int Id { get; set; } public string Name { get; set; } = null!; public ParentModelView Parent { get; set; } = null!; } }
/* Copyright (c) 2012 - 2015 Antmicro <www.antmicro.com> Authors: * Konrad Kruczynski (kkruczynski@antmicro.com) * Piotr Zierhoffer (pzierhoffer@antmicro.com) * Mateusz Holenko (mholenko@antmicro.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Runtime.Serialization; using System.Reflection; using System.Linq; using System.Collections.Generic; using System.Collections; using Antmicro.Migrant.Hooks; using Antmicro.Migrant.Utilities; using System.Collections.ObjectModel; using System.Reflection.Emit; using Antmicro.Migrant.Generators; using Antmicro.Migrant.VersionTolerance; using Antmicro.Migrant.Customization; namespace Antmicro.Migrant { /// <summary> /// Reads the object previously written by <see cref="Antmicro.Migrant.ObjectWriter" />. /// </summary> public class ObjectReader : IDisposable { /// <summary> /// Initializes a new instance of the <see cref="Antmicro.Migrant.ObjectReader" /> class. /// </summary> /// <param name='stream'> /// Stream from which objects will be read. /// </param> /// <param name='objectsForSurrogates'> /// Dictionary, containing callbacks that provide objects for given type of surrogate. Callbacks have to be of type Func&lt;T, object&gt; where /// typeof(T) is type of surrogate. They always have to be in sync with <paramref name="readMethods"/>. /// </param> /// <param name='postDeserializationCallback'> /// Callback which will be called after deserialization of every unique object. Deserialized /// object is given in the callback's only parameter. /// </param> /// <param name='readMethods'> /// Cache in which generated read methods are stored and reused between instances of <see cref="Antmicro.Migrant.ObjectReader" />. /// Can be null if one does not want to use the cache. For the life of the cache you always have to provide the same /// <paramref name="objectsForSurrogates"/>. /// </param> /// <param name='isGenerating'> /// True if read methods are to be generated, false if one wants to use reflection. /// </param> /// <param name = "treatCollectionAsUserObject"> /// True if collection objects are to be deserialized without optimization (treated as normal user objects). /// </param> /// <param name="versionToleranceLevel"> /// Describes the tolerance level of this reader when handling discrepancies in type description (new or missing fields, etc.). /// </param> /// <param name="useBuffering"> /// True if buffering was used with the corresponding ObjectWriter or false otherwise - i.e. when no padding and buffering is used. /// </param> /// <param name="referencePreservation"> /// Tells deserializer whether open stream serialization preserved objects identieties between serialization. Note that this option should /// be consistent with what was used during serialization. /// </param> public ObjectReader(Stream stream, InheritanceAwareList<Delegate> objectsForSurrogates = null, Action<object> postDeserializationCallback = null, IDictionary<Type, DynamicMethod> readMethods = null, bool isGenerating = false, bool treatCollectionAsUserObject = false, VersionToleranceLevel versionToleranceLevel = 0, bool useBuffering = true, ReferencePreservation referencePreservation = ReferencePreservation.Preserve) { if(objectsForSurrogates == null) { objectsForSurrogates = new InheritanceAwareList<Delegate>(); } this.objectsForSurrogates = objectsForSurrogates; this.readMethodsCache = readMethods ?? new Dictionary<Type, DynamicMethod>(); this.useGeneratedDeserialization = isGenerating; typeCache = new Dictionary<int, TypeDescriptor>(); methodList = new List<MethodInfo>(); assembliesList = new List<AssemblyDescriptor>(); postDeserializationHooks = new List<Action>(); this.postDeserializationCallback = postDeserializationCallback; this.treatCollectionAsUserObject = treatCollectionAsUserObject; delegatesCache = new Dictionary<Type, Func<int, object>>(); reader = new PrimitiveReader(stream, useBuffering); this.referencePreservation = referencePreservation; this.versionToleranceLevel = versionToleranceLevel; } /// <summary> /// Reads the object with the expected formal type <typeparamref name='T'/>. /// </summary> /// <returns> /// The object, previously written by the <see cref="Antmicro.Migrant.ObjectWriter" />. /// </returns> /// <typeparam name='T'> /// The expected formal type of object, that is the type of the reference returned /// by the method after serialization. The previously serialized object must be /// convertible to this type. /// </typeparam> /// <remarks> /// Note that this method will read the object from the stream along with other objects /// referenced by it. /// </remarks> public T ReadObject<T>() { if(soFarDeserialized != null) { deserializedObjects = new AutoResizingList<object>(soFarDeserialized.Length); for(var i = 0; i < soFarDeserialized.Length; i++) { deserializedObjects[i] = soFarDeserialized[i].Target; } } if(deserializedObjects == null) { deserializedObjects = new AutoResizingList<object>(InitialCapacity); } var firstObjectId = deserializedObjects.Count; var type = ReadType().UnderlyingType; if(useGeneratedDeserialization) { ReadObjectInnerGenerated(type, firstObjectId); } else { ReadObjectInner(type, firstObjectId); } var obj = deserializedObjects[firstObjectId]; if(!(obj is T)) { throw new InvalidDataException( string.Format("Type {0} requested to be deserialized, however type {1} encountered in the stream.", typeof(T), obj.GetType())); } PrepareForNextRead(); foreach(var hook in postDeserializationHooks) { hook(); } return (T)obj; } /// <summary> /// Releases all resource used by the <see cref="Antmicro.Migrant.ObjectReader"/> object. Note that this is not necessary /// if buffering is not used. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Antmicro.Migrant.ObjectReader"/>. The /// <see cref="Dispose"/> method leaves the <see cref="Antmicro.Migrant.ObjectReader"/> in an unusable state. /// After calling <see cref="Dispose"/>, you must release all references to the /// <see cref="Antmicro.Migrant.ObjectReader"/> so the garbage collector can reclaim the memory that the /// <see cref="Antmicro.Migrant.ObjectReader"/> was occupying.</remarks> public void Dispose() { reader.Dispose(); } private void TouchReadMethod(Type type) { if(!readMethodsCache.ContainsKey(type)) { var surrogateId = Helpers.GetSurrogateFactoryIdForType(type, objectsForSurrogates); var rmg = new ReadMethodGenerator(type, treatCollectionAsUserObject, surrogateId, Helpers.GetFieldInfo<ObjectReader, InheritanceAwareList<Delegate>>(x => x.objectsForSurrogates), Helpers.GetFieldInfo<ObjectReader, AutoResizingList<object>>(x => x.deserializedObjects), Helpers.GetFieldInfo<ObjectReader, PrimitiveReader>(x => x.reader), Helpers.GetFieldInfo<ObjectReader, Action<object>>(x => x.postDeserializationCallback), Helpers.GetFieldInfo<ObjectReader, List<Action>>(x => x.postDeserializationHooks)); readMethodsCache.Add(type, rmg.Method); } } private void PrepareForNextRead() { if(referencePreservation == ReferencePreservation.UseWeakReference) { soFarDeserialized = new WeakReference[deserializedObjects.Count]; for(var i = 0; i < soFarDeserialized.Length; i++) { soFarDeserialized[i] = new WeakReference(deserializedObjects[i]); } } if(referencePreservation != ReferencePreservation.Preserve) { deserializedObjects = null; } } internal static bool HasSpecialReadMethod(Type type) { return type == typeof(string) || typeof(ISpeciallySerializable).IsAssignableFrom(type) || Helpers.CheckTransientNoCache(type); } internal void ReadObjectInnerGenerated(Type actualType, int objectId) { TouchReadMethod(actualType); if(!delegatesCache.ContainsKey(actualType)) { var func = (Func<Int32, object>)readMethodsCache[actualType].CreateDelegate(typeof(Func<Int32, object>), this); delegatesCache.Add(actualType, func); } // execution of read method of given type deserializedObjects[objectId] = delegatesCache[actualType](objectId); } private void ReadObjectInner(Type actualType, int objectId) { TouchObject(actualType, objectId); switch(GetCreationWay(actualType, treatCollectionAsUserObject)) { case CreationWay.Null: ReadNotPrecreated(actualType, objectId); break; case CreationWay.DefaultCtor: UpdateElements(actualType, objectId); break; case CreationWay.Uninitialized: UpdateFields(actualType, deserializedObjects[objectId]); break; } var obj = deserializedObjects[objectId]; if(obj == null) { // it can happen if we deserialize delegate with empty invocation list return; } var factoryId = Helpers.GetSurrogateFactoryIdForType(obj.GetType(), objectsForSurrogates); if(factoryId != -1) { deserializedObjects[objectId] = objectsForSurrogates.GetByIndex(factoryId).DynamicInvoke(new [] { obj }); } Helpers.InvokeAttribute(typeof(PostDeserializationAttribute), obj); var postHook = Helpers.GetDelegateWithAttribute(typeof(LatePostDeserializationAttribute), obj); if(postHook != null) { if(factoryId != -1) { throw new InvalidOperationException(string.Format(ObjectReader.LateHookAndSurrogateError, actualType)); } postDeserializationHooks.Add(postHook); } if(postDeserializationCallback != null) { postDeserializationCallback(obj); } } private void UpdateFields(Type actualType, object target) { var fieldOrTypeInfos = TypeDescriptor.CreateFromType(actualType).FieldsToDeserialize; foreach(var fieldOrTypeInfo in fieldOrTypeInfos) { if(fieldOrTypeInfo.Field == null) { ReadField(fieldOrTypeInfo.TypeToOmit); continue; } var field = fieldOrTypeInfo.Field; if(field.IsDefined(typeof(TransientAttribute), false)) { if(field.IsDefined(typeof(ConstructorAttribute), false)) { var ctorAttribute = (ConstructorAttribute)field.GetCustomAttributes(false).First(x => x is ConstructorAttribute); field.SetValue(target, Activator.CreateInstance(field.FieldType, ctorAttribute.Parameters)); } continue; } field.SetValue(target, ReadField(field.FieldType)); } } private void ReadNotPrecreated(Type type, int objectId) { if(type.IsValueType) { // a boxed value type deserializedObjects[objectId] = ReadField(type); } else if(type == typeof(string)) { deserializedObjects[objectId] = reader.ReadString(); } else if(type.IsArray) { ReadArray(type.GetElementType(), objectId); } else if(typeof(MulticastDelegate).IsAssignableFrom(type)) { ReadDelegate(type, objectId); } else if(type.IsGenericType && typeof(ReadOnlyCollection<>).IsAssignableFrom(type.GetGenericTypeDefinition())) { ReadReadOnlyCollection(type, objectId); } else { throw new InvalidOperationException(InternalErrorMessage); } } private void UpdateElements(Type type, int objectId) { var obj = deserializedObjects[objectId]; var speciallyDeserializable = obj as ISpeciallySerializable; if(speciallyDeserializable != null) { LoadAndVerifySpeciallySerializableAndVerify(speciallyDeserializable, reader); return; } CollectionMetaToken token; if (!CollectionMetaToken.TryGetCollectionMetaToken(type, out token)) { throw new InvalidOperationException(InternalErrorMessage); } if(token.IsDictionary) { FillDictionary(token, obj); return; } // so we can assume it is ICollection<T> or ICollection FillCollection(token.FormalElementType, obj); } private object ReadField(Type formalType) { if(Helpers.CheckTransientNoCache(formalType)) { return Helpers.GetDefaultValue(formalType); } if(!formalType.IsValueType) { var refId = reader.ReadInt32(); if(refId == Consts.NullObjectId) { return null; } if(refId >= deserializedObjects.Count) { ReadObjectInner(ReadType().UnderlyingType, refId); } return deserializedObjects[refId]; } if(formalType.IsEnum) { var value = ReadField(Enum.GetUnderlyingType(formalType)); return Enum.ToObject(formalType, value); } var nullableActualType = Nullable.GetUnderlyingType(formalType); if(nullableActualType != null) { var isNotNull = reader.ReadBoolean(); return isNotNull ? ReadField(nullableActualType) : null; } if(Helpers.IsWriteableByPrimitiveWriter(formalType)) { var methodName = string.Concat("Read", formalType.Name); var readMethod = typeof(PrimitiveReader).GetMethod(methodName); return readMethod.Invoke(reader, Type.EmptyTypes); } var returnedObject = Activator.CreateInstance(formalType); // here we have a boxed struct which we put to struct reference list UpdateFields(formalType, returnedObject); // if this is subtype return returnedObject; } private void FillCollection(Type elementFormalType, object obj) { var collectionType = obj.GetType(); var count = reader.ReadInt32(); var addMethod = collectionType.GetMethod("Add", new [] { elementFormalType }) ?? collectionType.GetMethod("Enqueue", new [] { elementFormalType }) ?? collectionType.GetMethod("Push", new [] { elementFormalType }); if(addMethod == null) { throw new InvalidOperationException(string.Format(CouldNotFindAddErrorMessage, collectionType)); } Type delegateType; if(addMethod.ReturnType == typeof(void)) { delegateType = typeof(Action<>).MakeGenericType(new [] { elementFormalType }); } else { delegateType = typeof(Func<,>).MakeGenericType(new [] { elementFormalType, addMethod.ReturnType }); } var addDelegate = Delegate.CreateDelegate(delegateType, obj, addMethod); if(collectionType == typeof(Stack) || (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Stack<>))) { var stack = (dynamic)obj; var temp = new dynamic[count]; for(var i = 0; i < count; i++) { temp[i] = ReadField(elementFormalType); } for(var i = count - 1; i >= 0; --i) { stack.Push(temp[i]); } } else { for(var i = 0; i < count; i++) { var fieldValue = ReadField(elementFormalType); addDelegate.DynamicInvoke(fieldValue); } } } private void FillDictionary(CollectionMetaToken token, object obj) { var dictionaryType = obj.GetType(); var count = reader.ReadInt32(); var addMethodArgumentTypes = new [] { token.FormalKeyType, token.FormalValueType }; var addMethod = dictionaryType.GetMethod("Add", addMethodArgumentTypes) ?? dictionaryType.GetMethod("TryAdd", addMethodArgumentTypes); if(addMethod == null) { throw new InvalidOperationException(string.Format(CouldNotFindAddErrorMessage, dictionaryType)); } Type delegateType; if(addMethod.ReturnType == typeof(void)) { delegateType = typeof(Action<,>).MakeGenericType(addMethodArgumentTypes); } else { delegateType = typeof(Func<,,>).MakeGenericType(new [] { addMethodArgumentTypes[0], addMethodArgumentTypes[1], addMethod.ReturnType }); } var addDelegate = Delegate.CreateDelegate(delegateType, obj, addMethod); for(var i = 0; i < count; i++) { var key = ReadField(addMethodArgumentTypes[0]); var value = ReadField(addMethodArgumentTypes[1]); addDelegate.DynamicInvoke(key, value); } } private void ReadArray(Type elementFormalType, int objectId) { var rank = reader.ReadInt32(); var lengths = new int[rank]; for(var i = 0; i < rank; i++) { lengths[i] = reader.ReadInt32(); } var array = Array.CreateInstance(elementFormalType, lengths); // we should update the array object as soon as we can // why? because it can have the reference to itself (what a corner case!) deserializedObjects[objectId] = array; var position = new int[rank]; FillArrayRowRecursive(array, 0, position, elementFormalType); } private void ReadDelegate(Type type, int objectId) { var invocationListLength = reader.ReadInt32(); for(var i = 0; i < invocationListLength; i++) { var target = ReadField(typeof(object)); var method = ReadMethod(); var del = Delegate.CreateDelegate(type, target, method); deserializedObjects[objectId] = Delegate.Combine((Delegate)deserializedObjects[objectId], del); } } private void ReadReadOnlyCollection(Type type, int objectId) { var elementFormalType = type.GetGenericArguments()[0]; var length = reader.ReadInt32(); var array = Array.CreateInstance(elementFormalType, length); for(var i = 0; i < length; i++) { array.SetValue(ReadField(elementFormalType), i); } deserializedObjects[objectId] = Activator.CreateInstance(type, array); } private void FillArrayRowRecursive(Array array, int currentDimension, int[] position, Type elementFormalType) { var length = array.GetLength(currentDimension); for(var i = 0; i < length; i++) { if(currentDimension == array.Rank - 1) { var value = ReadField(elementFormalType); array.SetValue(value, position); } else { FillArrayRowRecursive(array, currentDimension + 1, position, elementFormalType); } position[currentDimension]++; for(var j = currentDimension + 1; j < array.Rank; j++) { position[j] = 0; } } } internal static void LoadAndVerifySpeciallySerializableAndVerify(ISpeciallySerializable obj, PrimitiveReader reader) { var beforePosition = reader.Position; obj.Load(reader); var afterPosition = reader.Position; var serializedLength = reader.ReadInt64(); if(serializedLength + beforePosition != afterPosition) { throw new InvalidOperationException(string.Format( "Stream corruption by '{0}', incorrent magic {1} when {2} expected.", obj.GetType(), serializedLength, afterPosition - beforePosition)); } } internal TypeDescriptor ReadType() { var typeId = reader.ReadInt32(); if(typeId == Consts.NullObjectId) { return null; } if(typeCache.Any() && typeCache.Keys.Max() >= typeId) { return typeCache[typeId]; } var type = TypeDescriptor.ReadFromStream(this); typeCache.Add(typeId, type); // we need to read stamp here (i.e., after adding to typeList) // as other types from the stamp can reference this type type.ReadStructureStampIfNeeded(this, versionToleranceLevel); return type; } internal MethodInfo ReadMethod() { MethodInfo result = null; var methodId = reader.ReadInt32(); if(methodList.Count <= methodId) { var type = ReadType().UnderlyingType; var methodName = reader.ReadString(); var genericArgumentsCount = reader.ReadInt32(); var genericArguments = new Type[genericArgumentsCount]; for(int i = 0; i < genericArgumentsCount; i++) { genericArguments[i] = ReadType().UnderlyingType; } var parametersCount = reader.ReadInt32(); if(genericArgumentsCount > 0) { var parameters = new TypeOrGenericTypeArgument[parametersCount]; for(int i = 0; i < parameters.Length; i++) { var genericType = reader.ReadBoolean(); parameters[i] = genericType ? new TypeOrGenericTypeArgument(reader.ReadInt32()) : new TypeOrGenericTypeArgument(ReadType().UnderlyingType); } result = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).SingleOrDefault(m => m.IsGenericMethod && m.GetGenericMethodDefinition().Name == methodName && m.GetGenericArguments().Length == genericArgumentsCount && CompareGenericArguments(m.GetGenericMethodDefinition().GetParameters(), parameters)); if(result != null) { result = result.MakeGenericMethod(genericArguments); } } else { var types = new Type[parametersCount]; for(int i = 0; i < types.Length; i++) { types[i] = ReadType().UnderlyingType; } result = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, types, null); } methodList.Add(result); } else { result = methodList[methodId]; } return result; } internal AssemblyDescriptor ReadAssembly() { var assemblyId = PrimitiveReader.ReadInt32(); if(assembliesList.Count <= assemblyId) { var descriptor = AssemblyDescriptor.ReadFromStream(this); assembliesList.Add(descriptor); return descriptor; } else { return assembliesList[assemblyId]; } } private object TouchObject(Type actualType, int refId) { if(deserializedObjects[refId] != null) { return deserializedObjects[refId]; } object created = null; switch(GetCreationWay(actualType, treatCollectionAsUserObject)) { case CreationWay.Null: break; case CreationWay.DefaultCtor: created = Activator.CreateInstance(actualType); break; case CreationWay.Uninitialized: created = FormatterServices.GetUninitializedObject(actualType); break; } deserializedObjects[refId] = created; return created; } internal static CreationWay GetCreationWay(Type actualType, bool treatCollectionAsUserObject) { if(Helpers.CanBeCreatedWithDataOnly(actualType, treatCollectionAsUserObject)) { return CreationWay.Null; } if(!treatCollectionAsUserObject && CollectionMetaToken.IsCollection(actualType)) { return CreationWay.DefaultCtor; } if(typeof(ISpeciallySerializable).IsAssignableFrom(actualType)) { return CreationWay.DefaultCtor; } return CreationWay.Uninitialized; } internal bool TreatCollectionAsUserObject { get { return treatCollectionAsUserObject; } } internal PrimitiveReader PrimitiveReader { get { return reader; } } internal const string LateHookAndSurrogateError = "Type {0}: late post deserialization callback cannot be used in conjunction with surrogates."; private static bool CompareGenericArguments(ParameterInfo[] actual, TypeOrGenericTypeArgument[] expected) { if(actual.Length != expected.Length) { return false; } for(int i = 0; i < actual.Length; i++) { if(actual[i].ParameterType.IsGenericParameter) { if(actual[i].ParameterType.GenericParameterPosition != expected[i].GenericTypeArgumentIndex) { return false; } } else { if(actual[i].ParameterType != expected[i].Type) { return false; } } } return true; } private readonly VersionToleranceLevel versionToleranceLevel; private WeakReference[] soFarDeserialized; private readonly bool useGeneratedDeserialization; private readonly bool treatCollectionAsUserObject; private ReferencePreservation referencePreservation; private AutoResizingList<object> deserializedObjects; private IDictionary<Type, DynamicMethod> readMethodsCache; private readonly Dictionary<Type, Func<Int32, object>> delegatesCache; private readonly PrimitiveReader reader; private readonly Dictionary<int, TypeDescriptor> typeCache; private readonly List<MethodInfo> methodList; private readonly List<AssemblyDescriptor> assembliesList; private readonly Action<object> postDeserializationCallback; private readonly List<Action> postDeserializationHooks; private readonly InheritanceAwareList<Delegate> objectsForSurrogates; private const int InitialCapacity = 128; private const string InternalErrorMessage = "Internal error: should not reach here."; private const string CouldNotFindAddErrorMessage = "Could not find suitable Add method for the type {0}."; internal enum CreationWay { Uninitialized, DefaultCtor, Null } private struct TypeOrGenericTypeArgument { public TypeOrGenericTypeArgument(Type t) : this() { Type = t; GenericTypeArgumentIndex = -1; } public TypeOrGenericTypeArgument(int index) : this() { Type = null; GenericTypeArgumentIndex = index; } public Type Type { get; private set; } public int GenericTypeArgumentIndex { get; private set; } } } }
//----------------------------------------------------------------------- // <copyright file="ADMGUIController.cs" company="Google"> // // Copyright 2016 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. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Threading; using Tango; using UnityEngine; using UnityEngine.UI; /// <summary> /// Class for all the UI interaction in the AreaDescriptionManagement sample. /// </summary> public class ADMGUIController : MonoBehaviour, ITangoLifecycle, ITangoEvent { /// <summary> /// Parent of the Area Description management screen. /// </summary> public GameObject m_managementRoot; /// <summary> /// Parent of the Area Description quality screen. /// </summary> public GameObject m_qualityRoot; /// <summary> /// UI parent of the list of Area Descriptions on the device. /// </summary> public RectTransform m_listParent; /// <summary> /// UI prefab for each element in the list of Area Descriptions on the device. /// </summary> public AreaDescriptionListElement m_listElement; /// <summary> /// UI to enable when m_ListParent has no children. /// </summary> public RectTransform m_listEmptyText; /// <summary> /// UI parent of the selected Area Description's details. /// </summary> public RectTransform m_detailsParent; /// <summary> /// Read-only UI for the selected Area Description's date. /// </summary> public Text m_detailsDate; /// <summary> /// Editable UI for the selected Area Description's human readable name. /// </summary> public InputField m_detailsEditableName; /// <summary> /// Editable UI for the selected Area Description's X position. /// </summary> public InputField m_detailsEditablePosX; /// <summary> /// Editable UI for the selected Area Description's Y position. /// </summary> public InputField m_detailsEditablePosY; /// <summary> /// Editable UI for the selected Area Description's Z position. /// </summary> public InputField m_detailsEditablePosZ; /// <summary> /// Editable UI for the selected Area Description's qX rotation. /// </summary> public InputField m_detailsEditableRotQX; /// <summary> /// Editable UI for the selected Area Description's qY rotation. /// </summary> public InputField m_detailsEditableRotQY; /// <summary> /// Editable UI for the selected Area Description's qZ rotation. /// </summary> public InputField m_detailsEditableRotQZ; /// <summary> /// Editable UI for the selected Area Description's qW rotation. /// </summary> public InputField m_detailsEditableRotQW; /// <summary> /// The reference of the TangoDeltaPoseController object. /// /// TangoDeltaPoseController listens to pose updates and applies the correct pose to itself and its built-in camera. /// </summary> public TangoDeltaPoseController m_deltaPoseController; /// <summary> /// Saving progress UI parent. /// </summary> public RectTransform m_savingTextParent; /// <summary> /// Saving progress UI text. /// </summary> public Text m_savingText; /// <summary> /// TangoApplication for this scene. /// </summary> private TangoApplication m_tangoApplication; /// <summary> /// Currently selected Area Description. /// </summary> private AreaDescription m_selectedAreaDescription; /// <summary> /// Currently selected Area Description's metadata. /// </summary> private AreaDescription.Metadata m_selectedMetadata; /// <summary> /// The background thread saving occurs on. /// </summary> private Thread m_saveThread; #if UNITY_EDITOR /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// If true, text input for naming new saved Area Description is displayed. /// </summary> private bool m_displayGuiTextInput; /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// Contains text data for naming new saved Area Descriptions. /// </summary> private string m_guiTextInputContents; /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// Indicates whether last text input was ended with confirmation or cancellation. /// </summary> private bool m_guiTextInputResult; #endif /// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (m_saveThread != null && m_saveThread.ThreadState != ThreadState.Running) { // After saving an Area Description, we reload the scene to restart the game. #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } // Pressing the back button should popup the management window if you are not in the management screen, // otherwise it can quit. if (Input.GetKey(KeyCode.Escape)) { if (m_managementRoot.activeSelf) { // This is a fix for a lifecycle issue where calling // Application.Quit() here, and restarting the application // immediately results in a deadlocked app. AndroidHelper.AndroidQuit(); } else { #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } } /// <summary> /// Use this for initialization. /// </summary> public void Start() { m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); if (AndroidHelper.IsTangoCorePresent()) { m_tangoApplication.RequestPermissions(); } } else { Debug.Log("No Tango Manager found in scene."); } } /// <summary> /// Application onPause / onResume callback. /// </summary> /// <param name="pauseStatus"><c>true</c> if the application about to pause, otherwise <c>false</c>.</param> public void OnApplicationPause(bool pauseStatus) { if (pauseStatus && !m_managementRoot.activeSelf) { // When application is backgrounded, we reload the level because the Tango Service is disconected. All // learned area and placed marker should be discarded as they are not saved. #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } #if UNITY_EDITOR /// <summary> /// Unity OnGUI. /// /// Handles text input when there is no device keyboard in the editor. /// </summary> public void OnGUI() { if (m_displayGuiTextInput) { Rect textBoxRect = new Rect(100, Screen.height - 200, Screen.width - 200, 100); Rect okButtonRect = textBoxRect; okButtonRect.y += 100; okButtonRect.width /= 2; Rect cancelButtonRect = okButtonRect; cancelButtonRect.x = textBoxRect.center.x; GUI.SetNextControlName("TextField"); GUIStyle customTextFieldStyle = new GUIStyle(GUI.skin.textField); customTextFieldStyle.alignment = TextAnchor.MiddleCenter; m_guiTextInputContents = GUI.TextField(textBoxRect, m_guiTextInputContents, customTextFieldStyle); GUI.FocusControl("TextField"); if (GUI.Button(okButtonRect, "OK") || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) { m_displayGuiTextInput = false; m_guiTextInputResult = true; } else if (GUI.Button(cancelButtonRect, "Cancel")) { m_displayGuiTextInput = false; m_guiTextInputResult = false; } } } #endif /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { if (permissionsGranted) { RefreshAreaDescriptionList(); } } /// <summary> /// This is called when successfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// This is called each time a Tango event happens. /// </summary> /// <param name="tangoEvent">Tango event.</param> public void OnTangoEventAvailableEventHandler(Tango.TangoEvent tangoEvent) { // We will not have the saving progress when the learning mode is off. if (!m_tangoApplication.m_areaDescriptionLearningMode) { return; } if (tangoEvent.type == TangoEnums.TangoEventType.TANGO_EVENT_AREA_LEARNING && tangoEvent.event_key == "AreaDescriptionSaveProgress") { m_savingText.text = "Saving... " + Mathf.RoundToInt(float.Parse(tangoEvent.event_value) * 100) + "%"; } } /// <summary> /// Refresh the UI list of Area Descriptions. /// </summary> public void RefreshAreaDescriptionList() { AreaDescription[] areaDescriptions = AreaDescription.GetList(); _SelectAreaDescription(null); // Always remove all old children. foreach (Transform child in m_listParent) { Destroy(child.gameObject); } if (areaDescriptions != null) { // Add new children ToggleGroup toggleGroup = GetComponent<ToggleGroup>(); foreach (AreaDescription areaDescription in areaDescriptions) { AreaDescriptionListElement button = GameObject.Instantiate(m_listElement) as AreaDescriptionListElement; button.m_areaDescriptionName.text = areaDescription.GetMetadata().m_name; button.m_areaDescriptionUUID.text = areaDescription.m_uuid; button.m_toggle.group = toggleGroup; // Ensure the lambda gets a copy of the reference to areaDescription in its current state. // (See https://resnikb.wordpress.com/2009/06/17/c-lambda-and-foreach-variable/) AreaDescription lambdaParam = areaDescription; button.m_toggle.onValueChanged.AddListener((value) => _OnAreaDescriptionToggleChanged(lambdaParam, value)); button.transform.SetParent(m_listParent, false); } m_listEmptyText.gameObject.SetActive(false); } else { m_listEmptyText.gameObject.SetActive(true); } } /// <summary> /// Start quality mode, creating a brand new Area Description. /// </summary> public void NewAreaDescription() { m_tangoApplication.Startup(null); // Disable the management UI, we are now in the world. m_managementRoot.SetActive(false); m_qualityRoot.SetActive(true); } /// <summary> /// Start quality mode, extending an existing Area Description. /// </summary> public void ExtendSelectedAreaDescription() { if (m_selectedAreaDescription == null) { AndroidHelper.ShowAndroidToastMessage("You must have a selected Area Description to extend"); return; } m_tangoApplication.Startup(m_selectedAreaDescription); // Disable the management UI, we are now in the world. m_managementRoot.SetActive(false); m_qualityRoot.SetActive(true); } /// <summary> /// Import an Area Description. /// </summary> public void ImportAreaDescription() { StartCoroutine(_DoImportAreaDescription()); } /// <summary> /// Export an Area Description. /// </summary> public void ExportSelectedAreaDescription() { if (m_selectedAreaDescription != null) { StartCoroutine(_DoExportAreaDescription(m_selectedAreaDescription)); } } /// <summary> /// Delete the selected Area Description. /// </summary> public void DeleteSelectedAreaDescription() { if (m_selectedAreaDescription != null) { m_selectedAreaDescription.Delete(); RefreshAreaDescriptionList(); } } /// <summary> /// Save changes made to the selected Area Description's metadata. /// </summary> public void SaveSelectedAreaDescriptionMetadata() { if (m_selectedAreaDescription != null && m_selectedMetadata != null) { m_selectedMetadata.m_name = m_detailsEditableName.text; double.TryParse(m_detailsEditablePosX.text, out m_selectedMetadata.m_transformationPosition[0]); double.TryParse(m_detailsEditablePosY.text, out m_selectedMetadata.m_transformationPosition[1]); double.TryParse(m_detailsEditablePosZ.text, out m_selectedMetadata.m_transformationPosition[2]); double.TryParse(m_detailsEditableRotQX.text, out m_selectedMetadata.m_transformationRotation[0]); double.TryParse(m_detailsEditableRotQY.text, out m_selectedMetadata.m_transformationRotation[1]); double.TryParse(m_detailsEditableRotQZ.text, out m_selectedMetadata.m_transformationRotation[2]); double.TryParse(m_detailsEditableRotQW.text, out m_selectedMetadata.m_transformationRotation[3]); m_selectedAreaDescription.SaveMetadata(m_selectedMetadata); RefreshAreaDescriptionList(); } } /// <summary> /// When in quality mode, save the current Area Description and switch back to management mode. /// </summary> public void SaveCurrentAreaDescription() { StartCoroutine(_DoSaveCurrentAreaDescription()); } /// <summary> /// Actually do the Area Description import. /// /// This runs over multiple frames, so a Unity coroutine is used. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoImportAreaDescription() { if (TouchScreenKeyboard.visible) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("/sdcard/", TouchScreenKeyboardType.Default, false); while (!kb.done && !kb.wasCanceled) { yield return null; } if (kb.done) { AreaDescription.ImportFromFile(kb.text); } } /// <summary> /// Actually do the Area description export. /// /// This runs over multiple frames, so a Unity coroutine is used. /// </summary> /// <returns>Coroutine IEnumerator.</returns> /// <param name="areaDescription">Area Description to export.</param> private IEnumerator _DoExportAreaDescription(AreaDescription areaDescription) { if (TouchScreenKeyboard.visible) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("/sdcard/", TouchScreenKeyboardType.Default, false); while (!kb.done && !kb.wasCanceled) { yield return null; } if (kb.done) { areaDescription.ExportToFile(kb.text); } } /// <summary> /// Called every time an Area Description toggle changes state. /// </summary> /// <param name="areaDescription">Area Description the toggle is for.</param> /// <param name="value">The new state of the toggle.</param> private void _OnAreaDescriptionToggleChanged(AreaDescription areaDescription, bool value) { if (value) { _SelectAreaDescription(areaDescription); } else { _SelectAreaDescription(null); } } /// <summary> /// Select a specific Area Description to show details. /// </summary> /// <param name="areaDescription">Area Description to show details for, or <c>null</c> if details should be hidden.</param> private void _SelectAreaDescription(AreaDescription areaDescription) { m_selectedAreaDescription = areaDescription; if (areaDescription != null) { m_selectedMetadata = areaDescription.GetMetadata(); m_detailsParent.gameObject.SetActive(true); m_detailsDate.text = m_selectedMetadata.m_dateTime.ToLongDateString() + ", " + m_selectedMetadata.m_dateTime.ToLongTimeString(); m_detailsEditableName.text = m_selectedMetadata.m_name; m_detailsEditablePosX.text = m_selectedMetadata.m_transformationPosition[0].ToString(); m_detailsEditablePosY.text = m_selectedMetadata.m_transformationPosition[1].ToString(); m_detailsEditablePosZ.text = m_selectedMetadata.m_transformationPosition[2].ToString(); m_detailsEditableRotQX.text = m_selectedMetadata.m_transformationRotation[0].ToString(); m_detailsEditableRotQY.text = m_selectedMetadata.m_transformationRotation[1].ToString(); m_detailsEditableRotQZ.text = m_selectedMetadata.m_transformationRotation[2].ToString(); m_detailsEditableRotQW.text = m_selectedMetadata.m_transformationRotation[3].ToString(); } else { m_selectedMetadata = null; m_detailsParent.gameObject.SetActive(false); } } /// <summary> /// Actually do the Area Description save. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoSaveCurrentAreaDescription() { #if UNITY_EDITOR // Work around lack of on-screen keyboard in editor: if (m_displayGuiTextInput || m_saveThread != null) { yield break; } m_displayGuiTextInput = true; m_guiTextInputContents = "Unnamed"; while (m_displayGuiTextInput) { yield return null; } #else if (TouchScreenKeyboard.visible || m_saveThread != null) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("Unnamed"); while (!kb.done && !kb.wasCanceled) { yield return null; } // Store name so it is available when we use it from thread delegate. var fileNameFromKeyboard = kb.text; #endif // Save the text in a background thread. m_savingTextParent.gameObject.SetActive(true); m_saveThread = new Thread(delegate() { // Save the name put in with the Area Description. AreaDescription areaDescription = AreaDescription.SaveCurrent(); AreaDescription.Metadata metadata = areaDescription.GetMetadata(); #if UNITY_EDITOR metadata.m_name = m_guiTextInputContents; #else metadata.m_name = fileNameFromKeyboard; #endif areaDescription.SaveMetadata(metadata); }); m_saveThread.Start(); } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace TMAPIv4 { /// <summary> /// Subscriber records contain the details of an individual recipient of communcations /// (email, SMS, and so forth); typically this includes one or more addresses along /// with supporting information such as first and last names, date of birth, and /// other user-defined data. /// </summary> public class Subscriber : Record { /// <summary> /// Instantiate an empty Subscriber object. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to which /// the subscriber belongs. /// </param> public Subscriber(Context context) : base(context) { this.resourceType = "subscriber"; } /// <summary> /// ID of the TaguchiMail record. /// </summary> public string RecordId { get { return backing["id"].ToString(); } } /// <summary> /// External ID/reference, intended to store external application primary keys. /// /// If not null, this field must be unique. /// </summary> public string Ref { get { return (string)backing["ref"]; } set { backing["ref"] = new JValue(value); } } /// <summary> /// Title (Mr, Mrs etc) /// </summary> public string Title { get { return (string)backing["title"]; } set { backing["title"] = new JValue(value); } } /// <summary> /// First (given) name /// </summary> public string FirstName { get { return (string)backing["firstname"]; } set { backing["firstname"] = new JValue(value); } } /// <summary> /// Last (family) name /// </summary> public string LastName { get { return (string)backing["lastname"]; } set { backing["lastname"] = new JValue(value); } } /// <summary> /// Notifications field, can store arbitrary application data /// </summary> public string Notifications { get { return (string)backing["notifications"]; } set { backing["notifications"] = new JValue(value); } } /// <summary> /// Extra field, can store arbitrary application data /// </summary> public string Extra { get { return (string)backing["extra"]; } set { backing["extra"] = new JValue(value); } } /// <summary> /// Phone number /// </summary> public string Phone { get { return (string)backing["phone"]; } set { backing["phone"] = new JValue(value); } } /// <summary> /// Date of birth /// </summary> public string Dob //XXX: Should be a date type, format is ISO8601 { get { return (string)backing["dob"]; } set { backing["dob"] = new JValue(value); } } /// <summary> /// Postal address line 1 /// </summary> public string Address { get { return (string)backing["address"]; } set { backing["address"] = new JValue(value); } } /// <summary> /// Postal address line 2 /// </summary> public string Address2 { get { return (string)backing["address2"]; } set { backing["address2"] = new JValue(value); } } /// <summary> /// Postal address line 3 /// </summary> public string Address3 { get { return (string)backing["address3"]; } set { backing["address3"] = new JValue(value); } } /// <summary> /// Postal address city, suburb or locality /// </summary> public string Suburb { get { return (string)backing["suburb"]; } set { backing["suburb"] = new JValue(value); } } /// <summary> /// Postal address state or region /// </summary> public string State { get { return (string)backing["state"]; } set { backing["state"] = new JValue(value); } } /// <summary> /// Postal address country /// </summary> public string Country { get { return (string)backing["country"]; } set { backing["country"] = new JValue(value); } } /// <summary> /// Postal code /// </summary> public string Postcode { get { return (string)backing["postcode"]; } set { backing["postcode"] = new JValue(value); } } /// <summary> /// Gender (M/F, male/female) /// </summary> public string Gender { get { return (string)backing["gender"]; } set { backing["gender"] = new JValue(value); } } /// <summary> /// Email address. If external ID is null, this must be unique. /// </summary> public string Email { get { return (string)backing["email"]; } set { backing["email"] = new JValue(value); } } /// <summary> /// Social media influence rating. Ordinal positive integer scale; higher /// values mean more public profile data, more status updates, and/or more /// friends. Read-only as this is caculated by TaguchiMail's social media /// subsystem. /// </summary> public int SocialRating { get { return (int)backing["social_rating"]; } } /// <summary> /// Social media aggregate profile. JSON data structure similar to the /// OpenSocial v1.1 Person schema. /// </summary> public string SocialProfile { get { return (string)backing["social_profile"]; } } /// <summary> /// Date/time at which this subscriber globally unsubscribed (or null). /// </summary> public string UnsubscribeDateTime { get { return (string)backing["unsubscribed"]; } set { backing["unsubscribed"] = new JValue(value); } } /// <summary> /// Date/time at which this subscriber's email address was marked as invalid (or null). /// </summary> public string BounceDateTime { get { return (string)backing["bounced"]; } set { backing["bounced"] = new JValue(value); } } /// <summary> /// Arbitrary application XML data store. /// </summary> public string XmlData { get { return (string)backing["data"]; } set { backing["data"] = new JValue(value); } } /// <summary> /// Retrieve a custom field value by field name. /// </summary> /// <param name="field"> /// A <see cref="System.String"/> indicating the custom field to retrieve. /// </param> /// <returns> /// A <see cref="System.String"/> containing the custom field value. /// </returns> public string GetCustomField(string field) { if (backing["custom_fields"] == null) { backing["custom_fields"] = new JArray(); } foreach (JObject field_data in backing["custom_fields"]) { if (((string)field_data["field"]).Equals(field)) { return (string)field_data["data"]; } } return null; } /// <summary> /// Set a custom field value by field. /// </summary> /// <param name="field"> /// A <see cref="System.String"/> containing the name of the field to set. /// /// If a field with that name is already defined for this subscriber, the new /// value will overwrite the old one. /// </param> /// <param name="data"> /// A <see cref="System.String"/> containing the field's data. If a field is intended /// to store array or other complex data types, this should be JSON-encoded (or /// serialized to XML depending on application preference). /// </param> public void SetCustomField(string field, string data) { if (backing["custom_fields"] == null) { backing["custom_fields"] = new JArray(); } for (int i = 0; i < ((JArray)backing["custom_fields"]).Count; i++) { if (((string)backing["custom_fields"][i]["field"]).Equals(field)) { backing["custom_fields"][i]["data"] = new JValue(data); return; } } // field was not found in the array, so add it JObject cf = new JObject(); cf.Add("field", new JValue(field)); cf.Add("data", new JValue(data)); ((JArray)backing["custom_fields"]).Add(cf); } /// <summary> /// Check the subscription status of a specific list. /// </summary> /// <param name="listId"> /// A <see cref="System.String"/> containing the list ID to check subscription status for. /// </param> /// <returns> /// A <see cref="System.Boolean"/> indicating whether or not the subscriber is subscribed /// to the list. /// </returns> public bool IsSubscribedToList(string listId) { if (backing["lists"] == null) { backing["lists"] = new JArray(); } foreach (JObject list in backing["lists"]) { if (list["list_id"].ToString().Equals(listId)) { if ((string)list["unsubscribed"] == null) { return true; } else { return false; } } } return false; } public bool IsSubscribedToList(SubscriberList list) { return this.IsSubscribedToList(list.RecordId); } /// <summary> /// Retrieve the subscription option (arbitrary application data) for a specific list. /// </summary> /// <param name="listId"> /// A <see cref="System.String"/> containing the list ID to retrieve subscription option for. /// </param> /// <returns> /// A <see cref="System.String"/> containing the subscription option. /// </returns> public string GetSubscriptionOption(string listId) { if (backing["lists"] == null) { backing["lists"] = new JArray(); } foreach (JObject list in backing["lists"]) { if (list["list_id"].ToString().Equals(listId)) { return (string)list["option"]; } } return null; } public string GetSubscriptionOption(SubscriberList list) { return this.GetSubscriptionOption(list.RecordId); } /// <summary> /// Check the unsubscription status of a specific list. /// </summary> /// <param name="listId"> /// A <see cref="System.String"/> containing the list ID to check unsubscription status for. /// </param> /// <returns> /// A <see cref="System.Boolean"/> indicating whether or not the subscriber is unsubscribed /// to the list. /// </returns> public bool IsUnsubscribedFromList(string listId) { if (backing["lists"] == null) { backing["lists"] = new JArray(); } foreach (JObject list in backing["lists"]) { if (list["list_id"].ToString().Equals(listId)) { if ((string)list["unsubscribed"] == null) { return false; } else { return true; } } } return false; } public bool IsUnsubscribedFromList(SubscriberList list) { return this.IsUnsubscribedFromList(list.RecordId); } /// <summary> /// Retrieve all lists to which this record is subscribed. /// </summary> /// <returns> /// A <see cref="System.String[]"/> containing subscribed list IDs. /// </returns> public string[] GetSubscribedListIds() { if (backing["lists"] == null) { backing["lists"] = new JArray(); } List<string> lists = new List<string>(); foreach (JObject list in backing["lists"]) { if ((string)list["unsubscribed"] == null) { lists.Add(list["list_id"].ToString()); } } return lists.ToArray(); } public SubscriberList[] GetSubscribedLists() { string[] listIds = this.GetSubscribedListIds(); List<SubscriberList> lists = new List<SubscriberList>(); foreach (string listId in listIds) { lists.Add(SubscriberList.Get(this.context, listId, null)); } return lists.ToArray(); } /// <summary> /// Retrieve all lists from which this record is unsubscribed. /// </summary> /// <returns> /// A <see cref="System.String[]"/> containing unsubscribed list IDs. /// </returns> public string[] GetUnsubscribedListIds() { if (backing["lists"] == null) { backing["lists"] = new JArray(); } List<string> lists = new List<string>(); foreach (JObject list in backing["lists"]) { if ((string)list["unsubscribed"] != null) { lists.Add(list["list_id"].ToString()); } } return lists.ToArray(); } public SubscriberList[] GetUnsubscribedLists() { string[] listIds = this.GetUnsubscribedListIds(); List<SubscriberList> lists = new List<SubscriberList>(); foreach (string listId in listIds) { lists.Add(SubscriberList.Get(this.context, listId, null)); } return lists.ToArray(); } /// <summary> /// Add the subscriber to a specific list, resetting the unsubscribe flag if /// previously set. /// </summary> /// <param name="listId"> /// A <see cref="System.String"/> containing the list ID which should be added. /// </param> /// <param name="option"> /// A <see cref="System.String"/> containing the list subscription option /// (arbitarary application data). /// </param> public void SubscribeToList(string listId, string option) { if (backing["lists"] == null) { backing["lists"] = new JArray(); } for (int i = 0; i < ((JArray)backing["lists"]).Count; i++) { if (backing["lists"][i]["list_id"].ToString().Equals(listId)) { backing["lists"][i]["option"] = new JValue(option); backing["lists"][i]["unsubscribed"] = null; return; } } // list was not found in the array, so add it JObject list = new JObject(); list.Add("list_id", new JValue(System.Convert.ToInt64(listId, 10))); list.Add("option", new JValue(option)); ((JArray)backing["lists"]).Add(list); } public void SubscribeToList(SubscriberList list, string option) { this.SubscribeToList(list.RecordId, option); } /// <summary> /// Unsubscribe from a specific list, adding the list if not already subscribed. /// </summary> /// <param name="listId"> /// A <see cref="System.String"/> containing the list ID from which the record /// should be unsubscribed. /// </param> public void UnsubscribeFromList(string listId) { if (backing["lists"] == null) { backing["lists"] = new JArray(); } for (int i = 0; i < ((JArray)backing["lists"]).Count; i++) { if (backing["lists"][i]["list_id"].ToString().Equals(listId) && (string)backing["lists"][i]["unsubscribed"] == null) { backing["lists"][i]["unsubscribed"] = new JValue(true); return; } } // list was not found in the array, so add it in the unsubscribed state JObject list = new JObject(); list.Add("list_id", new JValue(System.Convert.ToInt64(listId, 10))); list.Add("unsubscribed", new JValue(true)); ((JArray)backing["lists"]).Add(list); } public void UnsubscribeFromList(SubscriberList list) { this.UnsubscribeFromList(list.RecordId); } /// <summary> /// Create this record in the TaguchiMail database if it doesn't already exist /// (based on a search for records with the same ExternalRef or Email in that order). /// /// If it does, simply update what's already in the database. Fields not written /// to the backing store (via property update) will not be overwritten in the database. /// </summary> public void CreateOrUpdate() { JArray data = new JArray(); data.Add(this.backing); JArray results = JArray.Parse(context.MakeRequest(this.resourceType, "CREATEORUPDATE", null, data.ToString(), null, null)); this.backing = (JObject)results[0]; } /// <summary> /// Retrieve a single Subscriber based on its TaguchiMail identifier. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="recordId"> /// A <see cref="System.String"/> containing the subscriber's unique TaguchiMail identifier. /// </param> /// <returns> /// The <see cref="Subscriber"/> with that ID. /// </returns> public static Subscriber Get(Context context, string recordId, Dictionary<string, string> parameters) { JArray results = JArray.Parse(context.MakeRequest("subscriber", "GET", recordId, null, parameters, null)); Subscriber rec = new Subscriber(context); rec.backing = (JObject)results[0]; return rec; } /// <summary> /// Retrieve a list of Subscribers based on a query. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="sort"> /// A <see cref="System.String"/> indicating which of the record's fields should be used to /// sort the output. /// </param> /// <param name="order"> /// A <see cref="System.String"/> containing either 'asc' or 'desc', indicating whether the /// result list should be returned in ascending or descending order. /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> indicating the index of the first record to be returned in /// the list. /// </param> /// <param name="limit"> /// A <see cref="System.Int32"/> indicating the maximum number of records to return. /// </param> /// <param name="query"> /// An <see cref="System.String[]"/> of query predicates, each of the form: /// [field]-[operator]-[value] /// where [field] is one of the defined resource fields, [operator] is one of the below-listed comparison operators, /// and [value] is a string value to which the field should be compared. /// /// Supported operators: /// * eq: mapped to SQL '=', tests for equality between [field] and [value] (case-sensitive for strings); /// * neq: mapped to SQL '!=', tests for inequality between [field] and [value] (case-sensitive for strings); /// * lt: mapped to SQL '&lt;', tests if [field] is less than [value]; /// * gt: mapped to SQL '&gt;', tests if [field] is greater than [value]; /// * lte: mapped to SQL '&lt;=', tests if [field] is less than or equal to [value]; /// * gte: mapped to SQL '&gt;=', tests if [field] is greater than or equal to [value]; /// * re: mapped to PostgreSQL '~', interprets [value] as a POSIX regular expression and tests if [field] matches it; /// * rei: mapped to PostgreSQL '~*', performs a case-insensitive POSIX regular expression match; /// * like: mapped to SQL 'LIKE' (case-sensitive); /// * is: mapped to SQL 'IS', should be used to test for NULL values in the database as [field]-eq-null is always false; /// * nt: mapped to SQL 'IS NOT', should be used to test for NOT NULL values in the database as [field]-neq-null is always false. /// </param> /// <returns> /// A <see cref="Subscriber[]"/> matching the query. /// </returns> public static Subscriber[] Find(Context context, string sort, string order, int offset, int limit, string[] query) { Dictionary<string,string> parameters = new Dictionary<string, string>(); parameters["sort"] = sort; parameters["order"] = order; parameters["offset"] = offset.ToString(); parameters["limit"] = limit.ToString(); JArray results = JArray.Parse(context.MakeRequest("subscriber", "GET", null, null, parameters, query)); List<Subscriber> recordSet = new List<Subscriber>(); foreach (var result in results) { Subscriber rec = new Subscriber(context); rec.backing = (JObject)result; recordSet.Add(rec); } return recordSet.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { /// <summary> /// An abstract base class that provides functionality for 'Bitmap', 'Icon', 'Cursor', and 'Metafile' descended classes. /// </summary> [ImmutableObject(true)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] #if NETCOREAPP [TypeConverter("System.Drawing.ImageConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")] #endif public abstract partial class Image : MarshalByRefObject, IDisposable, ICloneable, ISerializable { // The signature of this delegate is incorrect. The signature of the corresponding // native callback function is: // extern "C" { // typedef BOOL (CALLBACK * ImageAbort)(VOID *); // typedef ImageAbort DrawImageAbort; // typedef ImageAbort GetThumbnailImageAbort; // } // However, as this delegate is not used in both GDI 1.0 and 1.1, we choose not // to modify it, in order to preserve compatibility. public delegate bool GetThumbnailImageAbort(); internal IntPtr nativeImage; private object _userData; // used to work around lack of animated gif encoder... rarely set... private byte[] _rawData; [Localizable(false)] [DefaultValue(null)] public object Tag { get => _userData; set => _userData = value; } private protected Image() { } #pragma warning disable CA2229 // Implement Serialization constructor private protected Image(SerializationInfo info, StreamingContext context) #pragma warning restore CA2229 { byte[] dat = (byte[])info.GetValue("Data", typeof(byte[])); // Do not rename (binary serialization) try { SetNativeImage(InitializeFromStream(new MemoryStream(dat))); } catch (ExternalException) { } catch (ArgumentException) { } catch (OutOfMemoryException) { } catch (InvalidOperationException) { } catch (NotImplementedException) { } catch (FileNotFoundException) { } } void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { using (MemoryStream stream = new MemoryStream()) { Save(stream); si.AddValue("Data", stream.ToArray(), typeof(byte[])); // Do not rename (binary serialization) } } /// <summary> /// Creates an <see cref='Image'/> from the specified file. /// </summary> public static Image FromFile(string filename) => FromFile(filename, false); public static Image FromFile(string filename, bool useEmbeddedColorManagement) { if (!File.Exists(filename)) { // Throw a more specific exception for invalid paths that are null or empty, // contain invalid characters or are too long. filename = Path.GetFullPath(filename); throw new FileNotFoundException(filename); } // GDI+ will read this file multiple times. Get the fully qualified path // so if our app changes default directory we won't get an error filename = Path.GetFullPath(filename); IntPtr image = IntPtr.Zero; if (useEmbeddedColorManagement) { Gdip.CheckStatus(Gdip.GdipLoadImageFromFileICM(filename, out image)); } else { Gdip.CheckStatus(Gdip.GdipLoadImageFromFile(filename, out image)); } ValidateImage(image); Image img = CreateImageObject(image); EnsureSave(img, filename, null); return img; } /// <summary> /// Creates an <see cref='Image'/> from the specified data stream. /// </summary> public static Image FromStream(Stream stream) => Image.FromStream(stream, false); public static Image FromStream(Stream stream, bool useEmbeddedColorManagement) => FromStream(stream, useEmbeddedColorManagement, true); /// <summary> /// Cleans up Windows resources for this <see cref='Image'/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Cleans up Windows resources for this <see cref='Image'/>. /// </summary> ~Image() => Dispose(false); /// <summary> /// Saves this <see cref='Image'/> to the specified file. /// </summary> public void Save(string filename) => Save(filename, RawFormat); /// <summary> /// Gets the width and height of this <see cref='Image'/>. /// </summary> public SizeF PhysicalDimension { get { float width; float height; int status = Gdip.GdipGetImageDimension(new HandleRef(this, nativeImage), out width, out height); Gdip.CheckStatus(status); return new SizeF(width, height); } } /// <summary> /// Gets the width and height of this <see cref='Image'/>. /// </summary> public Size Size => new Size(Width, Height); /// <summary> /// Gets the width of this <see cref='Image'/>. /// </summary> [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Width { get { int width; int status = Gdip.GdipGetImageWidth(new HandleRef(this, nativeImage), out width); Gdip.CheckStatus(status); return width; } } /// <summary> /// Gets the height of this <see cref='Image'/>. /// </summary> [DefaultValue(false)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Height { get { int height; int status = Gdip.GdipGetImageHeight(new HandleRef(this, nativeImage), out height); Gdip.CheckStatus(status); return height; } } /// <summary> /// Gets the horizontal resolution, in pixels-per-inch, of this <see cref='Image'/>. /// </summary> public float HorizontalResolution { get { float horzRes; int status = Gdip.GdipGetImageHorizontalResolution(new HandleRef(this, nativeImage), out horzRes); Gdip.CheckStatus(status); return horzRes; } } /// <summary> /// Gets the vertical resolution, in pixels-per-inch, of this <see cref='Image'/>. /// </summary> public float VerticalResolution { get { float vertRes; int status = Gdip.GdipGetImageVerticalResolution(new HandleRef(this, nativeImage), out vertRes); Gdip.CheckStatus(status); return vertRes; } } /// <summary> /// Gets attribute flags for this <see cref='Image'/>. /// </summary> [Browsable(false)] public int Flags { get { int flags; int status = Gdip.GdipGetImageFlags(new HandleRef(this, nativeImage), out flags); Gdip.CheckStatus(status); return flags; } } /// <summary> /// Gets the format of this <see cref='Image'/>. /// </summary> public ImageFormat RawFormat { get { Guid guid = new Guid(); int status = Gdip.GdipGetImageRawFormat(new HandleRef(this, nativeImage), ref guid); Gdip.CheckStatus(status); return new ImageFormat(guid); } } /// <summary> /// Gets the pixel format for this <see cref='Image'/>. /// </summary> public PixelFormat PixelFormat { get { int status = Gdip.GdipGetImagePixelFormat(new HandleRef(this, nativeImage), out PixelFormat format); return (status != Gdip.Ok) ? PixelFormat.Undefined : format; } } /// <summary> /// Returns the number of frames of the given dimension. /// </summary> public int GetFrameCount(FrameDimension dimension) { Guid dimensionID = dimension.Guid; Gdip.CheckStatus(Gdip.GdipImageGetFrameCount(new HandleRef(this, nativeImage), ref dimensionID, out int count)); return count; } /// <summary> /// Selects the frame specified by the given dimension and index. /// </summary> public int SelectActiveFrame(FrameDimension dimension, int frameIndex) { Guid dimensionID = dimension.Guid; Gdip.CheckStatus(Gdip.GdipImageSelectActiveFrame(new HandleRef(this, nativeImage), ref dimensionID, frameIndex)); return 0; } public void RotateFlip(RotateFlipType rotateFlipType) { int status = Gdip.GdipImageRotateFlip(new HandleRef(this, nativeImage), unchecked((int)rotateFlipType)); Gdip.CheckStatus(status); } /// <summary> /// Removes the specified property item from this <see cref='Image'/>. /// </summary> public void RemovePropertyItem(int propid) { int status = Gdip.GdipRemovePropertyItem(new HandleRef(this, nativeImage), propid); Gdip.CheckStatus(status); } /// <summary> /// Returns information about the codecs used for this <see cref='Image'/>. /// </summary> public EncoderParameters GetEncoderParameterList(Guid encoder) { EncoderParameters p; Gdip.CheckStatus(Gdip.GdipGetEncoderParameterListSize( new HandleRef(this, nativeImage), ref encoder, out int size)); if (size <= 0) return null; IntPtr buffer = Marshal.AllocHGlobal(size); try { Gdip.CheckStatus(Gdip.GdipGetEncoderParameterList( new HandleRef(this, nativeImage), ref encoder, size, buffer)); p = EncoderParameters.ConvertFromMemory(buffer); } finally { Marshal.FreeHGlobal(buffer); } return p; } /// <summary> /// Creates a <see cref='Bitmap'/> from a Windows handle. /// </summary> public static Bitmap FromHbitmap(IntPtr hbitmap) => FromHbitmap(hbitmap, IntPtr.Zero); /// <summary> /// Creates a <see cref='Bitmap'/> from the specified Windows handle with the specified color palette. /// </summary> public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette) { Gdip.CheckStatus(Gdip.GdipCreateBitmapFromHBITMAP(hbitmap, hpalette, out IntPtr bitmap)); return new Bitmap(bitmap); } /// <summary> /// Returns a value indicating whether the pixel format is extended. /// </summary> public static bool IsExtendedPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormat.Extended) != 0; } /// <summary> /// Returns a value indicating whether the pixel format is canonical. /// </summary> public static bool IsCanonicalPixelFormat(PixelFormat pixfmt) { // Canonical formats: // // PixelFormat32bppARGB // PixelFormat32bppPARGB // PixelFormat64bppARGB // PixelFormat64bppPARGB return (pixfmt & PixelFormat.Canonical) != 0; } internal void SetNativeImage(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException(SR.NativeHandle0, nameof(handle)); nativeImage = handle; } // Multi-frame support /// <summary> /// Gets an array of GUIDs that represent the dimensions of frames within this <see cref='Image'/>. /// </summary> [Browsable(false)] public unsafe Guid[] FrameDimensionsList { get { Gdip.CheckStatus(Gdip.GdipImageGetFrameDimensionsCount(new HandleRef(this, nativeImage), out int count)); Debug.Assert(count >= 0, "FrameDimensionsList returns bad count"); if (count <= 0) return Array.Empty<Guid>(); Guid[] guids = new Guid[count]; fixed (Guid* g = guids) { Gdip.CheckStatus(Gdip.GdipImageGetFrameDimensionsList(new HandleRef(this, nativeImage), g, count)); } return guids; } } /// <summary> /// Returns the size of the specified pixel format. /// </summary> public static int GetPixelFormatSize(PixelFormat pixfmt) { return (unchecked((int)pixfmt) >> 8) & 0xFF; } /// <summary> /// Returns a value indicating whether the pixel format contains alpha information. /// </summary> public static bool IsAlphaPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormat.Alpha) != 0; } internal static Image CreateImageObject(IntPtr nativeImage) { Gdip.CheckStatus(Gdip.GdipGetImageType(nativeImage, out int type)); switch ((ImageType)type) { case ImageType.Bitmap: return new Bitmap(nativeImage); case ImageType.Metafile: return new Metafile(nativeImage); default: throw new ArgumentException(SR.InvalidImage); } } internal static unsafe void EnsureSave(Image image, string filename, Stream dataStream) { if (image.RawFormat.Equals(ImageFormat.Gif)) { bool animatedGif = false; Gdip.CheckStatus(Gdip.GdipImageGetFrameDimensionsCount(new HandleRef(image, image.nativeImage), out int dimensions)); if (dimensions <= 0) { return; } Span<Guid> guids = dimensions < 16 ? stackalloc Guid[dimensions] : new Guid[dimensions]; fixed (Guid* g = &MemoryMarshal.GetReference(guids)) { Gdip.CheckStatus(Gdip.GdipImageGetFrameDimensionsList(new HandleRef(image, image.nativeImage), g, dimensions)); } Guid timeGuid = FrameDimension.Time.Guid; for (int i = 0; i < dimensions; i++) { if (timeGuid == guids[i]) { animatedGif = image.GetFrameCount(FrameDimension.Time) > 1; break; } } if (animatedGif) { try { Stream created = null; long lastPos = 0; if (dataStream != null) { lastPos = dataStream.Position; dataStream.Position = 0; } try { if (dataStream == null) { created = dataStream = File.OpenRead(filename); } image._rawData = new byte[(int)dataStream.Length]; dataStream.Read(image._rawData, 0, (int)dataStream.Length); } finally { if (created != null) { created.Close(); } else { dataStream.Position = lastPos; } } } // possible exceptions for reading the filename catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } // possible exceptions for setting/getting the position inside dataStream catch (NotSupportedException) { } catch (ObjectDisposedException) { } // possible exception when reading stuff into dataStream catch (ArgumentException) { } } } } } }
// 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.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using Xunit; namespace System.ComponentModel.Composition { public class ImportEngineTests { [Fact] public void PreviewImports_Successful_NoAtomicComposition_ShouldBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); engine.PreviewImports(importer, null); Assert.Throws<ChangeRejectedException>(() => exportProvider.AddExport("Value", 22)); Assert.Throws<ChangeRejectedException>(() => exportProvider.RemoveExport("Value")); GC.KeepAlive(importer); } [Fact] public void PreviewImports_Unsuccessful_NoAtomicComposition_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); Assert.Throws<CompositionException>(() => engine.PreviewImports(importer, null)); exportProvider.AddExport("Value", 22); exportProvider.AddExport("Value", 23); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void PreviewImports_Successful_AtomicComposition_Completeted_ShouldBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); using (var atomicComposition = new AtomicComposition()) { engine.PreviewImports(importer, atomicComposition); atomicComposition.Complete(); } Assert.Throws<ChangeRejectedException>(() => exportProvider.AddExport("Value", 22)); Assert.Throws<ChangeRejectedException>(() => exportProvider.RemoveExport("Value")); GC.KeepAlive(importer); } [Fact] public void PreviewImports_Successful_AtomicComposition_RolledBack_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); using (var atomicComposition = new AtomicComposition()) { engine.PreviewImports(importer, atomicComposition); // Let atomicComposition get disposed thus rolledback } exportProvider.AddExport("Value", 22); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void PreviewImports_Unsuccessful_AtomicComposition_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); using (var atomicComposition = new AtomicComposition()) { Assert.Throws<ChangeRejectedException>(() => engine.PreviewImports(importer, atomicComposition)); } exportProvider.AddExport("Value", 22); exportProvider.AddExport("Value", 23); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] [ActiveIssue(25498, TargetFrameworkMonikers.UapAot)] public void PreviewImports_ReleaseImports_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); engine.PreviewImports(importer, null); Assert.Throws<ChangeRejectedException>(() => exportProvider.AddExport("Value", 22)); Assert.Throws<ChangeRejectedException>(() => exportProvider.RemoveExport("Value")); engine.ReleaseImports(importer, null); exportProvider.AddExport("Value", 22); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void PreviewImports_MissingOptionalImport_ShouldSucceed() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrOne); var importer = PartFactory.CreateImporter(import); engine.PreviewImports(importer, null); GC.KeepAlive(importer); } [Fact] public void PreviewImports_ZeroCollectionImport_ShouldSucceed() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrMore); var importer = PartFactory.CreateImporter(import); engine.PreviewImports(importer, null); GC.KeepAlive(importer); } [Fact] public void PreviewImports_MissingOptionalImport_NonRecomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrOne, false, false); var importer = PartFactory.CreateImporter(import); engine.PreviewImports(importer, null); exportProvider.AddExport("Value", 21); exportProvider.AddExport("Value", 22); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void PreviewImports_ZeroCollectionImport_NonRecomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrMore, false, false); var importer = PartFactory.CreateImporter(import); engine.PreviewImports(importer, null); exportProvider.AddExport("Value", 21); exportProvider.AddExport("Value", 22); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_NonRecomposable_ValueShouldNotChange() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); exportProvider.AddExport("Value", 21); var import = ImportDefinitionFactory.Create("Value", false); var importer = PartFactory.CreateImporter(import); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import)); // After rejection batch failures throw ChangeRejectedException to indicate that // the failure did not affect the container Assert.Throws<ChangeRejectedException>(() => exportProvider.ReplaceExportValue("Value", 42)); Assert.Equal(21, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_Recomposable_ValueShouldChange() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); exportProvider.AddExport("Value", 21); var import = ImportDefinitionFactory.Create("Value", true); var importer = PartFactory.CreateImporter(import); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import)); exportProvider.ReplaceExportValue("Value", 42); Assert.Equal(42, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_NonRecomposable_Prerequisite_ValueShouldNotChange() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", false, true); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import)); Assert.Throws<ChangeRejectedException>(() => exportProvider.ReplaceExportValue("Value", 42)); Assert.Equal(21, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_Recomposable_Prerequisite_ValueShouldChange() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", true, true); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import)); exportProvider.ReplaceExportValue("Value", 42); Assert.Equal(42, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_OneRecomposable_OneNotRecomposable() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import1 = ImportDefinitionFactory.Create("Value", true); var import2 = ImportDefinitionFactory.Create("Value", false); var importer = PartFactory.CreateImporter(import1, import2); exportProvider.AddExport("Value", 21); engine.SatisfyImports(importer); // Initial compose values should be 21 Assert.Equal(21, importer.GetImport(import1)); Assert.Equal(21, importer.GetImport(import2)); // Reset value to ensure it doesn't get set to same value again importer.ResetImport(import1); importer.ResetImport(import2); Assert.Throws<ChangeRejectedException>(() => exportProvider.ReplaceExportValue("Value", 42)); Assert.Equal(null, importer.GetImport(import1)); Assert.Equal(null, importer.GetImport(import2)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_TwoRecomposables_SingleExportValueChanged() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import1 = ImportDefinitionFactory.Create("Value1", true); var import2 = ImportDefinitionFactory.Create("Value2", true); var importer = PartFactory.CreateImporter(import1, import2); exportProvider.AddExport("Value1", 21); exportProvider.AddExport("Value2", 23); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import1)); Assert.Equal(23, importer.GetImport(import2)); importer.ResetImport(import1); importer.ResetImport(import2); // Only change Value1 exportProvider.ReplaceExportValue("Value1", 42); Assert.Equal(42, importer.GetImport(import1)); Assert.Equal(null, importer.GetImport(import2)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_Recomposable_Unregister_ValueShouldChangeOnce() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); exportProvider.AddExport("Value", 21); var import = ImportDefinitionFactory.Create("Value", true); var importer = PartFactory.CreateImporter(import); engine.SatisfyImports(importer); Assert.Equal(21, importer.GetImport(import)); exportProvider.ReplaceExportValue("Value", 42); Assert.Equal(42, importer.GetImport(import)); engine.ReleaseImports(importer, null); exportProvider.ReplaceExportValue("Value", 666); Assert.Equal(42, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_MissingOptionalImport_NonRecomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrOne, false, false); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 20); engine.SatisfyImports(importer); Assert.Throws<ChangeRejectedException>(() => exportProvider.AddExport("Value", 21)); Assert.Throws<ChangeRejectedException>(() => exportProvider.RemoveExport("Value")); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_ZeroCollectionImport_NonRecomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrMore, false, false); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 20); engine.SatisfyImports(importer); Assert.Throws<ChangeRejectedException>(() => exportProvider.AddExport("Value", 21)); Assert.Throws<ChangeRejectedException>(() => exportProvider.RemoveExport("Value")); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_MissingOptionalImport_Recomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrOne, true, false); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 20); engine.SatisfyImports(importer); exportProvider.AddExport("Value", 21); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void SatisfyImports_ZeroCollectionImport_Recomposable_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value", ImportCardinality.ZeroOrMore, true, false); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 20); engine.SatisfyImports(importer); exportProvider.AddExport("Value", 21); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void SatisfyImportsOnce_Recomposable_ValueShouldNotChange_NoRecompositionRequested() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); exportProvider.AddExport("Value", 21); var import = ImportDefinitionFactory.Create("Value", true); var importer = PartFactory.CreateImporter(import); engine.SatisfyImportsOnce(importer); Assert.Equal(21, importer.GetImport(import)); exportProvider.ReplaceExportValue("Value", 42); Assert.Equal(21, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisifyImportsOnce_Recomposable_ValueShouldNotChange_NoRecompositionRequested_ViaNonArgumentSignature() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); exportProvider.AddExport("Value", 21); var import = ImportDefinitionFactory.Create("Value", true); var importer = PartFactory.CreateImporter(import); engine.SatisfyImportsOnce(importer); Assert.Equal(21, importer.GetImport(import)); exportProvider.ReplaceExportValue("Value", 42); Assert.Equal(21, importer.GetImport(import)); GC.KeepAlive(importer); } [Fact] public void SatisfyImportsOnce_Successful_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); exportProvider.AddExport("Value", 21); engine.SatisfyImportsOnce(importer); exportProvider.AddExport("Value", 22); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } [Fact] public void SatisfyImportsOnce_Unsuccessful_ShouldNotBlockChanges() { var exportProvider = ExportProviderFactory.CreateRecomposable(); var engine = new ImportEngine(exportProvider); var import = ImportDefinitionFactory.Create("Value"); var importer = PartFactory.CreateImporter(import); Assert.Throws<CompositionException>(() => engine.SatisfyImportsOnce(importer)); exportProvider.AddExport("Value", 22); exportProvider.AddExport("Value", 23); exportProvider.RemoveExport("Value"); GC.KeepAlive(importer); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Tools.Vhd { using System; using System.Collections.Generic; using System.IO; using Tools.Vhd.Model; using Tools.Vhd.Model.Persistence; /// <summary> /// Provides a logical stream over a virtual hard disk (VHD). /// </summary> /// <remarks> /// This stream implementation provides a "view" over a VHD, such that the /// VHD appears to be an ordinary fixed VHD file, regardless of the true physical layout. /// This stream supports any combination of differencing, dynamic disks, and fixed disks. /// </remarks> public class VirtualDiskStream : SparseStream { private long position; private VhdFile vhdFile; private IBlockFactory blockFactory; private IndexRange footerRange; private IndexRange fileDataRange; private bool isDisposed; public VirtualDiskStream(string vhdPath) { this.vhdFile = new VhdFileFactory().Create(vhdPath); this.blockFactory = vhdFile.GetBlockFactory(); footerRange = this.blockFactory.GetFooterRange(); fileDataRange = IndexRange.FromLength(0, this.Length - footerRange.Length); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override sealed long Length { get { return this.footerRange.EndIndex + 1; } } public override long Position { get { return this.position; } set { if (value < 0) throw new ArgumentException(); if (value >= this.Length) throw new EndOfStreamException(); this.position = value; } } /// <summary> /// Gets the extents of the stream that contain data. /// </summary> public override IEnumerable<StreamExtent> Extents { get { for (uint index = 0; index < blockFactory.BlockCount; index++ ) { var block = blockFactory.Create(index); if(!block.Empty) { yield return new StreamExtent { Owner = block.VhdUniqueId, StartOffset = block.LogicalRange.StartIndex, EndOffset = block.LogicalRange.EndIndex, Range = block.LogicalRange }; } } yield return new StreamExtent { Owner = vhdFile.Footer.UniqueId, StartOffset = this.footerRange.StartIndex, EndOffset = this.footerRange.EndIndex, Range = this.footerRange }; } } public DiskType DiskType { get { return this.vhdFile.DiskType; } } public DiskType RootDiskType { get { var diskType = this.vhdFile.DiskType; for(var parent = this.vhdFile.Parent; parent != null; parent = parent.Parent) { diskType = parent.DiskType; } return diskType; } } /// <summary> /// Reads the specified number of bytes from the current position. /// </summary> public override int Read(byte[] buffer, int offset, int count) { if (count <= 0) { return 0; } try { var rangeToRead = IndexRange.FromLength(this.position, count); int writtenCount = 0; if (fileDataRange.Intersection(rangeToRead) == null) { int readCountFromFooter; if (TryReadFromFooter(rangeToRead, buffer, offset, out readCountFromFooter)) { writtenCount += readCountFromFooter; } return writtenCount; } rangeToRead = fileDataRange.Intersection(rangeToRead); var startingBlock = ByteToBlock(rangeToRead.StartIndex); var endingBlock = ByteToBlock(rangeToRead.EndIndex); for(var blockIndex = startingBlock; blockIndex <= endingBlock; blockIndex++) { var currentBlock = blockFactory.Create(blockIndex); var rangeToReadInBlock = currentBlock.LogicalRange.Intersection(rangeToRead); var copyStartIndex = rangeToReadInBlock.StartIndex % blockFactory.GetBlockSize(); Buffer.BlockCopy(currentBlock.Data, (int) copyStartIndex, buffer, offset + writtenCount, (int) rangeToReadInBlock.Length); writtenCount += (int)rangeToReadInBlock.Length; } this.position += writtenCount; return writtenCount; } catch (Exception e) { throw new VhdParsingException("Invalid or Corrupted VHD file", e); } } public bool TryReadFromFooter(IndexRange rangeToRead, byte[] buffer, int offset, out int readCount) { readCount = 0; var rangeToReadFromFooter = this.footerRange.Intersection(rangeToRead); if (rangeToReadFromFooter != null) { var footerData = GenerateFooter(); var copyStartIndex = rangeToReadFromFooter.StartIndex - footerRange.StartIndex; Buffer.BlockCopy(footerData, (int)copyStartIndex, buffer, offset, (int)rangeToReadFromFooter.Length); this.position += (int)rangeToReadFromFooter.Length; readCount = (int)rangeToReadFromFooter.Length; return true; } return false; } private uint ByteToBlock(long position) { uint sectorsPerBlock = (uint) (this.blockFactory.GetBlockSize() / VhdConstants.VHD_SECTOR_LENGTH); return (uint)Math.Floor((position / VhdConstants.VHD_SECTOR_LENGTH) * 1.0m / sectorsPerBlock); } private byte[] GenerateFooter() { var footer = vhdFile.Footer.CreateCopy(); if(vhdFile.Footer.DiskType != DiskType.Fixed) { footer.HeaderOffset = VhdConstants.VHD_NO_DATA_LONG; footer.DiskType = DiskType.Fixed; footer.CreatorApplication = VhdFooterFactory.WindowsAzureCreatorApplicationName; } var serializer = new VhdFooterSerializer(footer); return serializer.ToByteArray(); } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: this.Position = offset; break; case SeekOrigin.Current: this.Position += offset; break; case SeekOrigin.End: this.Position -= offset; break; default: throw new NotSupportedException(); } return this.Position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if(!isDisposed) { if(disposing) { this.vhdFile.Dispose(); isDisposed = true; } } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// RecordingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account.Conference { public class RecordingResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum InProgress = new StatusEnum("in-progress"); public static readonly StatusEnum Paused = new StatusEnum("paused"); public static readonly StatusEnum Stopped = new StatusEnum("stopped"); public static readonly StatusEnum Processing = new StatusEnum("processing"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Absent = new StatusEnum("absent"); } public sealed class SourceEnum : StringEnum { private SourceEnum(string value) : base(value) {} public SourceEnum() {} public static implicit operator SourceEnum(string value) { return new SourceEnum(value); } public static readonly SourceEnum Dialverb = new SourceEnum("DialVerb"); public static readonly SourceEnum Conference = new SourceEnum("Conference"); public static readonly SourceEnum Outboundapi = new SourceEnum("OutboundAPI"); public static readonly SourceEnum Trunking = new SourceEnum("Trunking"); public static readonly SourceEnum Recordverb = new SourceEnum("RecordVerb"); public static readonly SourceEnum Startcallrecordingapi = new SourceEnum("StartCallRecordingAPI"); public static readonly SourceEnum Startconferencerecordingapi = new SourceEnum("StartConferenceRecordingAPI"); } private static Request BuildUpdateRequest(UpdateRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathConferenceSid + "/Recordings/" + options.PathSid + ".json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Changes the status of the recording to paused, stopped, or in-progress. Note: To use `Twilio.CURRENT`, pass it as /// recording sid. /// </summary> /// <param name="options"> Update Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Update(UpdateRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Changes the status of the recording to paused, stopped, or in-progress. Note: To use `Twilio.CURRENT`, pass it as /// recording sid. /// </summary> /// <param name="options"> Update Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> UpdateAsync(UpdateRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Changes the status of the recording to paused, stopped, or in-progress. Note: To use `Twilio.CURRENT`, pass it as /// recording sid. /// </summary> /// <param name="pathConferenceSid"> Update by unique Conference SID for the recording </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="status"> The new status of the recording </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to update </param> /// <param name="pauseBehavior"> Whether to record during a pause </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Update(string pathConferenceSid, string pathSid, RecordingResource.StatusEnum status, string pathAccountSid = null, string pauseBehavior = null, ITwilioRestClient client = null) { var options = new UpdateRecordingOptions(pathConferenceSid, pathSid, status){PathAccountSid = pathAccountSid, PauseBehavior = pauseBehavior}; return Update(options, client); } #if !NET35 /// <summary> /// Changes the status of the recording to paused, stopped, or in-progress. Note: To use `Twilio.CURRENT`, pass it as /// recording sid. /// </summary> /// <param name="pathConferenceSid"> Update by unique Conference SID for the recording </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="status"> The new status of the recording </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to update </param> /// <param name="pauseBehavior"> Whether to record during a pause </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> UpdateAsync(string pathConferenceSid, string pathSid, RecordingResource.StatusEnum status, string pathAccountSid = null, string pauseBehavior = null, ITwilioRestClient client = null) { var options = new UpdateRecordingOptions(pathConferenceSid, pathSid, status){PathAccountSid = pathAccountSid, PauseBehavior = pauseBehavior}; return await UpdateAsync(options, client); } #endif private static Request BuildFetchRequest(FetchRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathConferenceSid + "/Recordings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch an instance of a recording for a call /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch an instance of a recording for a call /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch an instance of a recording for a call /// </summary> /// <param name="pathConferenceSid"> Fetch by unique Conference SID for the recording </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(string pathConferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathConferenceSid, pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch an instance of a recording for a call /// </summary> /// <param name="pathConferenceSid"> Fetch by unique Conference SID for the recording </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(string pathConferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathConferenceSid, pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathConferenceSid + "/Recordings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a recording from your account /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a recording from your account /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a recording from your account /// </summary> /// <param name="pathConferenceSid"> Delete by the recording's conference SID </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(string pathConferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathConferenceSid, pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// Delete a recording from your account /// </summary> /// <param name="pathConferenceSid"> Delete by the recording's conference SID </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathConferenceSid, string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathConferenceSid, pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Conferences/" + options.PathConferenceSid + "/Recordings.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of recordings belonging to the call used to make the request /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of recordings belonging to the call used to make the request /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of recordings belonging to the call used to make the request /// </summary> /// <param name="pathConferenceSid"> Read by unique Conference SID for the recording </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="dateCreatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(string pathConferenceSid, string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(pathConferenceSid){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of recordings belonging to the call used to make the request /// </summary> /// <param name="pathConferenceSid"> Read by unique Conference SID for the recording </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="dateCreatedBefore"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreated"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="dateCreatedAfter"> The `YYYY-MM-DD` value of the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(string pathConferenceSid, string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(pathConferenceSid){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<RecordingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<RecordingResource> NextPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<RecordingResource> PreviousPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Converts a JSON string into a RecordingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> RecordingResource object represented by the provided JSON </returns> public static RecordingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<RecordingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The API version used to create the recording /// </summary> [JsonProperty("api_version")] public string ApiVersion { get; private set; } /// <summary> /// The SID of the Call the resource is associated with /// </summary> [JsonProperty("call_sid")] public string CallSid { get; private set; } /// <summary> /// The Conference SID that identifies the conference associated with the recording /// </summary> [JsonProperty("conference_sid")] public string ConferenceSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The start time of the recording, given in RFC 2822 format /// </summary> [JsonProperty("start_time")] public DateTime? StartTime { get; private set; } /// <summary> /// The length of the recording in seconds /// </summary> [JsonProperty("duration")] public string Duration { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The one-time cost of creating the recording. /// </summary> [JsonProperty("price")] public string Price { get; private set; } /// <summary> /// The currency used in the price property. /// </summary> [JsonProperty("price_unit")] public string PriceUnit { get; private set; } /// <summary> /// The status of the recording /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.StatusEnum Status { get; private set; } /// <summary> /// The number of channels in the final recording file as an integer /// </summary> [JsonProperty("channels")] public int? Channels { get; private set; } /// <summary> /// How the recording was created /// </summary> [JsonProperty("source")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.SourceEnum Source { get; private set; } /// <summary> /// More information about why the recording is missing, if status is `absent`. /// </summary> [JsonProperty("error_code")] public int? ErrorCode { get; private set; } /// <summary> /// How to decrypt the recording. /// </summary> [JsonProperty("encryption_details")] public object EncryptionDetails { get; private set; } /// <summary> /// The URI of the resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } private RecordingResource() { } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class ClassDefinition : TypeDefinition { [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ClassDefinition CloneNode() { return (ClassDefinition)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ClassDefinition CleanClone() { return (ClassDefinition)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.ClassDefinition; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnClassDefinition(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( ClassDefinition)node; if (_modifiers != other._modifiers) return NoMatch("ClassDefinition._modifiers"); if (_name != other._name) return NoMatch("ClassDefinition._name"); if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("ClassDefinition._attributes"); if (!Node.AllMatch(_members, other._members)) return NoMatch("ClassDefinition._members"); if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("ClassDefinition._baseTypes"); if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("ClassDefinition._genericParameters"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_attributes != null) { Attribute item = existing as Attribute; if (null != item) { Attribute newItem = (Attribute)newNode; if (_attributes.Replace(item, newItem)) { return true; } } } if (_members != null) { TypeMember item = existing as TypeMember; if (null != item) { TypeMember newItem = (TypeMember)newNode; if (_members.Replace(item, newItem)) { return true; } } } if (_baseTypes != null) { TypeReference item = existing as TypeReference; if (null != item) { TypeReference newItem = (TypeReference)newNode; if (_baseTypes.Replace(item, newItem)) { return true; } } } if (_genericParameters != null) { GenericParameterDeclaration item = existing as GenericParameterDeclaration; if (null != item) { GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode; if (_genericParameters.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { ClassDefinition clone = (ClassDefinition)FormatterServices.GetUninitializedObject(typeof(ClassDefinition)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._modifiers = _modifiers; clone._name = _name; if (null != _attributes) { clone._attributes = _attributes.Clone() as AttributeCollection; clone._attributes.InitializeParent(clone); } if (null != _members) { clone._members = _members.Clone() as TypeMemberCollection; clone._members.InitializeParent(clone); } if (null != _baseTypes) { clone._baseTypes = _baseTypes.Clone() as TypeReferenceCollection; clone._baseTypes.InitializeParent(clone); } if (null != _genericParameters) { clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection; clone._genericParameters.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _attributes) { _attributes.ClearTypeSystemBindings(); } if (null != _members) { _members.ClearTypeSystemBindings(); } if (null != _baseTypes) { _baseTypes.ClearTypeSystemBindings(); } if (null != _genericParameters) { _genericParameters.ClearTypeSystemBindings(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Reflection.Core.NonPortable; namespace System { [System.Runtime.CompilerServices.DependencyReductionRoot] public static class InvokeUtils { // // Various reflection scenarios (Array.SetValue(), reflection Invoke, delegate DynamicInvoke and FieldInfo.Set()) perform // automatic conveniences such as automatically widening primitive types to fit the destination type. // // This method attempts to collect as much of that logic as possible in place. (This may not be completely possible // as the desktop CLR is not particularly consistent across all these scenarios either.) // // The transforms supported are: // // Value-preserving widenings of primitive integrals and floats. // Enums can be converted to the same or wider underlying primitive. // Primitives can be converted to an enum with the same or wider underlying primitive. // // null converted to default(T) (this is important when T is a valuetype.) // // There is also another transform of T -> Nullable<T>. This method acknowleges that rule but does not actually transform the T. // Rather, the transformation happens naturally when the caller unboxes the value to its final destination. // // This method is targeted by the Delegate ILTransformer. // // public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType) { EETypePtr dstEEType = dstType.ToEETypePtr(); return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke); } // This option does nothing but decide which type of exception to throw to match the legacy behavior. internal enum CheckArgumentSemantics { ArraySet, // Throws InvalidCastException DynamicInvoke, // Throws ArgumentException } internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics) { if (srcObject == null) { // null -> default(T) if (dstEEType.IsValueType && !RuntimeImports.RhIsNullable(dstEEType)) return Runtime.RuntimeImports.RhNewObject(dstEEType); else return null; } else { EETypePtr srcEEType = srcObject.EETypePtr; if (RuntimeImports.AreTypesAssignable(srcEEType, dstEEType)) return srcObject; if (RuntimeImports.RhIsInterface(dstEEType)) { ICastable castable = srcObject as ICastable; Exception castError; if (castable != null && castable.IsInstanceOfInterface(new RuntimeTypeHandle(dstEEType), out castError)) return srcObject; } if (!((srcEEType.IsEnum || srcEEType.IsPrimitive) && (dstEEType.IsEnum || dstEEType.IsPrimitive))) throw CreateChangeTypeException(srcEEType, dstEEType, semantics); RuntimeImports.RhCorElementType dstCorElementType = dstEEType.CorElementType; if (!srcEEType.CorElementTypeInfo.CanWidenTo(dstCorElementType)) throw CreateChangeTypeArgumentException(srcEEType, dstEEType); Object dstObject; switch (dstCorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: dstObject = Convert.ToBoolean(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: dstObject = Convert.ToChar(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: dstObject = Convert.ToSByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: dstObject = Convert.ToInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: dstObject = Convert.ToInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: dstObject = Convert.ToInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: dstObject = Convert.ToByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: dstObject = Convert.ToUInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: dstObject = Convert.ToUInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: dstObject = Convert.ToUInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (float)(char)srcObject; } else { dstObject = Convert.ToSingle(srcObject); } break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (double)(char)srcObject; } else { dstObject = Convert.ToDouble(srcObject); } break; default: Debug.Assert(false, "Unexpected CorElementType: " + dstCorElementType + ": Not a valid widening target."); throw CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (dstEEType.IsEnum) { Type dstType = ReflectionCoreNonPortable.GetRuntimeTypeForEEType(dstEEType); dstObject = Enum.ToObject(dstType, dstObject); } Debug.Assert(dstObject.EETypePtr == dstEEType); return dstObject; } } private static Exception CreateChangeTypeException(EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics) { switch (semantics) { case CheckArgumentSemantics.DynamicInvoke: return CreateChangeTypeArgumentException(srcEEType, dstEEType); case CheckArgumentSemantics.ArraySet: return CreateChangeTypeInvalidCastException(srcEEType, dstEEType); default: Debug.Assert(false, "Unexpected CheckArgumentSemantics value: " + semantics); throw new InvalidOperationException(); } } private static ArgumentException CreateChangeTypeArgumentException(EETypePtr srcEEType, EETypePtr dstEEType) { return new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)))); } private static InvalidCastException CreateChangeTypeInvalidCastException(EETypePtr srcEEType, EETypePtr dstEEType) { return new InvalidCastException(SR.InvalidCast_StoreArrayElement); } // ----------------------------------------------- // Infrastructure and logic for Dynamic Invocation // ----------------------------------------------- public enum DynamicInvokeParamType { In = 0, Ref = 1 } public enum DynamicInvokeParamLookupType { ValuetypeObjectReturned = 0, IndexIntoObjectArrayReturned = 1, } public struct ArgSetupState { public bool fComplete; public object[] nullableCopyBackObjects; } // These thread static fields are used instead of passing parameters normally through to the helper functions // that actually implement dynamic invocation. This allows the large number of dynamically generated // functions to be just that little bit smaller, which, when spread across the many invocation helper thunks // generated adds up quite a bit. [ThreadStatic] private static object[] s_parameters; [ThreadStatic] private static object[] s_nullableCopyBackObjects; [ThreadStatic] private static int s_curIndex; [ThreadStatic] private static string s_defaultValueString; // Default parameter support private const int DefaultParamTypeNone = 0; private const int DefaultParamTypeBool = 1; private const int DefaultParamTypeChar = 2; private const int DefaultParamTypeI1 = 3; private const int DefaultParamTypeI2 = 4; private const int DefaultParamTypeI4 = 5; private const int DefaultParamTypeI8 = 6; private const int DefaultParamTypeR4 = 7; private const int DefaultParamTypeR8 = 8; private const int DefaultParamTypeString = 9; private const int DefaultParamTypeDefault = 10; private const int DefaultParamTypeDecimal = 11; private const int DefaultParamTypeDateTime = 12; private const int DefaultParamTypeNoneButOptional = 13; private struct StringDataParser { private string _str; private int _offset; public StringDataParser(string str) { _str = str; _offset = 0; } public void SetOffset(int offset) { _offset = offset; } public long GetLong() { long returnValue; char curVal = _str[_offset++]; // High bit is used to indicate an extended value // Low bit is sign bit // The middle 14 bits are used to hold 14 bits of the actual long value. // A sign bit approach is used so that a negative number can be represented with 1 char value. returnValue = (long)(curVal & (char)0x7FFE); returnValue = returnValue >> 1; bool isNegative = ((curVal & (char)1)) == 1; if ((returnValue == 0) && isNegative) { return Int64.MinValue; } int additionalCharCount = 0; int bitsAcquired = 14; // For additional characters, the first 3 additional characters hold 15 bits of data // and the last character may hold 5 bits of data. while ((curVal & (char)0x8000) != 0) { additionalCharCount++; curVal = _str[_offset++]; long grabValue = (long)(curVal & (char)0x7FFF); grabValue <<= bitsAcquired; bitsAcquired += 15; returnValue |= grabValue; } if (isNegative) returnValue = -returnValue; return returnValue; } public int GetInt() { return checked((int)GetLong()); } public unsafe float GetFloat() { int inputLocation = checked((int)GetLong()); float result = 0; byte* inputPtr = (byte*)&inputLocation; byte* outputPtr = (byte*)&result; for (int i = 0; i < 4; i++) { outputPtr[i] = inputPtr[i]; } return result; } public unsafe double GetDouble() { long inputLocation = GetLong(); double result = 0; byte* inputPtr = (byte*)&inputLocation; byte* outputPtr = (byte*)&result; for (int i = 0; i < 8; i++) { outputPtr[i] = inputPtr[i]; } return result; } public unsafe string GetString() { fixed (char* strData = _str) { int length = (int)GetLong(); char c = _str[_offset]; // Check for index out of range concerns. string strRet = new string(strData, _offset, length); _offset += length; return strRet; } } public void Skip(int count) { _offset += count; } } private static unsafe object GetDefaultValue(RuntimeTypeHandle thType, int argIndex) { // Group index of 0 indicates there are no default parameters if (s_defaultValueString == null) { throw new ArgumentException(SR.Arg_DefaultValueMissingException); } StringDataParser dataParser = new StringDataParser(s_defaultValueString); // Skip to current argument int curArgIndex = 0; while (curArgIndex != argIndex) { int skip = dataParser.GetInt(); dataParser.Skip(skip); curArgIndex++; } // Discard size of current argument int sizeOfCurrentArg = dataParser.GetInt(); int defaultValueType = dataParser.GetInt(); switch (defaultValueType) { case DefaultParamTypeNone: default: throw new ArgumentException(SR.Arg_DefaultValueMissingException); case DefaultParamTypeString: return dataParser.GetString(); case DefaultParamTypeDefault: if (thType.ToEETypePtr().IsValueType) { if (RuntimeImports.RhIsNullable(thType.ToEETypePtr())) { return null; } else { return RuntimeImports.RhNewObject(thType.ToEETypePtr()); } } else { return null; } case DefaultParamTypeBool: return (dataParser.GetInt() == 1); case DefaultParamTypeChar: return (char)dataParser.GetInt(); case DefaultParamTypeI1: return (sbyte)dataParser.GetInt(); case DefaultParamTypeI2: return (short)dataParser.GetInt(); case DefaultParamTypeI4: return dataParser.GetInt(); case DefaultParamTypeI8: return dataParser.GetLong(); case DefaultParamTypeR4: return dataParser.GetFloat(); case DefaultParamTypeR8: return dataParser.GetDouble(); case DefaultParamTypeDecimal: int[] decimalBits = new int[4]; decimalBits[0] = dataParser.GetInt(); decimalBits[1] = dataParser.GetInt(); decimalBits[2] = dataParser.GetInt(); decimalBits[3] = dataParser.GetInt(); return new Decimal(decimalBits); case DefaultParamTypeDateTime: return new DateTime(dataParser.GetLong()); case DefaultParamTypeNoneButOptional: return System.Reflection.Missing.Value; } } internal static object CallDynamicInvokeMethod(object thisPtr, IntPtr methodToCall, object thisPtrDynamicInvokeMethod, IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, string defaultValueString, object[] parameters, bool invokeMethodHelperIsThisCall = true, bool methodToCallIsThisCall = true) { bool fDontWrapInTargetInvocationException = false; bool parametersNeedCopyBack = false; ArgSetupState argSetupState = default(ArgSetupState); // Capture state of thread static invoke helper statics object[] parametersOld = s_parameters; object[] nullableCopyBackObjectsOld = s_nullableCopyBackObjects; int curIndexOld = s_curIndex; string defaultValueStringOld = s_defaultValueString; try { // If the passed in array is not an actual object[] instance, we need to copy it over to an actual object[] // instance so that the rest of the code can safely create managed object references to individual elements. if (parameters != null && EETypePtr.EETypePtrOf<object[]>() != parameters.EETypePtr) { s_parameters = new object[parameters.Length]; Array.Copy(parameters, s_parameters, parameters.Length); parametersNeedCopyBack = true; } else { s_parameters = parameters; } s_nullableCopyBackObjects = null; s_curIndex = 0; s_defaultValueString = defaultValueString; try { if (invokeMethodHelperIsThisCall) { Debug.Assert(methodToCallIsThisCall == true); return CallIHelperThisCall(thisPtr, methodToCall, thisPtrDynamicInvokeMethod, dynamicInvokeHelperMethod, ref argSetupState); } else { if (dynamicInvokeHelperGenericDictionary != IntPtr.Zero) return CallIHelperStaticCallWithInstantiation(thisPtr, methodToCall, dynamicInvokeHelperMethod, ref argSetupState, methodToCallIsThisCall, dynamicInvokeHelperGenericDictionary); else return CallIHelperStaticCall(thisPtr, methodToCall, dynamicInvokeHelperMethod, ref argSetupState, methodToCallIsThisCall); } } finally { if (parametersNeedCopyBack) { Array.Copy(s_parameters, parameters, parameters.Length); } if (!argSetupState.fComplete) { fDontWrapInTargetInvocationException = true; } else { // Nullable objects can't take advantage of the ability to update the boxed value on the heap directly, so perform // an update of the parameters array now. if (argSetupState.nullableCopyBackObjects != null) { for (int i = 0; i < argSetupState.nullableCopyBackObjects.Length; i++) { if (argSetupState.nullableCopyBackObjects[i] != null) { parameters[i] = DynamicInvokeBoxIntoNonNullable(argSetupState.nullableCopyBackObjects[i]); } } } } } } catch (Exception e) { if (fDontWrapInTargetInvocationException) { throw; } else { throw new System.Reflection.TargetInvocationException(e); } } finally { // Restore state of thread static helper statics s_parameters = parametersOld; s_nullableCopyBackObjects = nullableCopyBackObjectsOld; s_curIndex = curIndexOld; s_defaultValueString = defaultValueStringOld; } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static void DynamicInvokeArgSetupComplete(ref ArgSetupState argSetupState) { int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (s_curIndex != parametersLength) { throw new System.Reflection.TargetParameterCountException(); } argSetupState.fComplete = true; argSetupState.nullableCopyBackObjects = s_nullableCopyBackObjects; s_nullableCopyBackObjects = null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void DynamicInvokeArgSetupPtrComplete(IntPtr argSetupStatePtr) { // Intrinsic filled by the ImplementLibraryDynamicInvokeHelpers transform. // argSetupStatePtr is a pointer to a *pinned* ArgSetupState object // ldarg.0 // call void System.InvokeUtils.DynamicInvokeArgSetupComplete(ref ArgSetupState) // ret throw new PlatformNotSupportedException(); } internal static object CallIHelperThisCall(object thisPtr, IntPtr methodToCall, object thisPtrForDynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState) { // Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in. return null; } internal static object CallIHelperStaticCall(object thisPtr, IntPtr methodToCall, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState, bool isTargetThisCall) { // Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in. return null; } internal static object CallIHelperStaticCallWithInstantiation(object thisPtr, IntPtr methodToCall, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState, bool isTargetThisCall, IntPtr dynamicInvokeHelperGenericDictionary) { // Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in. return null; } // Template function that is used to call dynamically internal static object DynamicInvokeThisCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } internal static object DynamicInvokeCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool targetIsThisCall) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // !if (targetIsThisCall) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret // !else // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType (TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void DynamicInvokeUnboxIntoActualNullable(object actualBoxedNullable, object boxedFillObject, EETypePtr nullableType) { // pin the actualBoxedNullable // local0 is object pinned pinnedActualBoxedNullable // ldarg.0 // stloc.0 // ldarg.1 // object to unbox // ldarg.0 // ldflda System.Object::m_eetype // sizeof EETypePtr // add // byref to data data region within actualBoxedNullable // ldarg.2 // get a byref to the data within the actual boxed nullable, and then call RhUnBox with the boxedFillObject as the boxed object, and nullableType as the unbox type, and unbox into the actualBoxedNullable // call static void RuntimeImports.RhUnbox(object obj, void* pData, EETypePtr pUnboxToEEType); // ret } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static object DynamicInvokeBoxIntoNonNullable(object actualBoxedNullable) { // pin the actualBoxedNullable // local0 is object pinned pinnedActualBoxedNullable // ldarg.0 // stloc.0 // // grab the pointer to data, box using the EEType of the actualBoxedNullable, and then return the boxed object // ldarg.0 // ldfld System.Object::m_eetype // ldarg.0 // ldflda System.Object::m_eetype // sizeof EETypePtr // add // call RuntimeImports.RhBox(EETypePtr, void*data) // ret return null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static /* Transform change this into byref to IntPtr*/ IntPtr DynamicInvokeParamHelperIn(RuntimeTypeHandle rth) { // Call DynamicInvokeParamHelperCore as an in parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in. // // This function exactly matches DynamicInvokeParamHelperRef except for the value of the enum passed to DynamicInvokeParamHelperCore // // zeroinit // local0 is int index // local1 is DynamicInvokeParamLookupType // local2 is object // // Capture information about the parameter. // ldarg.0 // ldloca 1 // ref DynamicInvokeParamLookupType // ldloca 0 // ref index // ldc.i4.0 // DynamicInvokeParamType.In // call object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) // stloc.2 // decode output of DynamicInvokeParamHelperCore // if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) // return &local2.m_pEEType + sizeof(EETypePtr) // else // return &(((object[])local2)[index]) // // ldloc.1 // ldc.i4.0 // bne.un arrayCase // ldloc.2 // ldflda System.Object::m_eetype // sizeof EETypePtr // add // ret // arrayCase: // ldloc.2 // ldloc.0 // ldelema System.Object // ret return IntPtr.Zero; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static /* Transform change this into byref to IntPtr*/ IntPtr DynamicInvokeParamHelperRef(RuntimeTypeHandle rth) { // Call DynamicInvokeParamHelperCore as a ref parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in. // // This function exactly matches DynamicInvokeParamHelperIn except for the value of the enum passed to DynamicInvokeParamHelperCore // // zeroinit // local0 is int index // local1 is DynamicInvokeParamLookupType // local2 is object // // Capture information about the parameter. // ldarg.0 // ldloca 1 // ref DynamicInvokeParamLookupType // ldloca 0 // ref index // ldc.i4.1 // DynamicInvokeParamType.Ref // call object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) // stloc.2 // decode output of DynamicInvokeParamHelperCore // if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) // return &local2.m_pEEType + sizeof(EETypePtr) // else // return &(((object[])local2)[index]) // // ldloc.1 // ldc.i4.0 // bne.un arrayCase // ldloc.2 // ldflda System.Object::m_eetype // sizeof EETypePtr // add // ret // arrayCase: // ldloc.2 // ldloc.0 // ldelema System.Object // ret return IntPtr.Zero; } internal static object DynamicInvokeBoxedValuetypeReturn(out DynamicInvokeParamLookupType paramLookupType, object boxedValuetype, int index, RuntimeTypeHandle type, DynamicInvokeParamType paramType) { object finalObjectToReturn = boxedValuetype; EETypePtr eeType = type.ToEETypePtr(); bool nullable = RuntimeImports.RhIsNullable(eeType); if (finalObjectToReturn == null || nullable || paramType == DynamicInvokeParamType.Ref) { finalObjectToReturn = RuntimeImports.RhNewObject(eeType); if (boxedValuetype != null) { DynamicInvokeUnboxIntoActualNullable(finalObjectToReturn, boxedValuetype, eeType); } } if (nullable) { if (paramType == DynamicInvokeParamType.Ref) { if (s_nullableCopyBackObjects == null) { s_nullableCopyBackObjects = new object[s_parameters.Length]; } s_nullableCopyBackObjects[index] = finalObjectToReturn; s_parameters[index] = null; } } else { System.Diagnostics.Debug.Assert(finalObjectToReturn != null); if (paramType == DynamicInvokeParamType.Ref) s_parameters[index] = finalObjectToReturn; } paramLookupType = DynamicInvokeParamLookupType.ValuetypeObjectReturned; return finalObjectToReturn; } public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) { index = s_curIndex++; int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (index >= parametersLength) throw new System.Reflection.TargetParameterCountException(); object incomingParam = s_parameters[index]; // Handle default parameters if ((incomingParam == System.Reflection.Missing.Value) && paramType == DynamicInvokeParamType.In) { incomingParam = GetDefaultValue(type, index); // The default value is captured into the parameters array s_parameters[index] = incomingParam; } RuntimeTypeHandle widenAndCompareType = type; bool nullable = RuntimeImports.RhIsNullable(type.ToEETypePtr()); if (nullable) { widenAndCompareType = new RuntimeTypeHandle(RuntimeImports.RhGetNullableType(type.ToEETypePtr())); } if (widenAndCompareType.ToEETypePtr().IsPrimitive || type.ToEETypePtr().IsEnum) { // Nullable requires exact matching if (incomingParam != null) { if ((nullable || paramType == DynamicInvokeParamType.Ref) && incomingParam != null) { if (widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr) { throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr()); } } else { if (widenAndCompareType.ToEETypePtr().CorElementType != incomingParam.EETypePtr.CorElementType) { System.Diagnostics.Debug.Assert(paramType == DynamicInvokeParamType.In); incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke); } } } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else if (type.ToEETypePtr().IsValueType) { incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke); System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index])); return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else { incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke); System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index])); paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned; return s_parameters; } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Collections.Generic; using System.Runtime; using System.ServiceModel; using System.Threading; class ConcurrencyBehavior { ConcurrencyMode concurrencyMode; bool enforceOrderedReceive; bool supportsTransactedBatch; internal ConcurrencyBehavior(DispatchRuntime runtime) { this.concurrencyMode = runtime.ConcurrencyMode; this.enforceOrderedReceive = runtime.EnsureOrderedDispatch; this.supportsTransactedBatch = ConcurrencyBehavior.SupportsTransactedBatch(runtime.ChannelDispatcher); } static bool SupportsTransactedBatch(ChannelDispatcher channelDispatcher) { return channelDispatcher.IsTransactedReceive && (channelDispatcher.MaxTransactedBatchSize > 0); } internal bool IsConcurrent(ref MessageRpc rpc) { return IsConcurrent(this.concurrencyMode, this.enforceOrderedReceive, rpc.Channel.HasSession, this.supportsTransactedBatch); } internal static bool IsConcurrent(ConcurrencyMode concurrencyMode, bool ensureOrderedDispatch, bool hasSession, bool supportsTransactedBatch) { if (supportsTransactedBatch) { return false; } if (concurrencyMode != ConcurrencyMode.Single) { return true; } if (hasSession) { return false; } if (ensureOrderedDispatch) { return false; } return true; } internal static bool IsConcurrent(ChannelDispatcher runtime, bool hasSession) { bool isConcurrencyModeSingle = true; if (ConcurrencyBehavior.SupportsTransactedBatch(runtime)) { return false; } foreach (EndpointDispatcher endpointDispatcher in runtime.Endpoints) { if (endpointDispatcher.DispatchRuntime.EnsureOrderedDispatch) { return false; } if (endpointDispatcher.DispatchRuntime.ConcurrencyMode != ConcurrencyMode.Single) { isConcurrencyModeSingle = false; } } if (!isConcurrencyModeSingle) { return true; } if (!hasSession) { return true; } return false; } internal void LockInstance(ref MessageRpc rpc) { if (this.concurrencyMode != ConcurrencyMode.Multiple) { ConcurrencyInstanceContextFacet resource = rpc.InstanceContext.Concurrency; lock (rpc.InstanceContext.ThisLock) { if (!resource.Locked) { resource.Locked = true; } else { MessageRpcWaiter waiter = new MessageRpcWaiter(rpc.Pause()); resource.EnqueueNewMessage(waiter); } } if (this.concurrencyMode == ConcurrencyMode.Reentrant) { rpc.OperationContext.IsServiceReentrant = true; } } } internal void UnlockInstance(ref MessageRpc rpc) { if (this.concurrencyMode != ConcurrencyMode.Multiple) { ConcurrencyBehavior.UnlockInstance(rpc.InstanceContext); } } internal static void UnlockInstanceBeforeCallout(OperationContext operationContext) { if (operationContext != null && operationContext.IsServiceReentrant) { ConcurrencyBehavior.UnlockInstance(operationContext.InstanceContext); } } static void UnlockInstance(InstanceContext instanceContext) { ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency; lock (instanceContext.ThisLock) { if (resource.HasWaiters) { IWaiter nextWaiter = resource.DequeueWaiter(); nextWaiter.Signal(); } else { //We have no pending Callouts and no new Messages to process resource.Locked = false; } } } internal static void LockInstanceAfterCallout(OperationContext operationContext) { if (operationContext != null) { InstanceContext instanceContext = operationContext.InstanceContext; if (operationContext.IsServiceReentrant) { ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency; ThreadWaiter waiter = null; lock (instanceContext.ThisLock) { if (!resource.Locked) { resource.Locked = true; } else { waiter = new ThreadWaiter(); resource.EnqueueCalloutMessage(waiter); } } if (waiter != null) { waiter.Wait(); } } } } internal interface IWaiter { void Signal(); } class MessageRpcWaiter : IWaiter { IResumeMessageRpc resume; internal MessageRpcWaiter(IResumeMessageRpc resume) { this.resume = resume; } void IWaiter.Signal() { try { bool alreadyResumedNoLock; this.resume.Resume(out alreadyResumedNoLock); if (alreadyResumedNoLock) { Fx.Assert("ConcurrencyBehavior resumed more than once for same call."); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } } class ThreadWaiter : IWaiter { ManualResetEvent wait = new ManualResetEvent(false); void IWaiter.Signal() { this.wait.Set(); } internal void Wait() { this.wait.WaitOne(); this.wait.Close(); } } } internal class ConcurrencyInstanceContextFacet { internal bool Locked; Queue<ConcurrencyBehavior.IWaiter> calloutMessageQueue; Queue<ConcurrencyBehavior.IWaiter> newMessageQueue; internal bool HasWaiters { get { return (((this.calloutMessageQueue != null) && (this.calloutMessageQueue.Count > 0)) || ((this.newMessageQueue != null) && (this.newMessageQueue.Count > 0))); } } ConcurrencyBehavior.IWaiter DequeueFrom(Queue<ConcurrencyBehavior.IWaiter> queue) { ConcurrencyBehavior.IWaiter waiter = queue.Dequeue(); if (queue.Count == 0) { queue.TrimExcess(); } return waiter; } internal ConcurrencyBehavior.IWaiter DequeueWaiter() { // Finishing old work takes precedence over new work. if ((this.calloutMessageQueue != null) && (this.calloutMessageQueue.Count > 0)) { return this.DequeueFrom(this.calloutMessageQueue); } else { return this.DequeueFrom(this.newMessageQueue); } } internal void EnqueueNewMessage(ConcurrencyBehavior.IWaiter waiter) { if (this.newMessageQueue == null) this.newMessageQueue = new Queue<ConcurrencyBehavior.IWaiter>(); this.newMessageQueue.Enqueue(waiter); } internal void EnqueueCalloutMessage(ConcurrencyBehavior.IWaiter waiter) { if (this.calloutMessageQueue == null) this.calloutMessageQueue = new Queue<ConcurrencyBehavior.IWaiter>(); this.calloutMessageQueue.Enqueue(waiter); } } }
using System; using Csla; using Codisa.InterwayDocs.DataAccess; namespace Codisa.InterwayDocs.Business { /// <summary> /// DeliveryInfo (read only object).<br/> /// This is a generated <see cref="DeliveryInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="DeliveryBook"/> collection. /// </remarks> [Serializable] public partial class DeliveryInfo : ReadOnlyBase<DeliveryInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="RegisterId"/> property. /// </summary> public static readonly PropertyInfo<int> RegisterIdProperty = RegisterProperty<int>(p => p.RegisterId, "Register Id"); /// <summary> /// Gets the Register Id. /// </summary> /// <value>The Register Id.</value> public int RegisterId { get { return GetProperty(RegisterIdProperty); } } /// <summary> /// Maintains metadata about <see cref="RegisterDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> RegisterDateProperty = RegisterProperty<SmartDate>(p => p.RegisterDate, "Register Date"); /// <summary> /// Gets the Register Date. /// </summary> /// <value>The Register Date.</value> public string RegisterDate { get { return GetPropertyConvert<SmartDate, string>(RegisterDateProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentType"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentTypeProperty = RegisterProperty<string>(p => p.DocumentType, "Document Type"); /// <summary> /// Gets the Document Type. /// </summary> /// <value>The Document Type.</value> public string DocumentType { get { return GetProperty(DocumentTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentReference"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentReferenceProperty = RegisterProperty<string>(p => p.DocumentReference, "Document Reference"); /// <summary> /// Gets the Document Reference. /// </summary> /// <value>The Document Reference.</value> public string DocumentReference { get { return GetProperty(DocumentReferenceProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentEntity"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentEntityProperty = RegisterProperty<string>(p => p.DocumentEntity, "Document Entity"); /// <summary> /// Gets the Document Entity. /// </summary> /// <value>The Document Entity.</value> public string DocumentEntity { get { return GetProperty(DocumentEntityProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDept"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentDeptProperty = RegisterProperty<string>(p => p.DocumentDept, "Document Dept"); /// <summary> /// Gets the Document Dept. /// </summary> /// <value>The Document Dept.</value> public string DocumentDept { get { return GetProperty(DocumentDeptProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentClass"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentClassProperty = RegisterProperty<string>(p => p.DocumentClass, "Document Class"); /// <summary> /// Gets the Document Class. /// </summary> /// <value>The Document Class.</value> public string DocumentClass { get { return GetProperty(DocumentClassProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocumentDateProperty = RegisterProperty<SmartDate>(p => p.DocumentDate, "Document Date"); /// <summary> /// Gets the Document Date. /// </summary> /// <value>The Document Date.</value> public string DocumentDate { get { return GetPropertyConvert<SmartDate, string>(DocumentDateProperty); } } /// <summary> /// Maintains metadata about <see cref="RecipientName"/> property. /// </summary> public static readonly PropertyInfo<string> RecipientNameProperty = RegisterProperty<string>(p => p.RecipientName, "Recipient Name"); /// <summary> /// Gets the Recipient Name. /// </summary> /// <value>The Recipient Name.</value> public string RecipientName { get { return GetProperty(RecipientNameProperty); } } /// <summary> /// Maintains metadata about <see cref="ExpeditorName"/> property. /// </summary> public static readonly PropertyInfo<string> ExpeditorNameProperty = RegisterProperty<string>(p => p.ExpeditorName, "Expeditor Name"); /// <summary> /// Gets the Expeditor Name. /// </summary> /// <value>The Expeditor Name.</value> public string ExpeditorName { get { return GetProperty(ExpeditorNameProperty); } } /// <summary> /// Maintains metadata about <see cref="ReceptionName"/> property. /// </summary> public static readonly PropertyInfo<string> ReceptionNameProperty = RegisterProperty<string>(p => p.ReceptionName, "Reception Name"); /// <summary> /// Gets the Reception Name. /// </summary> /// <value>The Reception Name.</value> public string ReceptionName { get { return GetProperty(ReceptionNameProperty); } } /// <summary> /// Maintains metadata about <see cref="ReceptionDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ReceptionDateProperty = RegisterProperty<SmartDate>(p => p.ReceptionDate, "Reception Date"); /// <summary> /// Gets the Reception Date. /// </summary> /// <value>The Reception Date.</value> public string ReceptionDate { get { return GetPropertyConvert<SmartDate, string>(ReceptionDateProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="DeliveryInfo"/> object from the given DeliveryInfoDto. /// </summary> /// <param name="data">The <see cref="DeliveryInfoDto"/>.</param> /// <returns>A reference to the fetched <see cref="DeliveryInfo"/> object.</returns> internal static DeliveryInfo GetDeliveryInfo(DeliveryInfoDto data) { DeliveryInfo obj = new DeliveryInfo(); obj.Fetch(data); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DeliveryInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DeliveryInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="DeliveryInfo"/> object from the given <see cref="DeliveryInfoDto"/>. /// </summary> /// <param name="data">The DeliveryInfoDto to use.</param> private void Fetch(DeliveryInfoDto data) { // Value properties LoadProperty(RegisterIdProperty, data.RegisterId); LoadProperty(RegisterDateProperty, data.RegisterDate); LoadProperty(DocumentTypeProperty, data.DocumentType); LoadProperty(DocumentReferenceProperty, data.DocumentReference); LoadProperty(DocumentEntityProperty, data.DocumentEntity); LoadProperty(DocumentDeptProperty, data.DocumentDept); LoadProperty(DocumentClassProperty, data.DocumentClass); LoadProperty(DocumentDateProperty, data.DocumentDate); LoadProperty(RecipientNameProperty, data.RecipientName); LoadProperty(ExpeditorNameProperty, data.ExpeditorName); LoadProperty(ReceptionNameProperty, data.ReceptionName); LoadProperty(ReceptionDateProperty, data.ReceptionDate); var args = new DataPortalHookArgs(data); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class BreakState_Property : PortsTest { //The maximum time we will wait for the pin changed event to get firered for the break state private const int MAX_WAIT_FOR_BREAK = 800; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void BreakState_Default() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default BreakState"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasOneSerialPort))] public void BreakState_BeforeOpen() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying setting BreakState before open"); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Assert.Throws<InvalidOperationException>(() => com1.BreakState = true); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void BreakState_true() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying true BreakState"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); SetBreakStateandVerify(com1); serPortProp.SetProperty("BreakState", true); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void BreakState_false() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying false BreakState"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); SetBreakStateandVerify(com1); serPortProp.SetProperty("BreakState", false); com1.BreakState = false; serPortProp.VerifyPropertiesAndPrint(com1); Assert.False(GetCurrentBreakState()); } } [ConditionalFact(nameof(HasNullModem))] public void BreakState_true_false() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying setting BreakState to true then false"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); SetBreakStateandVerify(com1); serPortProp.SetProperty("BreakState", true); serPortProp.VerifyPropertiesAndPrint(com1); serPortProp.SetProperty("BreakState", false); com1.BreakState = false; serPortProp.VerifyPropertiesAndPrint(com1); } Assert.False(GetCurrentBreakState()); } [ConditionalFact(nameof(HasNullModem))] public void BreakState_true_false_true() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying setting BreakState to true then false then true again"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); SetBreakStateandVerify(com1); serPortProp.SetProperty("BreakState", true); serPortProp.VerifyPropertiesAndPrint(com1); serPortProp.SetProperty("BreakState", false); com1.BreakState = false; serPortProp.VerifyPropertiesAndPrint(com1); Assert.False(GetCurrentBreakState()); serPortProp.VerifyPropertiesAndPrint(com1); SetBreakStateandVerify(com1); serPortProp.SetProperty("BreakState", true); serPortProp.VerifyPropertiesAndPrint(com1); } } #endregion #region Verification for Test Cases private void SetBreakStateandVerify(SerialPort com1) { BreakStateEventHandler breakState; using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { breakState = new BreakStateEventHandler(); com2.PinChanged += breakState.HandleEvent; com2.Open(); com1.BreakState = true; Assert.True(breakState.WaitForBreak(MAX_WAIT_FOR_BREAK)); } } private bool GetCurrentBreakState() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { BreakStateEventHandler breakState = new BreakStateEventHandler(); com2.PinChanged += breakState.HandleEvent; com2.Open(); return breakState.WaitForBreak(MAX_WAIT_FOR_BREAK); } } private class BreakStateEventHandler { private bool _breakOccurred; public void HandleEvent(object source, SerialPinChangedEventArgs e) { lock (this) { if (SerialPinChange.Break == e.EventType) { _breakOccurred = true; Monitor.Pulse(this); } } } public void WaitForBreak() { lock (this) { if (!_breakOccurred) { Monitor.Wait(this); } } } public bool WaitForBreak(int timeout) { lock (this) { if (!_breakOccurred) { return Monitor.Wait(this, timeout); } return true; } } } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Controller class for APR_RecienNacido /// </summary> [System.ComponentModel.DataObject] public partial class AprRecienNacidoController { // Preload our schema.. AprRecienNacido thisSchemaLoad = new AprRecienNacido(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public AprRecienNacidoCollection FetchAll() { AprRecienNacidoCollection coll = new AprRecienNacidoCollection(); Query qry = new Query(AprRecienNacido.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public AprRecienNacidoCollection FetchByID(object IdRecienNacido) { AprRecienNacidoCollection coll = new AprRecienNacidoCollection().Where("idRecienNacido", IdRecienNacido).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public AprRecienNacidoCollection FetchByQuery(Query qry) { AprRecienNacidoCollection coll = new AprRecienNacidoCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdRecienNacido) { return (AprRecienNacido.Delete(IdRecienNacido) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdRecienNacido) { return (AprRecienNacido.Destroy(IdRecienNacido) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdEfector,int? IdPaciente,double? Peso,double? PerimetroCefalico,double? Longitud,int? APGAR1,int? APGAR5,double? PesoAlAlta,bool? Gemelar,int? NroGesta,string DiagnosticoNeonatalTemporal,string DiagnosticoNeonatalFisico,bool? ScreeningRealizado,bool? ScreeningNormal,string OEARealizado,bool? EmbarazoNormal,int? IdTipoParto,bool? PesquizaNeonatal,bool? Hb12meses,bool? TA3,string CreatedBy,DateTime? CreatedOn,string ModifiedBy,DateTime? ModifiedOn) { AprRecienNacido item = new AprRecienNacido(); item.IdEfector = IdEfector; item.IdPaciente = IdPaciente; item.Peso = Peso; item.PerimetroCefalico = PerimetroCefalico; item.Longitud = Longitud; item.APGAR1 = APGAR1; item.APGAR5 = APGAR5; item.PesoAlAlta = PesoAlAlta; item.Gemelar = Gemelar; item.NroGesta = NroGesta; item.DiagnosticoNeonatalTemporal = DiagnosticoNeonatalTemporal; item.DiagnosticoNeonatalFisico = DiagnosticoNeonatalFisico; item.ScreeningRealizado = ScreeningRealizado; item.ScreeningNormal = ScreeningNormal; item.OEARealizado = OEARealizado; item.EmbarazoNormal = EmbarazoNormal; item.IdTipoParto = IdTipoParto; item.PesquizaNeonatal = PesquizaNeonatal; item.Hb12meses = Hb12meses; item.TA3 = TA3; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdRecienNacido,int IdEfector,int? IdPaciente,double? Peso,double? PerimetroCefalico,double? Longitud,int? APGAR1,int? APGAR5,double? PesoAlAlta,bool? Gemelar,int? NroGesta,string DiagnosticoNeonatalTemporal,string DiagnosticoNeonatalFisico,bool? ScreeningRealizado,bool? ScreeningNormal,string OEARealizado,bool? EmbarazoNormal,int? IdTipoParto,bool? PesquizaNeonatal,bool? Hb12meses,bool? TA3,string CreatedBy,DateTime? CreatedOn,string ModifiedBy,DateTime? ModifiedOn) { AprRecienNacido item = new AprRecienNacido(); item.MarkOld(); item.IsLoaded = true; item.IdRecienNacido = IdRecienNacido; item.IdEfector = IdEfector; item.IdPaciente = IdPaciente; item.Peso = Peso; item.PerimetroCefalico = PerimetroCefalico; item.Longitud = Longitud; item.APGAR1 = APGAR1; item.APGAR5 = APGAR5; item.PesoAlAlta = PesoAlAlta; item.Gemelar = Gemelar; item.NroGesta = NroGesta; item.DiagnosticoNeonatalTemporal = DiagnosticoNeonatalTemporal; item.DiagnosticoNeonatalFisico = DiagnosticoNeonatalFisico; item.ScreeningRealizado = ScreeningRealizado; item.ScreeningNormal = ScreeningNormal; item.OEARealizado = OEARealizado; item.EmbarazoNormal = EmbarazoNormal; item.IdTipoParto = IdTipoParto; item.PesquizaNeonatal = PesquizaNeonatal; item.Hb12meses = Hb12meses; item.TA3 = TA3; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Save(UserName); } } }
/** * Repairs missing pb_Object and pb_Entity references. It is based * on this article by Unity Gems: http://unitygems.com/lateral1/ */ using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Linq; namespace ProBuilder2.EditorCommon { /** * Extends MonoBehaviour Inspector, automatically fixing missing script * references (typically caused by ProBuilder upgrade process). */ [CustomEditor(typeof(MonoBehaviour))] public class pb_MissingScriptEditor : Editor { #region Members static bool applyDummyScript = true; ///< If true, any null components that can't be set will have this script applied to their reference, allowing us to later remove them. static float index = 0; ///< general idea of where we are in terms of processing this scene. static float total; ///< general idea of how many missing script references are in this scene. static bool doFix = false; ///< while true, the inspector will attempt to cycle to broken gameobjects until none are found. static List<GameObject> unfixable = new List<GameObject>(); ///< if a non-pb missing reference is encountered, need to let the iterator know not to bother, static MonoScript _mono_pb; ///< MonoScript assets static MonoScript _mono_pe; ///< MonoScript assets static MonoScript _mono_dummy; ///< MonoScript assets /** * Load the pb_Object and pb_Entity classes to MonoScript assets. Saves us from having to fall back on Reflection. */ static void LoadMonoScript() { GameObject go = new GameObject(); pb_Object pb = go.AddComponent<pb_Object>(); pb_Entity pe = go.AddComponent<pb_Entity>(); pb_DummyScript du = go.AddComponent<pb_DummyScript>(); _mono_pb = MonoScript.FromMonoBehaviour( pb ); _mono_pe = MonoScript.FromMonoBehaviour( pe ); _mono_dummy = MonoScript.FromMonoBehaviour( du ); DestroyImmediate(go); } public MonoScript pb_monoscript { get { if(_mono_pb == null) LoadMonoScript(); return _mono_pb; } } public MonoScript pe_monoscript { get { if(_mono_pe == null) LoadMonoScript(); return _mono_pe; } } public MonoScript dummy_monoscript { get { if(_mono_dummy == null) LoadMonoScript(); return _mono_dummy; } } #endregion [MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Repair/Repair Missing Script References")] public static void MenuRepairMissingScriptReferences() { FixAllScriptReferencesInScene(); } static void FixAllScriptReferencesInScene() { EditorApplication.ExecuteMenuItem("Window/Inspector"); Object[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject)).Where(x => ((GameObject)x).GetComponents<Component>().Any(n => n == null) ).ToArray(); total = all.Length; unfixable.Clear(); if(total > 1) { Undo.RecordObjects(all, "Fix missing script references"); index = 0; doFix = true; Next(); } else { if( applyDummyScript ) DeleteDummyScripts(); EditorUtility.DisplayDialog("Success", "No missing ProBuilder script references found.", "Okay"); } } /** * Advance to the next gameobject with missing components. If none are found, display dialog and exit. */ static void Next() { bool earlyExit = false; if( EditorUtility.DisplayCancelableProgressBar("Repair ProBuilder Script References", "Fixing " + (int)Mathf.Floor(index+1) + " out of " + total + " objects in scene.", ((float)index/total) ) ) { earlyExit = true; doFix = false; } if(!earlyExit) { // Cycle through FindObjectsOfType on every Next() because using a static list didn't work for some reason. foreach(GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject))) { if(go.GetComponents<Component>().Any(x => x == null) && !unfixable.Contains(go)) { if( (PrefabUtility.GetPrefabType(go) == PrefabType.PrefabInstance || PrefabUtility.GetPrefabType(go) == PrefabType.Prefab ) ) { GameObject pref = (GameObject)PrefabUtility.GetPrefabParent(go); if(pref && (pref.GetComponent<pb_Object>() || pref.GetComponent<pb_Entity>())) { unfixable.Add(go); continue; } } if(go.hideFlags != HideFlags.None) { unfixable.Add(go); continue; } Selection.activeObject = go; return; } } } pb_Object[] pbs = (pb_Object[])Resources.FindObjectsOfTypeAll(typeof(pb_Object)); for(int i = 0; i < pbs.Length; i++) { EditorUtility.DisplayProgressBar("Checking ProBuilder Meshes", "Refresh " + (i+1) + " out of " + total + " objects in scene.", ((float)i/pbs.Length) ); try { pbs[i].ToMesh(); pbs[i].Refresh(); pbs[i].Optimize(); } catch (System.Exception e) { Debug.LogWarning("Failed reconstituting " + pbs[i].name + ". Proceeding with upgrade anyways. Usually this means a prefab is already fixed, and just needs to be instantiated to take effect.\n" + e.ToString()); } } EditorUtility.ClearProgressBar(); if( applyDummyScript ) DeleteDummyScripts(); EditorUtility.DisplayDialog("Success", "Successfully repaired " + total + " ProBuilder objects.", "Okay"); if(!EditorApplication.SaveCurrentSceneIfUserWantsTo()) Debug.LogWarning("Repaired script references will be lost on exit if this scene is not saved!"); doFix = false; skipEvent = true; } /** * SerializedProperty names found in pb_Entity. */ List<string> PB_OBJECT_SCRIPT_PROPERTIES = new List<string>() { "_sharedIndices", "_vertices", "_uv", "_sharedIndicesUV", "_quads" }; /** * SerializedProperty names found in pb_Object. */ List<string> PB_ENTITY_SCRIPT_PROPERTIES = new List<string>() { "pb", "userSetDimensions", "_entityType", "forceConvex" }; // Prevents ArgumentException after displaying 'Done' dialog. For some reason the Event loop skips layout phase after DisplayDialog. private static bool skipEvent = false; public override void OnInspectorGUI() { if(skipEvent && Event.current.type == EventType.Repaint) { skipEvent = false; return; } SerializedProperty scriptProperty = this.serializedObject.FindProperty("m_Script"); if(scriptProperty == null || scriptProperty.objectReferenceValue != null) { if(doFix) { if(Event.current.type == EventType.Repaint) { Next(); } } else { base.OnInspectorGUI(); } return; } int pbObjectMatches = 0, pbEntityMatches = 0; // Shows a detailed tree view of all the properties in this serializedobject. // GUILayout.Label( SerializedObjectToString(this.serializedObject) ); SerializedProperty iterator = this.serializedObject.GetIterator(); iterator.Next(true); while( iterator.Next(true) ) { if( PB_OBJECT_SCRIPT_PROPERTIES.Contains(iterator.name) ) pbObjectMatches++; if( PB_ENTITY_SCRIPT_PROPERTIES.Contains(iterator.name) ) pbEntityMatches++; } // If we can fix it, show the help box, otherwise just default inspector it up. if(pbObjectMatches >= 3 || pbEntityMatches >= 3) { EditorGUILayout.HelpBox("Missing Script Reference\n\nProBuilder can automatically fix this missing reference. To fix all references in the scene, click \"Fix All in Scene\". To fix just this one, click \"Reconnect\".", MessageType.Warning); } else { if(doFix) { if( applyDummyScript ) { index += .5f; scriptProperty.objectReferenceValue = dummy_monoscript; scriptProperty.serializedObject.ApplyModifiedProperties(); scriptProperty = this.serializedObject.FindProperty("m_Script"); scriptProperty.serializedObject.Update(); } else { unfixable.Add( ((Component)target).gameObject ); } Next(); GUIUtility.ExitGUI(); return; } else { base.OnInspectorGUI(); } return; } GUI.backgroundColor = Color.green; if(!doFix) { if(GUILayout.Button("Fix All in Scene")) { FixAllScriptReferencesInScene(); return; } } GUI.backgroundColor = Color.cyan; if((doFix && Event.current.type == EventType.Repaint) || GUILayout.Button("Reconnect")) { if(pbObjectMatches >= 3) // only increment for pb_Object otherwise the progress bar will fill 2x faster than it should { index++; } else { // Make sure that pb_Object is fixed first if we're automatically cycling objects. if(doFix && ((Component)target).gameObject.GetComponent<pb_Object>() == null) return; } if(!doFix) { Undo.RegisterCompleteObjectUndo(target, "Fix missing reference."); } // Debug.Log("Fix: " + (pbObjectMatches > 2 ? "pb_Object" : "pb_Entity") + " " + ((Component)target).gameObject.name); scriptProperty.objectReferenceValue = pbObjectMatches >= 3 ? pb_monoscript : pe_monoscript; scriptProperty.serializedObject.ApplyModifiedProperties(); scriptProperty = this.serializedObject.FindProperty("m_Script"); scriptProperty.serializedObject.Update(); if(doFix) Next(); GUIUtility.ExitGUI(); } GUI.backgroundColor = Color.white; } /** * Scan the scene for gameObjects referencing `pb_DummyScript` and delete them. */ static void DeleteDummyScripts() { pb_DummyScript[] dummies = (pb_DummyScript[])Resources.FindObjectsOfTypeAll(typeof(pb_DummyScript)); dummies = dummies.Where(x => x.hideFlags == HideFlags.None).ToArray(); if(dummies.Length > 0) { int ret = EditorUtility.DisplayDialogComplex("Found Unrepairable Objects", "Repair script found " + dummies.Length + " missing components that could not be repaired. Would you like to delete those components now, or attempt to rebuild (ProBuilderize) them?", "Delete", "Cancel", "ProBuilderize"); switch(ret) { case 1: // cancel {} break; default: { // Delete and ProBuilderize if(ret == 2) { // Only interested in objects that have 2 null components (pb_Object and pb_Entity) Object[] broken = (Object[])Resources.FindObjectsOfTypeAll(typeof(GameObject)) .Where(x => !x.Equals(null) && x is GameObject && ((GameObject)x).GetComponents<pb_DummyScript>().Length == 2 && ((GameObject)x).GetComponent<MeshRenderer>() != null && ((GameObject)x).GetComponent<MeshFilter>() != null && ((GameObject)x).GetComponent<MeshFilter>().sharedMesh != null ).ToArray(); broken = broken.Distinct().ToArray(); pb_Menu_Commands.ProBuilderize(System.Array.ConvertAll(broken, x => (GameObject)x).ToArray(), true); } // Always delete components Undo.RecordObjects(dummies.Select(x=>x.gameObject).ToArray(), "Delete Broken Scripts"); for(int i = 0; i < dummies.Length; i++) GameObject.DestroyImmediate( dummies[i] ); } break; } } } /** * Returns a formatted string with all properties in serialized object. */ static string SerializedObjectToString(SerializedObject serializedObject) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(serializedObject == null) { sb.Append("NULL"); return sb.ToString(); } SerializedProperty iterator = serializedObject.GetIterator(); iterator.Next(true); while( iterator.Next(true) ) { string tabs = ""; for(int i = 0; i < iterator.depth; i++) tabs += "\t"; sb.AppendLine(tabs + iterator.name + (iterator.propertyType == SerializedPropertyType.ObjectReference && iterator.type.Contains("Component") && iterator.objectReferenceValue == null ? " -> NULL" : "") ); tabs += " - "; sb.AppendLine(tabs + "Type: (" + iterator.type + " / " + iterator.propertyType + " / " + " / " + iterator.name + ")"); sb.AppendLine(tabs + iterator.propertyPath); sb.AppendLine(tabs + "Value: " + SerializedPropertyValue(iterator)); } return sb.ToString(); } /** * Return a string from the value of a SerializedProperty. */ static string SerializedPropertyValue(SerializedProperty sp) { switch(sp.propertyType) { case SerializedPropertyType.Integer: return sp.intValue.ToString(); case SerializedPropertyType.Boolean: return sp.boolValue.ToString(); case SerializedPropertyType.Float: return sp.floatValue.ToString(); case SerializedPropertyType.String: return sp.stringValue.ToString(); case SerializedPropertyType.Color: return sp.colorValue.ToString(); case SerializedPropertyType.ObjectReference: return (sp.objectReferenceValue == null ? "null" : sp.objectReferenceValue.name); case SerializedPropertyType.LayerMask: return sp.intValue.ToString(); case SerializedPropertyType.Enum: return sp.enumValueIndex.ToString(); case SerializedPropertyType.Vector2: return sp.vector2Value.ToString(); case SerializedPropertyType.Vector3: return sp.vector3Value.ToString(); // Not public api as of 4.3? // case SerializedPropertyType.Vector4: // return sp.vector4Value.ToString(); case SerializedPropertyType.Rect: return sp.rectValue.ToString(); case SerializedPropertyType.ArraySize: return sp.intValue.ToString(); case SerializedPropertyType.Character: return "Character"; case SerializedPropertyType.AnimationCurve: return sp.animationCurveValue.ToString(); case SerializedPropertyType.Bounds: return sp.boundsValue.ToString(); case SerializedPropertyType.Gradient: return "Gradient"; default: return "Unknown type"; } } } }
// DeflaterHuffman.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7 using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the DeflaterHuffman class. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of Deflate and SetInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> internal class DeflaterHuffman { const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); const int LITERAL_NUM = 286; // Number of distance codes const int DIST_NUM = 30; // Number of codes used to transfer bit lengths const int BITLEN_NUM = 19; // repeat previous bit length 3-6 times (2 bits of repeat count) const int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) const int REP_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) const int REP_11_138 = 18; const int EOF_SYMBOL = 256; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit length codes. static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static readonly byte[] bit4Reverse = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; static short[] staticLCodes; static byte[] staticLLength; static short[] staticDCodes; static byte[] staticDLength; class Tree { #region Instance Fields public short[] freqs; public byte[] length; public int minNumCodes; public int numCodes; short[] codes; int[] bl_counts; int maxLength; DeflaterHuffman dh; #endregion #region Constructors public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) { this.dh = dh; this.minNumCodes = minCodes; this.maxLength = maxLength; freqs = new short[elems]; bl_counts = new int[maxLength]; } #endregion /// <summary> /// Resets the internal state of the tree /// </summary> public void Reset() { for (int i = 0; i < freqs.Length; i++) { freqs[i] = 0; } codes = null; length = null; } public void WriteSymbol(int code) { // if (DeflaterConstants.DEBUGGING) { // freqs[code]--; // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); // } dh.pending.WriteBits(codes[code] & 0xffff, length[code]); } /// <summary> /// Check that all frequencies are zero /// </summary> /// <exception cref="SharpZipBaseException"> /// At least one frequency is non-zero /// </exception> public void CheckEmpty() { bool empty = true; for (int i = 0; i < freqs.Length; i++) { if (freqs[i] != 0) { //Console.WriteLine("freqs[" + i + "] == " + freqs[i]); empty = false; } } if (!empty) { throw new SharpZipBaseException("!Empty"); } } /// <summary> /// Set static codes and length /// </summary> /// <param name="staticCodes">new codes</param> /// <param name="staticLengths">length for new codes</param> public void SetStaticCodes(short[] staticCodes, byte[] staticLengths) { codes = staticCodes; length = staticLengths; } /// <summary> /// Build dynamic codes and lengths /// </summary> public void BuildCodes() { int numSymbols = freqs.Length; int[] nextCode = new int[maxLength]; int code = 0; codes = new short[freqs.Length]; // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("buildCodes: "+freqs.Length); // } for (int bits = 0; bits < maxLength; bits++) { nextCode[bits] = code; code += bl_counts[bits] << (15 - bits); // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] // +" nextCode: "+code); // } } #if DebugDeflation if ( DeflaterConstants.DEBUGGING && (code != 65536) ) { throw new SharpZipBaseException("Inconsistent bl_counts!"); } #endif for (int i=0; i < numCodes; i++) { int bits = length[i]; if (bits > 0) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), // +bits); // } codes[i] = BitReverse(nextCode[bits-1]); nextCode[bits-1] += 1 << (16 - bits); } } } public void BuildTree() { int numSymbols = freqs.Length; /* heap is a priority queue, sorted by frequency, least frequent * nodes first. The heap is a binary tree, with the property, that * the parent node is smaller than both child nodes. This assures * that the smallest node is the first parent. * * The binary tree is encoded in an array: 0 is root node and * the nodes 2*n+1, 2*n+2 are the child nodes of node n. */ int[] heap = new int[numSymbols]; int heapLen = 0; int maxCode = 0; for (int n = 0; n < numSymbols; n++) { int freq = freqs[n]; if (freq != 0) { // Insert n into heap int pos = heapLen++; int ppos; while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { heap[pos] = heap[ppos]; pos = ppos; } heap[pos] = n; maxCode = n; } } /* We could encode a single literal with 0 bits but then we * don't see the literals. Therefore we force at least two * literals to avoid this case. We don't care about order in * this case, both literals get a 1 bit code. */ while (heapLen < 2) { int node = maxCode < 2 ? ++maxCode : 0; heap[heapLen++] = node; } numCodes = Math.Max(maxCode + 1, minNumCodes); int numLeafs = heapLen; int[] childs = new int[4 * heapLen - 2]; int[] values = new int[2 * heapLen - 1]; int numNodes = numLeafs; for (int i = 0; i < heapLen; i++) { int node = heap[i]; childs[2 * i] = node; childs[2 * i + 1] = -1; values[i] = freqs[node] << 8; heap[i] = i; } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { int first = heap[0]; int last = heap[--heapLen]; // Propagate the hole to the leafs of the heap int ppos = 0; int path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = path * 2 + 1; } /* Now propagate the last element down along path. Normally * it shouldn't go too deep. */ int lastVal = values[last]; while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; int second = heap[0]; // Create a new node father of first and second last = numNodes++; childs[2 * last] = first; childs[2 * last + 1] = second; int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); values[last] = lastVal = values[first] + values[second] - mindepth + 1; // Again, propagate the hole to the leafs ppos = 0; path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = ppos * 2 + 1; } // Now propagate the new element down along path while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; } while (heapLen > 1); if (heap[0] != childs.Length / 2 - 1) { throw new SharpZipBaseException("Heap invariant violated"); } BuildLength(childs); } /// <summary> /// Get encoded length /// </summary> /// <returns>Encoded length, the sum of frequencies * lengths</returns> public int GetEncodedLength() { int len = 0; for (int i = 0; i < freqs.Length; i++) { len += freqs[i] * length[i]; } return len; } /// <summary> /// Scan a literal or distance tree to determine the frequencies of the codes /// in the bit length tree. /// </summary> public void CalcBLFreq(Tree blTree) { int max_count; /* max repeat count */ int min_count; /* min repeat count */ int count; /* repeat count of the current code */ int curlen = -1; /* length of current code */ int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.freqs[nextlen]++; count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { blTree.freqs[curlen] += (short)count; } else if (curlen != 0) { blTree.freqs[REP_3_6]++; } else if (count <= 10) { blTree.freqs[REP_3_10]++; } else { blTree.freqs[REP_11_138]++; } } } /// <summary> /// Write tree values /// </summary> /// <param name="blTree">Tree to write</param> public void WriteTree(Tree blTree) { int max_count; // max repeat count int min_count; // min repeat count int count; // repeat count of the current code int curlen = -1; // length of current code int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.WriteSymbol(nextlen); count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { while (count-- > 0) { blTree.WriteSymbol(curlen); } } else if (curlen != 0) { blTree.WriteSymbol(REP_3_6); dh.pending.WriteBits(count - 3, 2); } else if (count <= 10) { blTree.WriteSymbol(REP_3_10); dh.pending.WriteBits(count - 3, 3); } else { blTree.WriteSymbol(REP_11_138); dh.pending.WriteBits(count - 11, 7); } } } void BuildLength(int[] childs) { this.length = new byte [freqs.Length]; int numNodes = childs.Length / 2; int numLeafs = (numNodes + 1) / 2; int overflow = 0; for (int i = 0; i < maxLength; i++) { bl_counts[i] = 0; } // First calculate optimal bit lengths int[] lengths = new int[numNodes]; lengths[numNodes-1] = 0; for (int i = numNodes - 1; i >= 0; i--) { if (childs[2 * i + 1] != -1) { int bitLength = lengths[i] + 1; if (bitLength > maxLength) { bitLength = maxLength; overflow++; } lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength; } else { // A leaf node int bitLength = lengths[i]; bl_counts[bitLength - 1]++; this.length[childs[2*i]] = (byte) lengths[i]; } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } if (overflow == 0) { return; } int incrBitLen = maxLength - 1; do { // Find the first bit length which could increase: while (bl_counts[--incrBitLen] == 0) ; // Move this node one down and remove a corresponding // number of overflow nodes. do { bl_counts[incrBitLen]--; bl_counts[++incrBitLen]++; overflow -= 1 << (maxLength - 1 - incrBitLen); } while (overflow > 0 && incrBitLen < maxLength - 1); } while (overflow > 0); /* We may have overshot above. Move some nodes from maxLength to * maxLength-1 in that case. */ bl_counts[maxLength-1] += overflow; bl_counts[maxLength-2] -= overflow; /* Now recompute all bit lengths, scanning in increasing * frequency. It is simpler to reconstruct all lengths instead of * fixing only the wrong ones. This idea is taken from 'ar' * written by Haruhiko Okumura. * * The nodes were inserted with decreasing frequency into the childs * array. */ int nodePtr = 2 * numLeafs; for (int bits = maxLength; bits != 0; bits--) { int n = bl_counts[bits-1]; while (n > 0) { int childPtr = 2*childs[nodePtr++]; if (childs[childPtr + 1] == -1) { // We found another leaf length[childs[childPtr]] = (byte) bits; n--; } } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("*** After overflow elimination. ***"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } } } #region Instance Fields /// <summary> /// Pending buffer to use /// </summary> public DeflaterPending pending; Tree literalTree; Tree distTree; Tree blTree; // Buffer for distances short[] d_buf; byte[] l_buf; int last_lit; int extra_bits; #endregion static DeflaterHuffman() { // See RFC 1951 3.2.6 // Literal codes staticLCodes = new short[LITERAL_NUM]; staticLLength = new byte[LITERAL_NUM]; int i = 0; while (i < 144) { staticLCodes[i] = BitReverse((0x030 + i) << 8); staticLLength[i++] = 8; } while (i < 256) { staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); staticLLength[i++] = 9; } while (i < 280) { staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); staticLLength[i++] = 7; } while (i < LITERAL_NUM) { staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); staticLLength[i++] = 8; } // Distance codes staticDCodes = new short[DIST_NUM]; staticDLength = new byte[DIST_NUM]; for (i = 0; i < DIST_NUM; i++) { staticDCodes[i] = BitReverse(i << 11); staticDLength[i] = 5; } } /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending">Pending buffer to use</param> public DeflaterHuffman(DeflaterPending pending) { this.pending = pending; literalTree = new Tree(this, LITERAL_NUM, 257, 15); distTree = new Tree(this, DIST_NUM, 1, 15); blTree = new Tree(this, BITLEN_NUM, 4, 7); d_buf = new short[BUFSIZE]; l_buf = new byte [BUFSIZE]; } /// <summary> /// Reset internal state /// </summary> public void Reset() { last_lit = 0; extra_bits = 0; literalTree.Reset(); distTree.Reset(); blTree.Reset(); } /// <summary> /// Write all trees to pending buffer /// </summary> /// <param name="blTreeCodes">The number/rank of treecodes to send.</param> public void SendAllTrees(int blTreeCodes) { blTree.BuildCodes(); literalTree.BuildCodes(); distTree.BuildCodes(); pending.WriteBits(literalTree.numCodes - 257, 5); pending.WriteBits(distTree.numCodes - 1, 5); pending.WriteBits(blTreeCodes - 4, 4); for (int rank = 0; rank < blTreeCodes; rank++) { pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); } literalTree.WriteTree(blTree); distTree.WriteTree(blTree); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { blTree.CheckEmpty(); } #endif } /// <summary> /// Compress current buffer writing data to pending buffer /// </summary> public void CompressBlock() { for (int i = 0; i < last_lit; i++) { int litlen = l_buf[i] & 0xff; int dist = d_buf[i]; if (dist-- != 0) { // if (DeflaterConstants.DEBUGGING) { // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); // } int lc = Lcode(litlen); literalTree.WriteSymbol(lc); int bits = (lc - 261) / 4; if (bits > 0 && bits <= 5) { pending.WriteBits(litlen & ((1 << bits) - 1), bits); } int dc = Dcode(dist); distTree.WriteSymbol(dc); bits = dc / 2 - 1; if (bits > 0) { pending.WriteBits(dist & ((1 << bits) - 1), bits); } } else { // if (DeflaterConstants.DEBUGGING) { // if (litlen > 32 && litlen < 127) { // Console.Write("("+(char)litlen+"): "); // } else { // Console.Write("{"+litlen+"}: "); // } // } literalTree.WriteSymbol(litlen); } } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.Write("EOF: "); } #endif literalTree.WriteSymbol(EOF_SYMBOL); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { literalTree.CheckEmpty(); distTree.CheckEmpty(); } #endif } /// <summary> /// Flush block to output with no compression /// </summary> /// <param name="stored">Data to write</param> /// <param name="storedOffset">Index of first byte to write</param> /// <param name="storedLength">Count of bytes to write</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { #if DebugDeflation // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Flushing stored block "+ storedLength); // } #endif pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); pending.AlignToByte(); pending.WriteShort(storedLength); pending.WriteShort(~storedLength); pending.WriteBlock(stored, storedOffset, storedLength); Reset(); } /// <summary> /// Flush block to output with compression /// </summary> /// <param name="stored">Data to flush</param> /// <param name="storedOffset">Index of first byte to flush</param> /// <param name="storedLength">Count of bytes to flush</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { literalTree.freqs[EOF_SYMBOL]++; // Build trees literalTree.BuildTree(); distTree.BuildTree(); // Calculate bitlen frequency literalTree.CalcBLFreq(blTree); distTree.CalcBLFreq(blTree); // Build bitlen tree blTree.BuildTree(); int blTreeCodes = 4; for (int i = 18; i > blTreeCodes; i--) { if (blTree.length[BL_ORDER[i]] > 0) { blTreeCodes = i+1; } } int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + literalTree.GetEncodedLength() + distTree.GetEncodedLength() + extra_bits; int static_len = extra_bits; for (int i = 0; i < LITERAL_NUM; i++) { static_len += literalTree.freqs[i] * staticLLength[i]; } for (int i = 0; i < DIST_NUM; i++) { static_len += distTree.freqs[i] * staticDLength[i]; } if (opt_len >= static_len) { // Force static trees opt_len = static_len; } if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { // Store Block // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len // + " <= " + static_len); // } FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); } else if (opt_len == static_len) { // Encode with static tree pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); literalTree.SetStaticCodes(staticLCodes, staticLLength); distTree.SetStaticCodes(staticDCodes, staticDLength); CompressBlock(); Reset(); } else { // Encode with dynamic tree pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); SendAllTrees(blTreeCodes); CompressBlock(); Reset(); } } /// <summary> /// Get value indicating if internal buffer is full /// </summary> /// <returns>true if buffer is full</returns> public bool IsFull() { return last_lit >= BUFSIZE; } /// <summary> /// Add literal to buffer /// </summary> /// <param name="literal">Literal value to add to buffer.</param> /// <returns>Value indicating internal buffer is full</returns> public bool TallyLit(int literal) { // if (DeflaterConstants.DEBUGGING) { // if (lit > 32 && lit < 127) { // //Console.WriteLine("("+(char)lit+")"); // } else { // //Console.WriteLine("{"+lit+"}"); // } // } d_buf[last_lit] = 0; l_buf[last_lit++] = (byte)literal; literalTree.freqs[literal]++; return IsFull(); } /// <summary> /// Add distance code and length to literal and distance trees /// </summary> /// <param name="distance">Distance code</param> /// <param name="length">Length</param> /// <returns>Value indicating if internal buffer is full</returns> public bool TallyDist(int distance, int length) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("[" + distance + "," + length + "]"); // } d_buf[last_lit] = (short)distance; l_buf[last_lit++] = (byte)(length - 3); int lc = Lcode(length - 3); literalTree.freqs[lc]++; if (lc >= 265 && lc < 285) { extra_bits += (lc - 261) / 4; } int dc = Dcode(distance - 1); distTree.freqs[dc]++; if (dc >= 4) { extra_bits += dc / 2 - 1; } return IsFull(); } /// <summary> /// Reverse the bits of a 16 bit value. /// </summary> /// <param name="toReverse">Value to reverse bits</param> /// <returns>Value with bits reversed</returns> public static short BitReverse(int toReverse) { return (short) (bit4Reverse[toReverse & 0xF] << 12 | bit4Reverse[(toReverse >> 4) & 0xF] << 8 | bit4Reverse[(toReverse >> 8) & 0xF] << 4 | bit4Reverse[toReverse >> 12]); } static int Lcode(int length) { if (length == 255) { return 285; } int code = 257; while (length >= 8) { code += 4; length >>= 1; } return code + length; } static int Dcode(int distance) { int code = 0; while (distance >= 4) { code += 2; distance >>= 1; } return code + distance; } } }
//----------------------------------------------------------------------- // <copyright file="Form1.Designer.cs" company="VillageIdiot"> // Copyright (c) Village Idiot. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace ArzExplorer { /// <summary> /// Class for Form1 Designer Generated code. /// </summary> public partial class MainForm { /// <summary> /// Generated menu strip /// </summary> private System.Windows.Forms.MenuStrip menuStrip1; /// <summary> /// Generated File menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; /// <summary> /// Generated Open menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; /// <summary> /// Generated Exit menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; /// <summary> /// Generated Extract menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem extractToolStripMenuItem; /// <summary> /// Generated Help menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; /// <summary> /// Generated About menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; /// <summary> /// Generated Selected File menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem selectedFileToolStripMenuItem; /// <summary> /// Generated All Files menu item /// </summary> private System.Windows.Forms.ToolStripMenuItem allFilesToolStripMenuItem; /// <summary> /// Generated TreeView /// </summary> private System.Windows.Forms.TreeView treeViewTOC; /// <summary> /// Generated TextBox /// </summary> private System.Windows.Forms.TextBox textBoxDetails; /// <summary> /// Generated PictureBox /// </summary> private System.Windows.Forms.PictureBox pictureBoxItem; /// <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 && (this.components != null)) { this.components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle10 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle11 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle12 = new System.Windows.Forms.DataGridViewCellStyle(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.extractToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.selectedFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.allFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.treeViewTOC = new System.Windows.Forms.TreeView(); this.textBoxDetails = new System.Windows.Forms.TextBox(); this.pictureBoxItem = new System.Windows.Forms.PictureBox(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.hideZeroValuesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxItem)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.extractToolStripMenuItem, this.viewToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(803, 24); this.menuStrip1.TabIndex = 11; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.fileToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.openToolStripMenuItem.Text = "&Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.OpenToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItem_Click); // // extractToolStripMenuItem // this.extractToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; this.extractToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.selectedFileToolStripMenuItem, this.allFilesToolStripMenuItem}); this.extractToolStripMenuItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.extractToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; this.extractToolStripMenuItem.Name = "extractToolStripMenuItem"; this.extractToolStripMenuItem.Size = new System.Drawing.Size(52, 20); this.extractToolStripMenuItem.Text = "&Extract"; // // selectedFileToolStripMenuItem // this.selectedFileToolStripMenuItem.Name = "selectedFileToolStripMenuItem"; this.selectedFileToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.selectedFileToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.selectedFileToolStripMenuItem.Text = "&Selected File"; this.selectedFileToolStripMenuItem.Click += new System.EventHandler(this.SelectedFileToolStripMenuItem_Click); // // allFilesToolStripMenuItem // this.allFilesToolStripMenuItem.Name = "allFilesToolStripMenuItem"; this.allFilesToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A))); this.allFilesToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.allFilesToolStripMenuItem.Text = "&All Files"; this.allFilesToolStripMenuItem.Click += new System.EventHandler(this.AllFilesToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.helpToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(41, 20); this.helpToolStripMenuItem.Text = "&Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(102, 22); this.aboutToolStripMenuItem.Text = "&About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.AboutToolStripMenuItem_Click); // // treeViewTOC // this.treeViewTOC.Dock = System.Windows.Forms.DockStyle.Fill; this.treeViewTOC.Location = new System.Drawing.Point(0, 0); this.treeViewTOC.Name = "treeViewTOC"; this.treeViewTOC.Size = new System.Drawing.Size(281, 453); this.treeViewTOC.TabIndex = 12; this.treeViewTOC.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeView1_AfterSelect); // // textBoxDetails // this.textBoxDetails.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxDetails.Location = new System.Drawing.Point(50, 0); this.textBoxDetails.Multiline = true; this.textBoxDetails.Name = "textBoxDetails"; this.textBoxDetails.RightToLeft = System.Windows.Forms.RightToLeft.No; this.textBoxDetails.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textBoxDetails.Size = new System.Drawing.Size(468, 453); this.textBoxDetails.TabIndex = 13; // // pictureBoxItem // this.pictureBoxItem.Dock = System.Windows.Forms.DockStyle.Left; this.pictureBoxItem.Location = new System.Drawing.Point(0, 0); this.pictureBoxItem.MinimumSize = new System.Drawing.Size(50, 0); this.pictureBoxItem.Name = "pictureBoxItem"; this.pictureBoxItem.Size = new System.Drawing.Size(50, 453); this.pictureBoxItem.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBoxItem.TabIndex = 14; this.pictureBoxItem.TabStop = false; this.pictureBoxItem.Visible = false; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 24); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.treeViewTOC); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.dataGridView1); this.splitContainer1.Panel2.Controls.Add(this.textBoxDetails); this.splitContainer1.Panel2.Controls.Add(this.pictureBoxItem); this.splitContainer1.Size = new System.Drawing.Size(803, 453); this.splitContainer1.SplitterDistance = 281; this.splitContainer1.TabIndex = 15; // // dataGridView1 // this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; dataGridViewCellStyle10.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle10.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle10.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle10.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle10.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle10.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle10.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle10; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.Column1, this.Column2}); dataGridViewCellStyle11.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle11.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle11.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle11.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle11.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle11.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle11.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle11; this.dataGridView1.Location = new System.Drawing.Point(14, 3); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; dataGridViewCellStyle12.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle12.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle12.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle12.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle12.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle12.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle12.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle12; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.Size = new System.Drawing.Size(479, 438); this.dataGridView1.TabIndex = 15; this.dataGridView1.Visible = false; // // Column1 // this.Column1.HeaderText = "Variable"; this.Column1.Name = "Column1"; this.Column1.ReadOnly = true; this.Column1.Width = 70; // // Column2 // this.Column2.HeaderText = "Values"; this.Column2.Name = "Column2"; this.Column2.ReadOnly = true; this.Column2.Width = 64; // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.hideZeroValuesToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.viewToolStripMenuItem.Text = "&View"; // // hideZeroValuesToolStripMenuItem // this.hideZeroValuesToolStripMenuItem.Checked = true; this.hideZeroValuesToolStripMenuItem.CheckOnClick = true; this.hideZeroValuesToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.hideZeroValuesToolStripMenuItem.Enabled = false; this.hideZeroValuesToolStripMenuItem.Name = "hideZeroValuesToolStripMenuItem"; this.hideZeroValuesToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.hideZeroValuesToolStripMenuItem.Text = "Hide &Zero Values"; this.hideZeroValuesToolStripMenuItem.Click += new System.EventHandler(this.hideZeroValuesToolStripMenuItem_Click); // // MainForm // this.AllowDrop = true; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(803, 477); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.menuStrip1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.SystemColors.ControlText; this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "ARZ Explorer"; this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxItem)).EndInit(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.DataGridViewTextBoxColumn Column1; private System.Windows.Forms.DataGridViewTextBoxColumn Column2; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hideZeroValuesToolStripMenuItem; } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Tik_Tok_Tank { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { #region Declarations // Main declarations: graphics component and sprite-drawing class GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // Texture declarations Texture2D spriteSheet; Texture2D menuBackground; // font declarations SpriteFont menuItemFont; // Game states enum GameStates { TitleMenu, OptionsMenu, ControlsMenu, GameModesMenu, PauseMenu, GameOverMenu, Standard, Duel, Adventure, Coop }; GameStates gameState = GameStates.TitleMenu; // Menu declarations and timers Menus.Menu menu = new Menus.TitleMenu(); GameStates prevState; // used for pausing game float menuMinTimer = 15f; float menuTimer = 15f; float gameOverMinTimer = 180f; float gameOverTimer = 0f; // player controls Player.Controls player1Controls = Player.Controls.Computer; Player.Controls player2Controls = Player.Controls.Xbox1; #endregion public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // set window size this.graphics.PreferredBackBufferWidth = 800; this.graphics.PreferredBackBufferHeight = 600; this.graphics.ApplyChanges(); // set the mouse to be visible in game window this.IsMouseVisible = true; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Load textures used for game spriteSheet = Content.Load<Texture2D>(@"Textures\SpriteSheet"); menuBackground = Content.Load<Texture2D>(@"Textures\MenuBackground"); // Load fonts for game menuItemFont = Content.Load<SpriteFont>(@"Fonts\MenuItem"); // Camera initialization Camera.ViewPortWidth = this.graphics.PreferredBackBufferWidth; Camera.ViewPortHeight = this.graphics.PreferredBackBufferHeight; // WeaponManager initialization WeaponManager.Texture = spriteSheet; // SoundManager initialization SoundManager.Initialize(Content); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState keyState = Keyboard.GetState(); GamePadState padState = GamePad.GetState(PlayerIndex.One); // handle menu iteration menuTimer++; if (gameState == GameStates.TitleMenu || gameState == GameStates.OptionsMenu || gameState == GameStates.ControlsMenu || gameState == GameStates.GameModesMenu || gameState == GameStates.PauseMenu || gameState == GameStates.GameOverMenu) { if (menuTimer >= menuMinTimer) { if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S) || padState.ThumbSticks.Left.Y < -0.3) { menuTimer = 0f; menu.Iterator++; } else if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W) || padState.ThumbSticks.Left.Y > 0.3) { menuTimer = 0f; menu.Iterator--; } } } switch (gameState) { case GameStates.TitleMenu: if (keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { this.Exit(); } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: gameState = GameStates.GameModesMenu; menu = new Menus.GameModesMenu(); break; case 1: gameState = GameStates.OptionsMenu; menu = new Menus.OptionsMenu(); break; case 2: this.Exit(); break; } } } break; case GameStates.OptionsMenu: if (keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: gameState = GameStates.ControlsMenu; menu = new Menus.ControlsMenu(1); break; case 1: gameState = GameStates.ControlsMenu; menu = new Menus.ControlsMenu(2); break; case 2: if (SoundManager.MusicPlaying) { SoundManager.PauseBackgroundMusic(); } else { SoundManager.StartBackgroundMusic(); } break; case 3: gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; } } } break; case GameStates.ControlsMenu: if (keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; gameState = GameStates.OptionsMenu; menu = new Menus.OptionsMenu(); } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: if (menu.PlayerIndex == 1) { if (player2Controls == Player.Controls.Computer) { player2Controls = player1Controls; } player1Controls = Player.Controls.Computer; } else { if (player1Controls == Player.Controls.Computer) { player1Controls = player2Controls; } player2Controls = Player.Controls.Computer; } gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; case 1: if (menu.PlayerIndex == 1) { if (player2Controls == Player.Controls.Xbox1) { player2Controls = player1Controls; } player1Controls = Player.Controls.Xbox1; } else { if (player1Controls == Player.Controls.Xbox1) { player1Controls = player2Controls; } player2Controls = Player.Controls.Xbox1; } gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; case 2: if (menu.PlayerIndex == 1) { if (player2Controls == Player.Controls.Xbox2) { player2Controls = player1Controls; } player1Controls = Player.Controls.Xbox2; } else { if (player1Controls == Player.Controls.Computer) { player1Controls = player2Controls; } player2Controls = Player.Controls.Xbox2; } gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; case 3: gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; } } } break; case GameStates.GameModesMenu: if (keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: gameState = GameStates.Standard; Camera.WorldRectangle = new Rectangle(0, 0, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight); Camera.Reset(); TileMap.Initialize(spriteSheet, 17, 13); WeaponManager.ClearShotList(); PlayerManager.ClearPlayerList(); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(120, 120), "blue", player1Controls)); PlayerManager.NeededPlayers = 1; EnemyManager.Initialize(spriteSheet, 2); break; case 1: gameState = GameStates.Duel; Camera.WorldRectangle = new Rectangle(0, 0, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight); Camera.Reset(); TileMap.Initialize(spriteSheet, 17, 13); WeaponManager.ClearShotList(); PlayerManager.ClearPlayerList(); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(120, 120), "blue", player1Controls)); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(696, 504), "red", player2Controls)); PlayerManager.NeededPlayers = 2; break; case 2: gameState = GameStates.Coop; Camera.WorldRectangle = new Rectangle(0, 0, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight); Camera.Reset(); TileMap.Initialize(spriteSheet, 17, 13); WeaponManager.ClearShotList(); PlayerManager.ClearPlayerList(); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(120, 120), "blue", player1Controls)); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(696, 504), "red", player2Controls)); PlayerManager.NeededPlayers = 1; EnemyManager.Initialize(spriteSheet, 3); break; case 3: gameState = GameStates.Adventure; Camera.WorldRectangle = new Rectangle(0, 0, 1920, 1920); // camera initialization Camera.Reset(); TileMap.Initialize(spriteSheet, 40, 40); // TileMap initialization WeaponManager.ClearShotList(); PlayerManager.ClearPlayerList(); PlayerManager.AddPlayer(new Player(spriteSheet, new Vector2(120, 120), "blue", player1Controls)); PlayerManager.NeededPlayers = 1; EnemyManager.Initialize(spriteSheet, 5); break; case 4: gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; } } } break; case GameStates.PauseMenu: if (keyState.IsKeyDown(Keys.Escape) || keyState.IsKeyDown(Keys.P) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; gameState = prevState; } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: gameState = prevState; break; case 1: gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; case 2: this.Exit(); break; } } } break; case GameStates.GameOverMenu: if (keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); } } else if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Enter) || padState.IsButtonDown(Buttons.A)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; switch (menu.Iterator) { case 0: gameState = GameStates.TitleMenu; menu = new Menus.TitleMenu(); break; case 1: this.Exit(); break; } } } break; case GameStates.Standard: case GameStates.Duel: case GameStates.Adventure: case GameStates.Coop: EnemyManager.Update(gameTime); PlayerManager.Update(gameTime); WeaponManager.Update(gameTime); if (PlayerManager.GameFinished || ((gameState != GameStates.Duel) && !EnemyManager.EnemiesLeft)) { gameOverTimer++; if (gameOverTimer > gameOverMinTimer) { gameOverTimer = 0f; string gameOverTitle; if (gameState == GameStates.Duel) { if (PlayerManager.NumPlayers == 0) gameOverTitle = "Tie!"; else if (PlayerManager.GetPlayer(0).TankColor.Equals("blue")) gameOverTitle = "Blue Wins!"; else gameOverTitle = "Red Wins!"; } else if (!EnemyManager.EnemiesLeft) { gameOverTitle = "You Won!"; } else { gameOverTitle = "You Lost!"; } menuTimer = 0f; gameState = GameStates.GameOverMenu; menu = new Menus.GameOverMenu(gameOverTitle); } } else { if (keyState.IsKeyDown(Keys.P) || keyState.IsKeyDown(Keys.Escape) || padState.IsButtonDown(Buttons.Back) || padState.IsButtonDown(Buttons.Start)) { if (menuTimer >= menuMinTimer) { menuTimer = 0f; prevState = gameState; gameState = GameStates.PauseMenu; menu = new Menus.PauseMenu(); } } } break; } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); switch (gameState) { case GameStates.TitleMenu: case GameStates.OptionsMenu: case GameStates.ControlsMenu: case GameStates.GameModesMenu: case GameStates.PauseMenu: case GameStates.GameOverMenu: menu.DrawMenu(spriteBatch, menuBackground, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight, menuItemFont); break; case GameStates.Standard: case GameStates.Duel: case GameStates.Adventure: case GameStates.Coop: TileMap.Draw(spriteBatch); EnemyManager.Draw(spriteBatch); PlayerManager.Draw(spriteBatch); WeaponManager.Draw(spriteBatch); /*// Temporary Code Begin Vector2 mouseLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); mouseLocation += Camera.Position; mouseLocation.X = MathHelper.Clamp(mouseLocation.X, Camera.Position.X, Camera.Position.X + Camera.ViewPortWidth); mouseLocation.Y = MathHelper.Clamp(mouseLocation.Y, Camera.Position.Y, Camera.Position.Y + Camera.ViewPortHeight); if (PlayerManager.NumPlayers > 0) { List<Vector2> path = Astar.PathFinder.FindPath(TileMap.GetSquareAtPixel(mouseLocation), TileMap.GetSquareAtPixel(PlayerManager.GetPlayer(0).BaseSprite.WorldLocation)); if (path != null) { foreach (Vector2 node in path) { spriteBatch.Draw(spriteSheet, TileMap.SquareScreenRectangle((int)node.X, (int)node.Y), new Rectangle(0, 0, 48, 48), new Color(128, 0, 0, 80)); } } } // Temporary Code End*/ break; } spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using GoCardless.Internals; namespace GoCardless.Resources { /// <summary> /// Represents a creditor resource. /// /// Each [payment](#core-endpoints-payments) taken through the API is linked /// to a "creditor", to whom the payment is then paid out. In most cases /// your organisation will have a single "creditor", but the API also /// supports collecting payments on behalf of others. /// /// Currently, for Anti Money Laundering reasons, any creditors you add must /// be directly related to your organisation. /// </summary> public class Creditor { /// <summary> /// The first line of the creditor's address. /// </summary> [JsonProperty("address_line1")] public string AddressLine1 { get; set; } /// <summary> /// The second line of the creditor's address. /// </summary> [JsonProperty("address_line2")] public string AddressLine2 { get; set; } /// <summary> /// The third line of the creditor's address. /// </summary> [JsonProperty("address_line3")] public string AddressLine3 { get; set; } /// <summary> /// Boolean indicating whether the creditor is permitted to create /// refunds /// </summary> [JsonProperty("can_create_refunds")] public bool? CanCreateRefunds { get; set; } /// <summary> /// The city of the creditor's address. /// </summary> [JsonProperty("city")] public string City { get; set; } /// <summary> /// [ISO 3166-1 alpha-2 /// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) /// </summary> [JsonProperty("country_code")] public string CountryCode { get; set; } /// <summary> /// Fixed [timestamp](#api-usage-time-zones--dates), recording when this /// resource was created. /// </summary> [JsonProperty("created_at")] public DateTimeOffset? CreatedAt { get; set; } /// <summary> /// Boolean value indicating whether creditor has the [Custom Payment /// Pages](https://support.gocardless.com/hc/en-gb/articles/115003734705-Custom-payment-pages) /// functionality enabled. /// </summary> [JsonProperty("custom_payment_pages_enabled")] public bool? CustomPaymentPagesEnabled { get; set; } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) code /// for the currency in which amounts will be paid out (after foreign /// exchange). Currently "AUD", "CAD", "DKK", "EUR", "GBP", "NZD", "SEK" /// and "USD" are supported. Present only if payouts will be (or were) /// made via foreign exchange. /// </summary> [JsonProperty("fx_payout_currency")] public CreditorFxPayoutCurrency? FxPayoutCurrency { get; set; } /// <summary> /// Unique identifier, beginning with "CR". /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// Resources linked to this Creditor. /// </summary> [JsonProperty("links")] public CreditorLinks Links { get; set; } /// <summary> /// URL for the creditor's logo, which may be shown on their payment /// pages. /// </summary> [JsonProperty("logo_url")] public string LogoUrl { get; set; } /// <summary> /// Boolean value indicating whether creditor has the [Mandate /// Imports](#core-endpoints-mandate-imports) functionality enabled. /// </summary> [JsonProperty("mandate_imports_enabled")] public bool? MandateImportsEnabled { get; set; } /// <summary> /// Boolean value indicating whether the organisation is responsible for /// sending all customer notifications (note this is separate from the /// functionality described /// [here](/getting-started/api/handling-customer-notifications/)). If /// you are a partner app, and this value is true, you should not send /// notifications on behalf of this organisation. /// </summary> [JsonProperty("merchant_responsible_for_notifications")] public bool? MerchantResponsibleForNotifications { get; set; } /// <summary> /// The creditor's name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The creditor's postal code. /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; set; } /// <summary> /// The creditor's address region, county or department. /// </summary> [JsonProperty("region")] public string Region { get; set; } /// <summary> /// An array of the scheme identifiers this creditor can create mandates /// against. /// /// The support address, `phone_number` and `email` fields are for /// customers to contact the merchant for support purposes. They must be /// displayed on the payment page, please see our [compliance /// requirements](#appendix-compliance-requirements) for more details. /// </summary> [JsonProperty("scheme_identifiers")] public List<CreditorSchemeIdentifier> SchemeIdentifiers { get; set; } /// <summary> /// The creditor's verification status, indicating whether they can yet /// receive payouts. For more details on handling verification as a /// partner, see our ["Helping your users get verified" /// guide](/getting-started/partners/helping-your-users-get-verified/). /// One of: /// <ul> /// <li>`successful`: The creditor's account is fully verified, and they /// can receive payouts. Once a creditor has been successfully verified, /// they may in the future require further verification - for example, /// if they change their payout bank account, we will have to check that /// they own the new bank account before they can receive payouts /// again.</li> /// <li>`in_review`: The creditor has provided all of the information /// currently requested, and it is awaiting review by GoCardless before /// they can be verified and receive payouts.</li> /// <li>`action_required`: The creditor needs to provide further /// information to verify their account so they can receive payouts, and /// should visit the verification flow.</li> /// </ul> /// </summary> [JsonProperty("verification_status")] public CreditorVerificationStatus? VerificationStatus { get; set; } } /// <summary> /// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes) code for the currency in /// which amounts will be paid out (after foreign exchange). Currently "AUD", "CAD", "DKK", /// "EUR", "GBP", "NZD", "SEK" and "USD" are supported. Present only if payouts will be (or /// were) made via foreign exchange. /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum CreditorFxPayoutCurrency { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`fx_payout_currency` with a value of "AUD"</summary> [EnumMember(Value = "AUD")] AUD, /// <summary>`fx_payout_currency` with a value of "CAD"</summary> [EnumMember(Value = "CAD")] CAD, /// <summary>`fx_payout_currency` with a value of "DKK"</summary> [EnumMember(Value = "DKK")] DKK, /// <summary>`fx_payout_currency` with a value of "EUR"</summary> [EnumMember(Value = "EUR")] EUR, /// <summary>`fx_payout_currency` with a value of "GBP"</summary> [EnumMember(Value = "GBP")] GBP, /// <summary>`fx_payout_currency` with a value of "NZD"</summary> [EnumMember(Value = "NZD")] NZD, /// <summary>`fx_payout_currency` with a value of "SEK"</summary> [EnumMember(Value = "SEK")] SEK, /// <summary>`fx_payout_currency` with a value of "USD"</summary> [EnumMember(Value = "USD")] USD, } /// <summary> /// Resources linked to this Creditor /// </summary> public class CreditorLinks { /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in AUD. /// </summary> [JsonProperty("default_aud_payout_account")] public string DefaultAudPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in CAD. /// </summary> [JsonProperty("default_cad_payout_account")] public string DefaultCadPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in DKK. /// </summary> [JsonProperty("default_dkk_payout_account")] public string DefaultDkkPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in EUR. /// </summary> [JsonProperty("default_eur_payout_account")] public string DefaultEurPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in GBP. /// </summary> [JsonProperty("default_gbp_payout_account")] public string DefaultGbpPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in NZD. /// </summary> [JsonProperty("default_nzd_payout_account")] public string DefaultNzdPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in SEK. /// </summary> [JsonProperty("default_sek_payout_account")] public string DefaultSekPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in USD. /// </summary> [JsonProperty("default_usd_payout_account")] public string DefaultUsdPayoutAccount { get; set; } } /// <summary> /// An array of the scheme identifiers this creditor can create mandates /// against. /// /// The support address, `phone_number` and `email` fields are for customers /// to contact the merchant for support purposes. They must be displayed on /// the payment page, please see our [compliance /// requirements](#appendix-compliance-requirements) for more details. /// </summary> public class CreditorSchemeIdentifier { /// <summary> /// The first line of the support address. /// </summary> [JsonProperty("address_line1")] public string AddressLine1 { get; set; } /// <summary> /// The second line of the support address. /// </summary> [JsonProperty("address_line2")] public string AddressLine2 { get; set; } /// <summary> /// The third line of the support address. /// </summary> [JsonProperty("address_line3")] public string AddressLine3 { get; set; } /// <summary> /// Whether a custom reference can be submitted for mandates using this /// scheme identifier. /// </summary> [JsonProperty("can_specify_mandate_reference")] public bool? CanSpecifyMandateReference { get; set; } /// <summary> /// The city of the support address. /// </summary> [JsonProperty("city")] public string City { get; set; } /// <summary> /// [ISO 3166-1 alpha-2 /// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) /// </summary> [JsonProperty("country_code")] public string CountryCode { get; set; } /// <summary> /// The currency of the scheme identifier. /// </summary> [JsonProperty("currency")] public CreditorSchemeIdentifierCurrency? Currency { get; set; } /// <summary> /// The support email address. /// </summary> [JsonProperty("email")] public string Email { get; set; } /// <summary> /// The minimum interval, in working days, between the sending of a /// pre-notification to the customer, and the charge date of a payment /// using this scheme identifier. /// /// By default, GoCardless sends these notifications automatically. /// Please see our [compliance /// requirements](#appendix-compliance-requirements) for more details. /// </summary> [JsonProperty("minimum_advance_notice")] public int? MinimumAdvanceNotice { get; set; } /// <summary> /// The name which appears on customers' bank statements. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The support phone number. /// </summary> [JsonProperty("phone_number")] public string PhoneNumber { get; set; } /// <summary> /// The support postal code. /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; set; } /// <summary> /// The scheme-unique identifier against which payments are submitted. /// </summary> [JsonProperty("reference")] public string Reference { get; set; } /// <summary> /// The support address region, county or department. /// </summary> [JsonProperty("region")] public string Region { get; set; } /// <summary> /// The scheme which this scheme identifier applies to. /// </summary> [JsonProperty("scheme")] public CreditorSchemeIdentifierScheme? Scheme { get; set; } } /// <summary> /// The currency of the scheme identifier. /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum CreditorSchemeIdentifierCurrency { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`currency` with a value of "AUD"</summary> [EnumMember(Value = "AUD")] AUD, /// <summary>`currency` with a value of "CAD"</summary> [EnumMember(Value = "CAD")] CAD, /// <summary>`currency` with a value of "DKK"</summary> [EnumMember(Value = "DKK")] DKK, /// <summary>`currency` with a value of "EUR"</summary> [EnumMember(Value = "EUR")] EUR, /// <summary>`currency` with a value of "GBP"</summary> [EnumMember(Value = "GBP")] GBP, /// <summary>`currency` with a value of "NZD"</summary> [EnumMember(Value = "NZD")] NZD, /// <summary>`currency` with a value of "SEK"</summary> [EnumMember(Value = "SEK")] SEK, /// <summary>`currency` with a value of "USD"</summary> [EnumMember(Value = "USD")] USD, } /// <summary> /// The scheme which this scheme identifier applies to. /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum CreditorSchemeIdentifierScheme { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`scheme` with a value of "ach"</summary> [EnumMember(Value = "ach")] Ach, /// <summary>`scheme` with a value of "autogiro"</summary> [EnumMember(Value = "autogiro")] Autogiro, /// <summary>`scheme` with a value of "bacs"</summary> [EnumMember(Value = "bacs")] Bacs, /// <summary>`scheme` with a value of "becs"</summary> [EnumMember(Value = "becs")] Becs, /// <summary>`scheme` with a value of "becs_nz"</summary> [EnumMember(Value = "becs_nz")] BecsNz, /// <summary>`scheme` with a value of "betalingsservice"</summary> [EnumMember(Value = "betalingsservice")] Betalingsservice, /// <summary>`scheme` with a value of "faster_payments"</summary> [EnumMember(Value = "faster_payments")] FasterPayments, /// <summary>`scheme` with a value of "pad"</summary> [EnumMember(Value = "pad")] Pad, /// <summary>`scheme` with a value of "sepa"</summary> [EnumMember(Value = "sepa")] Sepa, /// <summary>`scheme` with a value of "sepa_credit_transfer"</summary> [EnumMember(Value = "sepa_credit_transfer")] SepaCreditTransfer, /// <summary>`scheme` with a value of "sepa_instant_credit_transfer"</summary> [EnumMember(Value = "sepa_instant_credit_transfer")] SepaInstantCreditTransfer, } /// <summary> /// The creditor's verification status, indicating whether they can yet receive payouts. For /// more details on handling verification as a partner, see our ["Helping your users get /// verified" guide](/getting-started/partners/helping-your-users-get-verified/). One of: /// <ul> /// <li>`successful`: The creditor's account is fully verified, and they can receive payouts. /// Once a creditor has been successfully verified, they may in the future require further /// verification - for example, if they change their payout bank account, we will have to check /// that they own the new bank account before they can receive payouts again.</li> /// <li>`in_review`: The creditor has provided all of the information currently requested, and /// it is awaiting review by GoCardless before they can be verified and receive payouts.</li> /// <li>`action_required`: The creditor needs to provide further information to verify their /// account so they can receive payouts, and should visit the verification flow.</li> /// </ul> /// </summary> [JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)] public enum CreditorVerificationStatus { /// <summary>Unknown status</summary> [EnumMember(Value = "unknown")] Unknown = 0, /// <summary>`verification_status` with a value of "successful"</summary> [EnumMember(Value = "successful")] Successful, /// <summary>`verification_status` with a value of "in_review"</summary> [EnumMember(Value = "in_review")] InReview, /// <summary>`verification_status` with a value of "action_required"</summary> [EnumMember(Value = "action_required")] ActionRequired, } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using System.Threading; using System.Globalization; using NUnit.Common; using NUnit.Framework; #if !NETCF using System.Security.Principal; #endif using NUnit.TestData.TestContextData; using NUnit.TestUtilities; namespace NUnit.Framework.Internal { /// <summary> /// Summary description for TestExecutionContextTests. /// </summary> [TestFixture][Property("Question", "Why?")] public class TestExecutionContextTests { TestExecutionContext fixtureContext; TestExecutionContext setupContext; #if !NETCF && !SILVERLIGHT && !PORTABLE string originalDirectory; IPrincipal originalPrincipal; #endif [OneTimeSetUp] public void OneTimeSetUp() { fixtureContext = TestExecutionContext.CurrentContext; } [OneTimeTearDown] public void OneTimeTearDown() { // TODO: We put some tests in one time teardown to verify that // the context is still valid. It would be better if these tests // were placed in a second-level test, invoked from this test class. TestExecutionContext ec = TestExecutionContext.CurrentContext; Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(ec.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } /// <summary> /// Since we are testing the mechanism that saves and /// restores contexts, we save manually here /// </summary> [SetUp] public void Initialize() { setupContext = new TestExecutionContext(TestExecutionContext.CurrentContext); #if !NETCF originalCulture = CultureInfo.CurrentCulture; originalUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE originalDirectory = Environment.CurrentDirectory; originalPrincipal = Thread.CurrentPrincipal; #endif } [TearDown] public void Cleanup() { #if !NETCF Thread.CurrentThread.CurrentCulture = originalCulture; Thread.CurrentThread.CurrentUICulture = originalUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE Environment.CurrentDirectory = originalDirectory; Thread.CurrentPrincipal = originalPrincipal; #endif Assert.That( TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo(setupContext.CurrentTest.FullName), "Context at TearDown failed to match that saved from SetUp"); } #region CurrentTest [Test] public void FixtureSetUpCanAccessFixtureName() { Assert.That(fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); } [Test] public void FixtureSetUpCanAccessFixtureFullName() { Assert.That(fixtureContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); } [Test] public void FixtureSetUpCanAccessFixtureId() { Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] public void FixtureSetUpCanAccessFixtureProperties() { Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [Test] public void SetUpCanAccessTestName() { Assert.That(setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName")); } [Test] public void SetUpCanAccessTestFullName() { Assert.That(setupContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName")); } [Test] public void SetUpCanAccessTestId() { Assert.That(setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void SetUpCanAccessTestProperties() { Assert.That(setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName")); } [Test] public void TestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void TestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } #endregion #region CurrentCulture and CurrentUICulture #if !NETCF CultureInfo originalCulture; CultureInfo originalUICulture; [Test] public void FixtureSetUpontextReflectsCurrentCulture() { Assert.That(fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void FixtureSetUpContextReflectsCurrentUICulture() { Assert.That(fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void SetUpContextReflectsCurrentCulture() { Assert.That(setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void SetUpContextReflectsCurrentUICulture() { Assert.That(setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void TestContextReflectsCurrentCulture() { Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void TestContextReflectsCurrentUICulture() { Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void SetAndRestoreCurrentCulture() { var context = new TestExecutionContext(setupContext); try { CultureInfo otherCulture = new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentCulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set"); Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context"); Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored"); Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Culture not in final context"); } [Test] public void SetAndRestoreCurrentUICulture() { var context = new TestExecutionContext(setupContext); try { CultureInfo otherCulture = new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentUICulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set"); Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context"); Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored"); Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context"); } #endif #endregion #region CurrentPrincipal #if !NETCF && !SILVERLIGHT && !PORTABLE [Test] public void FixtureSetUpContextReflectsCurrentPrincipal() { Assert.That(fixtureContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void SetUpContextReflectsCurrentPrincipal() { Assert.That(setupContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void TestContextReflectsCurrentPrincipal() { Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void SetAndRestoreCurrentPrincipal() { var context = new TestExecutionContext(setupContext); try { GenericIdentity identity = new GenericIdentity("foo"); context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set"); Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context"); Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored"); Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context"); } #endif #endregion #region ExecutionStatus [Test] public void ExecutionStatusIsPushedToHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } [Test] public void ExecutionStatusIsPulledFromHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); topContext.ExecutionStatus = TestExecutionStatus.AbortRequested; Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested)); } [Test] public void ExecutionStatusIsPromulgatedAcrossBranches() { var topContext = new TestExecutionContext(); var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); leftContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } #endregion #region Cross-domain Tests #if !SILVERLIGHT && !NETCF && !PORTABLE [Test] public void CanCreateObjectInAppDomain() { AppDomain domain = AppDomain.CreateDomain( "TestCanCreateAppDomain", AppDomain.CurrentDomain.Evidence, AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()), null, false); var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass"); Assert.NotNull(obj); } [Serializable] private class TestClass { } #endif #endregion } #if !PORTABLE && !SILVERLIGHT && !NETCF [TestFixture] public class TextExecutionContextInAppDomain { private RunsInAppDomain _runsInAppDomain; [SetUp] public void SetUp() { var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false); _runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain; Assert.That(_runsInAppDomain, Is.Not.Null); } [Test] [Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")] public void CanWriteToConsoleInAppDomain() { _runsInAppDomain.WriteToConsole(); } [Test] [Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")] public void CanWriteToTestContextInAppDomain() { _runsInAppDomain.WriteToTestContext(); } } internal class RunsInAppDomain : MarshalByRefObject { public void WriteToConsole() { Console.WriteLine("RunsInAppDomain.WriteToConsole"); } public void WriteToTestContext() { TestContext.WriteLine("RunsInAppDomain.WriteToTestContext"); } } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Table; using Orleans.AzureUtils.Utilities; using Orleans.AzureUtils; using Orleans.Reminders.AzureStorage; namespace Orleans.Runtime.ReminderService { internal class ReminderTableEntry : TableEntity { public string GrainReference { get; set; } // Part of RowKey public string ReminderName { get; set; } // Part of RowKey public string ServiceId { get; set; } // Part of PartitionKey public string DeploymentId { get; set; } public string StartAt { get; set; } public string Period { get; set; } public string GrainRefConsistentHash { get; set; } // Part of PartitionKey public static string ConstructRowKey(GrainReference grainRef, string reminderName) { var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName); return AzureStorageUtils.SanitizeTableProperty(key); } public static string ConstructPartitionKey(string serviceId, GrainReference grainRef) { return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode()); } public static string ConstructPartitionKey(string serviceId, uint number) { // IMPORTANT NOTE: Other code using this return data is very sensitive to format changes, // so take great care when making any changes here!!! // this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly // the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now, // when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative // string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number); return AzureStorageUtils.SanitizeTableProperty($"{serviceId}_{number:X8}"); } public override string ToString() { var sb = new StringBuilder(); sb.Append("Reminder ["); sb.Append(" PartitionKey=").Append(PartitionKey); sb.Append(" RowKey=").Append(RowKey); sb.Append(" GrainReference=").Append(GrainReference); sb.Append(" ReminderName=").Append(ReminderName); sb.Append(" Deployment=").Append(DeploymentId); sb.Append(" ServiceId=").Append(ServiceId); sb.Append(" StartAt=").Append(StartAt); sb.Append(" Period=").Append(Period); sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash); sb.Append("]"); return sb.ToString(); } } internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry> { private const string REMINDERS_TABLE_NAME = "OrleansReminders"; public string ServiceId { get; private set; } public string ClusterId { get; private set; } private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout; public static async Task<RemindersTableManager> GetManager(string serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory) { var singleton = new RemindersTableManager(serviceId, clusterId, storageConnectionString, loggerFactory); try { singleton.Logger.Info("Creating RemindersTableManager for service id {0} and clusterId {1}.", serviceId, clusterId); await singleton.InitTableAsync() .WithTimeout(initTimeout); } catch (TimeoutException te) { string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}"; singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_38, errorMsg, te); throw new OrleansException(errorMsg, te); } catch (Exception ex) { string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}"; singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_39, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return singleton; } private RemindersTableManager(string serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory) : base(REMINDERS_TABLE_NAME, storageConnectionString, loggerFactory) { ClusterId = clusterId; ServiceId = serviceId; } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end) { // TODO: Determine whether or not a single query could be used here while avoiding a table scan string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin); string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end); string serviceIdStr = ServiceId; string filterOnServiceIdStr = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, serviceIdStr + '_'), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, serviceIdStr + (char)('_' + 1))); if (begin < end) { string filterBetweenBeginAndEnd = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd)); string query = TableQuery.CombineFilters(filterOnServiceIdStr, TableOperators.And, filterBetweenBeginAndEnd); var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } if (begin == end) { var queryResults = await ReadTableEntriesAndEtagsAsync(filterOnServiceIdStr); return queryResults.ToList(); } // (begin > end) string queryOnSBegin = TableQuery.CombineFilters( filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin)); string queryOnSEnd = TableQuery.CombineFilters( filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd)); var resultsOnSBeginQuery = ReadTableEntriesAndEtagsAsync(queryOnSBegin); var resultsOnSEndQuery = ReadTableEntriesAndEtagsAsync(queryOnSEnd); IEnumerable<Tuple<ReminderTableEntry, string>>[] results = await Task.WhenAll(resultsOnSBeginQuery, resultsOnSEndQuery); return results[0].Concat(results[1]).ToList(); } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef) { var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); string filter = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.GreaterThan, grainRef.ToKeyString() + '-'), TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.LessThanOrEqual, grainRef.ToKeyString() + (char)('-' + 1))); string query = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.Equal, partitionKey), TableOperators.And, filter); var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName) { string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName); return await ReadSingleTableEntryAsync(partitionKey, rowKey); } private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries() { return FindReminderEntries(0, 0); } internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry) { try { return await UpsertTableEntryAsync(reminderEntry); } catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false; } throw; } } internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag) { try { await DeleteTableEntryAsync(reminderEntry, eTag); return true; }catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; } throw; } } internal async Task DeleteTableEntries() { if (ServiceId.Equals(Guid.Empty) && ClusterId == null) { await DeleteTableAsync(); } else { List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries(); // return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed // group by grain hashcode so each query goes to different partition var tasks = new List<Task>(); var groupedByHash = entries .Where(tuple => tuple.Item1.ServiceId.Equals(ServiceId)) .Where(tuple => tuple.Item1.DeploymentId.Equals(ClusterId)) // delete only entries that belong to our DeploymentId. .GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList()); foreach (var entriesPerPartition in groupedByHash.Values) { foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) { tasks.Add(DeleteTableEntriesAsync(batch)); } } await Task.WhenAll(tasks); } } } }
/* * Emulates the Motorola 6800 CPU * Copyright(C) 2015 David Khristepher Santos * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * This code contains work derived from the MAME project https://www.mamedev.org/ * Specifically the Motorla 6800 CPU core https://github.com/mamedev/mame/tree/master/src/devices/cpu/m6800 */ namespace Core6800 { public partial class Cpu6800 { private int IMMBYTE() { var result = ReadMem(State.PC); State.PC++; return result; } private int DIRBYTE() { DIRECT(); return ReadMem(State.EAD); } private void IMM8() { State.EAD = State.PC++; } private void IMM16() { State.EAD = State.PC; State.PC += 2; } private int EXTBYTE() { EXTENDED(); return ReadMem(State.EAD); } private int EXTWORD() { EXTENDED(); return RM16(State.EAD); } private int ONE_MORE_INSN() { int fetchCode = ReadMem(State.PC) & 0xff; State.PC++; InterpretOpCode(fetchCode); return cycles[fetchCode]; } private int SIGNED(int b) { return ((int)((b & 0x80) == 0x80 ? b | 0xffffff00 : b)); } private bool NXORV() { return ((State.CC & 0x08) ^ ((State.CC & 0x02) << 2)) == 0x08; } public int PULLBYTE() { State.S++; return ReadMem(State.S); } public int PULLWORD() { State.S++; int result = ReadMem(State.S) << 8; State.S++; result |= ReadMem(State.S); return result; } public void PUSHBYTE(int b) { WriteMem(State.S, b); --State.S; } public void PUSHWORD(int w) { WriteMem(State.S, w & 0xFF); --State.S; WriteMem(State.S, w >> 8); --State.S; } private void BRANCH(bool f) { var t = IMMBYTE(); if (f) { State.PC += SIGNED(t); } } int[] cycles = new int[] { //0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F 0x05,0x02,0x05,0x05,0x05,0x05,0x02,0x02,0x04,0x04,0x02,0x02,0x02,0x02,0x02,0x02, // 0x00 0x02,0x02,0x05,0x05,0x05,0x05,0x02,0x02,0x05,0x02,0x05,0x02,0x05,0x05,0x05,0x05, // 0x10 0x04,0x05,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04, // 0x20 0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x05,0x05,0x05,0x0A,0x05,0x05,0x09,0x0C, // 0x30 0x02,0x05,0x05,0x02,0x02,0x05,0x02,0x02,0x02,0x02,0x02,0x05,0x02,0x02,0x05,0x02, // 0x40 0x02,0x05,0x05,0x02,0x02,0x05,0x02,0x02,0x02,0x02,0x02,0x05,0x02,0x02,0x05,0x02, // 0x50 0x07,0x05,0x05,0x07,0x07,0x05,0x07,0x07,0x07,0x07,0x07,0x05,0x07,0x07,0x04,0x07, // 0x60 0x06,0x05,0x05,0x06,0x06,0x05,0x06,0x06,0x06,0x06,0x06,0x05,0x06,0x06,0x03,0x06, // 0x70 0x02,0x02,0x02,0x05,0x02,0x02,0x02,0x05,0x02,0x02,0x02,0x02,0x03,0x08,0x03,0x05, // 0x80 0x03,0x03,0x03,0x05,0x03,0x03,0x03,0x04,0x03,0x03,0x03,0x03,0x04,0x05,0x04,0x05, // 0x90 0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x06,0x05,0x05,0x05,0x05,0x06,0x08,0x06,0x07, // 0xA0 0x04,0x04,0x04,0x05,0x04,0x04,0x04,0x05,0x04,0x04,0x04,0x04,0x05,0x09,0x05,0x06, // 0xB0 0x02,0x02,0x02,0x05,0x02,0x02,0x02,0x05,0x02,0x02,0x02,0x02,0x05,0x05,0x03,0x05, // 0xC0 0x03,0x03,0x03,0x05,0x03,0x03,0x03,0x04,0x03,0x03,0x03,0x03,0x05,0x05,0x04,0x05, // 0xD0 0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x06,0x05,0x05,0x05,0x05,0x05,0x05,0x06,0x07, // 0xE0 0x04,0x04,0x04,0x05,0x04,0x04,0x04,0x05,0x04,0x04,0x04,0x04,0x05,0x05,0x05,0x06 // 0xF0 }; int[] flags8i = new int[] /* increment */ { 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x0a,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08 }; int[] flags8d = new int[]/* decrement */ { 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08 }; private void SET_FLAGS8I(int a) { State.CC |= flags8i[(a) & 0xff]; } private void SET_FLAGS8D(int a) { State.CC |= flags8d[(a) & 0xff]; } int RM16(int Addr) { int result = ReadMem(Addr) << 8 | ReadMem(Addr + 1); return result & 0xffff; } void WM16(int Addr, int p) { WriteMem(Addr, p >> 8 & 0xff); WriteMem((Addr + 1) & 0xffff, p & 0xff); } private int DIRWORD() { DIRECT(); return RM16(State.EAD); } private void DIRECT() { State.EAD = IMMBYTE(); } private void EXTENDED() { State.EAD = IMMWORD(); } private void INDEXED() { State.EAD = State.X + ReadMem(State.PC); State.PC++; } private int IMMWORD() { var result = (ReadMem(State.PC) << 8) | ReadMem((State.PC + 1) & 0xffff); State.PC += 2; return result; } private int IDXBYTE() { INDEXED(); return ReadMem(State.EAD); } private int IDXWORD() { INDEXED(); return RM16(State.EAD); } private void SEC() { State.CC |= 0x01; } private void CLC() { State.CC &= 0xfe; } private void SEZ() { State.CC |= 0x04; } private void CLZ() { State.CC &= 0xfb; } private void SEN() { State.CC |= 0x08; } private void CLN() { State.CC &= 0xf7; } private void SEV() { State.CC |= 0x02; } private void CLV() { State.CC &= 0xfd; } private void SEH() { State.CC |= 0x20; } private void CLH() { State.CC &= 0xdf; } private void SEI() { State.CC |= 0x10; } private void CLI() { State.CC &= ~0x10; } private void CLR_HNZVC() { State.CC &= 0xd0; } private void CLR_NZV() { State.CC &= 0xf1; } private void CLR_HNZC() { State.CC &= 0xd2; } private void CLR_NZVC() { State.CC &= 0xf0; } private void CLR_Z() { State.CC &= 0xfb; } private void CLR_NZC() { State.CC &= 0xf2; } private void CLR_ZC() { State.CC &= 0xfa; } private void CLR_C() { State.CC &= 0xfe; } /* macros for State.CC -- State.CC bits affected should be reset before calling */ private void SET_Z(int a) { if ((a & 0xff) == 0) SEZ(); } private void SET_Z8(int a) { SET_Z(a); } private void SET_Z16(int a) { SET_Z(a); } private void SET_N8(int a) { State.CC |= (((a) & 0x80) >> 4); } private void SET_N16(int a) { State.CC |= (((a) & 0x8000) >> 12); } private void SET_H(int a, int b, int r) { State.CC |= ((((a) ^ (b) ^ (r)) & 0x10) << 1); } private void SET_C8(int a) { State.CC |= (((a) & 0x100) >> 8); } private void SET_C16(int a) { State.CC |= (((a) & 0x10000) >> 16); } private void SET_V8(int a, int b, int r) { State.CC |= ((((a) ^ (b) ^ (r) ^ ((r) >> 1)) & 0x80) >> 6); } private void SET_V16(int a, int b, int r) { State.CC |= ((((a) ^ (b) ^ (r) ^ ((r) >> 1)) & 0x8000) >> 14); } private void SET_NZ8(int a) { SET_N8(a); SET_Z8(a); } private void SET_NZ16(int a) { SET_N16(a); SET_Z16(a); } private void SET_FLAGS8(int a, int b, int r) { SET_N8(r); SET_Z8(r); SET_V8(a, b, r); SET_C8(r); } private void SET_FLAGS16(int a, int b, int r) { SET_N16(r); SET_Z16(r); SET_V16(a, b, r); SET_C16(r); } private int ADD8(int a, int b) { return (a + b) & 0xff; } private int SUB8(int a, int b) { return (a - b) & 0xff; } private int INC8(int a) { return ++a & 0xff; } private int DEC8(int a) { return --a & 0xff; } private int INC18(int a) { return ++a & 0xffff; } private int DEC16(int a) { return --a & 0xffff; } } }
// 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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. internal class DecoderNLS : Decoder { // Remember our encoding private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; private int _leftoverBytes; // leftover data from a previous invocation of GetChars (up to 4 bytes) private int _leftoverByteCount; // number of bytes of actual data in _leftoverBytes internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = this._encoding.DecoderFallback; this.Reset(); } public override void Reset() { ClearLeftoverData(); _fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetCharCount(pBytes + index, count, flush); } public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encoding version, no flush by default Debug.Assert(_encoding != null); return _encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); int charCount = chars.Length - charIndex; // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encodings version Debug.Assert(_encoding != null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; // Do conversion Debug.Assert(_encoding != null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); // Our data thingy are now full, we can return } public bool MustFlush => _mustFlush; // Anything left in our decoder? internal virtual bool HasState => _leftoverByteCount != 0; // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { _mustFlush = false; } internal ReadOnlySpan<byte> GetLeftoverData() => MemoryMarshal.AsBytes(new ReadOnlySpan<int>(ref _leftoverBytes, 1)).Slice(0, _leftoverByteCount); internal void SetLeftoverData(ReadOnlySpan<byte> bytes) { bytes.CopyTo(MemoryMarshal.AsBytes(new Span<int>(ref _leftoverBytes, 1))); _leftoverByteCount = bytes.Length; } internal bool HasLeftoverData => _leftoverByteCount != 0; internal void ClearLeftoverData() { _leftoverByteCount = 0; } internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan<byte> bytes, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then get its char count by decoding it. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: charCount = value.Utf16SequenceLength; goto Finish; // successfully transcoded bytes -> chars case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { goto Finish; // consumed some bytes, output 0 chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. See comment in DrainLeftoverDataForGetChars // for more information on why a negative index is provided. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount)) { charCount = _fallbackBuffer!.DrainRemainingDataForGetCharCount(); Debug.Assert(charCount >= 0, "Fallback buffer shouldn't have returned a negative char count."); } Finish: bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; // amount of 'bytes' buffer consumed just now return charCount; } internal int DrainLeftoverDataForGetChars(ReadOnlySpan<byte> bytes, Span<char> chars, out int bytesConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown. Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer."); Debug.Assert(HasLeftoverData, "Caller shouldn't invoke this routine unless there's leftover data in the decoder."); // Copy the existing leftover data plus as many bytes as possible of the new incoming data // into a temporary concated buffer, then transcode it from bytes to chars. Span<byte> combinedBuffer = stackalloc byte[4]; combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charsWritten = 0; bool persistNewCombinedBuffer = false; Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: if (value.TryEncodeToUtf16(chars, out charsWritten)) { goto Finish; // successfully transcoded bytes -> chars } else { goto DestinationTooSmall; } case OperationStatus.NeedMoreData: if (MustFlush) { goto case OperationStatus.InvalidData; // treat as equivalent to bad data } else { persistNewCombinedBuffer = true; goto Finish; // successfully consumed some bytes, output no chars } case OperationStatus.InvalidData: break; default: Debug.Fail("Unexpected OperationStatus return value."); break; } // Couldn't decode the buffer. Fallback the buffer instead. The fallback mechanism relies // on a negative index to convey "the start of the invalid sequence was some number of // bytes back before the current buffer." Since we know the invalid sequence must have // started at the beginning of our leftover byte buffer, we can signal to our caller that // they must backtrack that many bytes to find the real start of the invalid sequence. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: -_leftoverByteCount) && !_fallbackBuffer!.TryDrainRemainingDataForGetChars(chars, out charsWritten)) { goto DestinationTooSmall; } Finish: // Report back the number of bytes (from the new incoming span) we consumed just now. // This calculation is simple: it's the difference between the original leftover byte // count and the number of bytes from the combined buffer we needed to decode the first // scalar value. We need to report this before the call to SetLeftoverData / // ClearLeftoverData because those methods will overwrite the _leftoverByteCount field. bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; if (persistNewCombinedBuffer) { Debug.Assert(combinedBufferBytesConsumed == combinedBuffer.Length, "We should be asked to persist the entire combined buffer."); SetLeftoverData(combinedBuffer); // the buffer still only contains partial data; a future call to Convert will need it } else { ClearLeftoverData(); // the buffer contains no partial data; we'll go down the normal paths } return charsWritten; DestinationTooSmall: // If we got to this point, we're trying to write chars to the output buffer, but we're unable to do // so. Unlike EncoderNLS, this type does not allow partial writes to the output buffer. Since we know // draining leftover data is the first operation performed by any DecoderNLS API, there was no // opportunity for any code before us to make forward progress, so we must fail immediately. _encoding.ThrowCharsOverflow(this, nothingDecoded: true); throw null!; // will never reach this point } /// <summary> /// Given a byte buffer <paramref name="dest"/>, concatenates as much of <paramref name="srcLeft"/> followed /// by <paramref name="srcRight"/> into it as will fit, then returns the total number of bytes copied. /// </summary> private static int ConcatInto(ReadOnlySpan<byte> srcLeft, ReadOnlySpan<byte> srcRight, Span<byte> dest) { int total = 0; for (int i = 0; i < srcLeft.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcLeft[i]; } } for (int i = 0; i < srcRight.Length; i++) { if ((uint)total >= (uint)dest.Length) { goto Finish; } else { dest[total++] = srcRight[i]; } } Finish: return total; } } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Internal; using Orleans.Runtime; using Orleans.Runtime.Scheduler; using Orleans.Runtime.TestHooks; using Orleans.Statistics; using TestExtensions; using UnitTests.Grains; using UnitTests.TesterInternal; using Xunit; using Xunit.Abstractions; namespace UnitTests.SchedulerTests { public class OrleansTaskSchedulerAdvancedTests_Set2 : IDisposable { private static readonly object Lockable = new object(); private static readonly int WaitFactor = Debugger.IsAttached ? 100 : 1; private readonly ITestOutputHelper output; private readonly UnitTestSchedulingContext context; private readonly IHostEnvironmentStatistics performanceMetrics; private readonly ILoggerFactory loggerFactory; public OrleansTaskSchedulerAdvancedTests_Set2(ITestOutputHelper output) { this.output = output; this.loggerFactory = OrleansTaskSchedulerBasicTests.InitSchedulerLogging(); this.context = new UnitTestSchedulingContext(); this.performanceMetrics = new TestHooksHostEnvironmentStatistics(); } public void Dispose() { this.loggerFactory.Dispose(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_SimpleFifoTest() { // This is not a great test because there's a 50/50 shot that it will work even if the scheduling // is completely and thoroughly broken and both closures are executed "simultaneously" using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; int n = 0; // ReSharper disable AccessToModifiedClosure Task task1 = new Task(() => { Thread.Sleep(1000); n = n + 5; }); Task task2 = new Task(() => { n = n * 3; }); // ReSharper restore AccessToModifiedClosure task1.Start(scheduler); task2.Start(scheduler); // Pause to let things run Thread.Sleep(1500); // N should be 15, because the two tasks should execute in order Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(15, n); // "Work items executed out of order" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_NewTask_ContinueWith_Wrapped() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; Task<Task> wrapped = new Task<Task>(() => { this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Task t0 = new Task(() => { this.output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #1" }); Task t1 = t0.ContinueWith(task => { Assert.False(task.IsFaulted, "Task #1 Faulted=" + task.Exception); this.output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #2" }); t0.Start(scheduler); return t1; }); wrapped.Start(scheduler); bool ok = wrapped.Unwrap().Wait(TimeSpan.FromSeconds(2)); Assert.True(ok, "Finished OK"); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_SubTaskExecutionSequencing() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; LogContext("Main-task " + Task.CurrentId); int n = 0; Action action = () => { LogContext("WorkItem-task " + Task.CurrentId); for (int i = 0; i < 10; i++) { int id = -1; Task.Factory.StartNew(() => { id = Task.CurrentId.HasValue ? (int)Task.CurrentId : -1; // ReSharper disable AccessToModifiedClosure LogContext("Sub-task " + id + " n=" + n); int k = n; this.output.WriteLine("Sub-task " + id + " sleeping"); Thread.Sleep(100); this.output.WriteLine("Sub-task " + id + " awake"); n = k + 1; // ReSharper restore AccessToModifiedClosure }) .ContinueWith(tsk => { LogContext("Sub-task " + id + "-ContinueWith"); this.output.WriteLine("Sub-task " + id + " Done"); }); } }; Task t = new Task(action); t.Start(scheduler); // Pause to let things run this.output.WriteLine("Main-task sleeping"); Thread.Sleep(TimeSpan.FromSeconds(2)); this.output.WriteLine("Main-task awake"); // N should be 10, because all tasks should execute serially Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(10, n); // "Work items executed concurrently" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_ContinueWith_1_Test() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; var result = new TaskCompletionSource<bool>(); int n = 0; Task wrapper = new Task(() => { // ReSharper disable AccessToModifiedClosure Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(1000); n = n + 3; this.output.WriteLine("===> 1b"); }); Task task2 = task1.ContinueWith(task => { n = n * 5; this.output.WriteLine("===> 2"); }); Task task3 = task2.ContinueWith(task => { n = n / 5; this.output.WriteLine("===> 3"); }); Task task4 = task3.ContinueWith(task => { n = n - 2; this.output.WriteLine("===> 4"); result.SetResult(true); }); // ReSharper restore AccessToModifiedClosure task4.ContinueWith(task => { this.output.WriteLine("Done Faulted={0}", task.IsFaulted); Assert.False(task.IsFaulted, "Faulted with Exception=" + task.Exception); }); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(2); try { await result.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(1, n); // "Work items executed out of order" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current=" + TaskScheduler.Current pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.True(task1.IsCompleted || task2.IsCompleted, "Task-1 Status = " + task1.Status + " Task-2 Status = " + task2.Status); pause2.Set(); task2.Ignore(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny_Timeout() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.NotNull(join); await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status); pause1.Set(); task1.Ignore(); pause2.Set(); task2.Ignore(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny_Busy_Timeout() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; var pause1 = new TaskCompletionSource<bool>(); var pause2 = new TaskCompletionSource<bool>(); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); int num1 = 1; while (!pause1.Task.Result) // Infinite busy loop { num1 = ThreadSafeRandom.Next(); } this.output.WriteLine("Task-1 Done"); return num1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); int num2 = 2; while (!pause2.Task.Result) // Infinite busy loop { num2 = ThreadSafeRandom.Next(); } this.output.WriteLine("Task-2 Done"); return num2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Run() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task.Run(() => { this.output.WriteLine("Task-1 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task.Run(() => { this.output.WriteLine("Task-2 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAll(task1, task2).ContinueWith(t => { this.output.WriteLine("Join Started"); if (t.IsFaulted) throw t.Exception; Assert.Equal(scheduler, TaskScheduler.Current); this.output.WriteLine("Join Done"); }); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); pause2.Set(); Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join); Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1); Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Run_Delay() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task.Run(() => { this.output.WriteLine("Task-1 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); Task.Delay(1); Assert.NotEqual(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task.Run(() => { this.output.WriteLine("Task-2 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); Task.Delay(1); Assert.NotEqual(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAll(task1, task2).ContinueWith(t => { this.output.WriteLine("Join Started"); if (t.IsFaulted) throw t.Exception; Assert.Equal(scheduler, TaskScheduler.Current); this.output.WriteLine("Join Done"); }); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); pause2.Set(); Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join); Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1); Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Delay() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; Task wrapper = new Task(async () => { Assert.Equal(scheduler, TaskScheduler.Current); await DoDelay(1); Assert.Equal(scheduler, TaskScheduler.Current); await DoDelay(2); Assert.Equal(scheduler, TaskScheduler.Current); }); wrapper.Start(scheduler); await wrapper; } private async Task DoDelay(int i) { try { this.output.WriteLine("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current); await Task.Delay(1); this.output.WriteLine("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current); } catch (ObjectDisposedException) { // Ignore any problems with ObjectDisposedException if console output stream has already been closed } } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Turn_Execution_Order_Loop() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; const int NumChains = 100; const int ChainLength = 3; // Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn? // For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew. // You test that no CW/StartNew runs until the main turn is fully done. And run in stress. var resultHandles = new TaskCompletionSource<bool>[NumChains]; Task[] taskChains = new Task[NumChains]; Task[] taskChainEnds = new Task[NumChains]; bool[] executingChain = new bool[NumChains]; int[] stageComplete = new int[NumChains]; int executingGlobal = -1; for (int i = 0; i < NumChains; i++) { int chainNum = i; // Capture int sleepTime = ThreadSafeRandom.Next(100); resultHandles[i] = new TaskCompletionSource<bool>(); taskChains[i] = new Task(() => { const int taskNum = 0; try { Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum); executingGlobal = chainNum; executingChain[chainNum] = true; Thread.Sleep(sleepTime); } finally { stageComplete[chainNum] = taskNum; executingChain[chainNum] = false; executingGlobal = -1; } }); Task task = taskChains[i]; for (int j = 1; j < ChainLength; j++) { int taskNum = j; // Capture task = task.ContinueWith(t => { if (t.IsFaulted) throw t.Exception; this.output.WriteLine("Inside Chain {0} Task {1}", chainNum, taskNum); try { Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum); Assert.Equal(taskNum - 1, stageComplete[chainNum]); // "Detected unexpected execution stage on chain " + chainNum + " Task " + taskNum executingGlobal = chainNum; executingChain[chainNum] = true; Thread.Sleep(sleepTime); } finally { stageComplete[chainNum] = taskNum; executingChain[chainNum] = false; executingGlobal = -1; } }, scheduler); } taskChainEnds[chainNum] = task.ContinueWith(t => { if (t.IsFaulted) throw t.Exception; this.output.WriteLine("Inside Chain {0} Final Task", chainNum); resultHandles[chainNum].SetResult(true); }, scheduler); } for (int i = 0; i < NumChains; i++) { taskChains[i].Start(scheduler); } for (int i = 0; i < NumChains; i++) { TimeSpan waitCheckTime = TimeSpan.FromMilliseconds(150 * ChainLength * NumChains * WaitFactor); try { await resultHandles[i].Task.WithTimeout(waitCheckTime); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + waitCheckTime); } bool ok = resultHandles[i].Task.Result; try { // since resultHandle being complete doesn't directly imply that the final chain was completed (there's a chance for a race condition), give a small chance for it to complete. await taskChainEnds[i].WithTimeout(TimeSpan.FromMilliseconds(10)); } catch (TimeoutException) { Assert.True(false, $"Task chain end {i} should complete very shortly after after its resultHandle"); } Assert.True(taskChainEnds[i].IsCompleted, "Task chain " + i + " should be completed"); Assert.False(taskChainEnds[i].IsFaulted, "Task chain " + i + " should not be Faulted: " + taskChainEnds[i].Exception); Assert.Equal(ChainLength - 1, stageComplete[i]); // "Task chain " + i + " should have completed all stages" Assert.True(ok, "Successfully waited for ResultHandle for Task chain " + i); } } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Test1() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; await Run_ActivationSched_Test1(scheduler, false); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Test1_Bounce() { using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, loggerFactory); TaskScheduler scheduler = workItemGroup.TaskScheduler; await Run_ActivationSched_Test1(scheduler, true); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task OrleansSched_Test1() { UnitTestSchedulingContext context = new UnitTestSchedulingContext(); using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, this.loggerFactory); ActivationTaskScheduler scheduler = workItemGroup.TaskScheduler; await Run_ActivationSched_Test1(scheduler, false); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task OrleansSched_Test1_Bounce() { UnitTestSchedulingContext context = new UnitTestSchedulingContext(); using var workItemGroup = SchedulingHelper.CreateWorkItemGroupForTesting(context, this.loggerFactory); ActivationTaskScheduler scheduler = workItemGroup.TaskScheduler; await Run_ActivationSched_Test1(scheduler, true); } internal async Task Run_ActivationSched_Test1(TaskScheduler scheduler, bool bounceToThreadPool) { var grainId = LegacyGrainId.GetGrainId(0, Guid.NewGuid()); var silo = new MockSiloDetails { SiloAddress = SiloAddressUtils.NewLocalSiloAddress(23) }; var grain = new NonReentrentStressGrainWithoutState(); await Task.Factory.StartNew(() => grain.OnActivateAsync(), CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap(); Task wrapped = null; var wrapperDone = new TaskCompletionSource<bool>(); var wrappedDone = new TaskCompletionSource<bool>(); Task<Task> wrapper = new Task<Task>(() => { this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Task t1 = grain.Test1(); Action wrappedDoneAction = () => { wrappedDone.SetResult(true); }; if (bounceToThreadPool) { wrapped = t1.ContinueWith(_ => wrappedDoneAction(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } else { wrapped = t1.ContinueWith(_ => wrappedDoneAction()); } wrapperDone.SetResult(true); return wrapped; }); wrapper.Start(scheduler); await wrapper; var timeoutLimit = TimeSpan.FromSeconds(1); try { await wrapperDone.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } bool done = wrapperDone.Task.Result; Assert.True(done, "Wrapper Task finished"); Assert.True(wrapper.IsCompleted, "Wrapper Task completed"); //done = wrapped.Wait(TimeSpan.FromSeconds(12)); //Assert.True(done, "Wrapped Task not timeout"); await wrapped; try { await wrappedDone.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } done = wrappedDone.Task.Result; Assert.True(done, "Wrapped Task should be finished"); Assert.True(wrapped.IsCompleted, "Wrapped Task completed"); } private void LogContext(string what) { lock (Lockable) { this.output.WriteLine( "{0}\n" + " TaskScheduler.Current={1}\n" + " Task.Factory.Scheduler={2}\n" + " SynchronizationContext.Current={3}", what, (TaskScheduler.Current == null ? "null" : TaskScheduler.Current.ToString()), (Task.Factory.Scheduler == null ? "null" : Task.Factory.Scheduler.ToString()), (SynchronizationContext.Current == null ? "null" : SynchronizationContext.Current.ToString()) ); //var st = new StackTrace(); //output.WriteLine(st.ToString()); } } private class MockSiloDetails : ILocalSiloDetails { public string DnsHostName { get; } public SiloAddress SiloAddress { get; set; } public SiloAddress GatewayAddress { get; } public string Name { get; set; } = Guid.NewGuid().ToString(); public string ClusterId { get; } } } }
// // SoundMenuService.cs // // Authors: // Bertrand Lorentz <bertrand.lorentz@gmail.com> // // Copyright (C) 2010 Bertrand Lorentz // // 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 Mono.Addins; using Mono.Unix; using Gtk; using Notifications; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.Configuration; using Banshee.Gui; using Banshee.IO; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Preferences; namespace Banshee.SoundMenu { public class SoundMenuService : IExtensionService { private bool? actions_supported; private ArtworkManager artwork_manager_service; private Notification current_nf; private TrackInfo current_track; private GtkElementsService elements_service; private InterfaceActionService interface_action_service; private string notify_last_artist; private string notify_last_title; private uint ui_manager_id; private SoundMenuProxy sound_menu; private const int icon_size = 42; public SoundMenuService () { } void IExtensionService.Initialize () { elements_service = ServiceManager.Get<GtkElementsService> (); interface_action_service = ServiceManager.Get<InterfaceActionService> (); var notif_addin = AddinManager.Registry.GetAddin("Banshee.NotificationArea"); var ind_addin = AddinManager.Registry.GetAddin("Banshee.AppIndicator"); if (notif_addin != null && notif_addin.Enabled) { Log.Debug("NotificationArea conflicts with SoundMenu, disabling NotificationArea"); notif_addin.Enabled = false; } else if (ind_addin != null && ind_addin.Enabled) { Log.Debug("AppIndicator conflicts with SoundMenu, disabling AppIndicator"); ind_addin.Enabled = false; } AddinManager.AddinLoaded += OnAddinLoaded; if (!ServiceStartup ()) { ServiceManager.ServiceStarted += OnServiceStarted; } } private void OnServiceStarted (ServiceStartedArgs args) { if (args.Service is Banshee.Gui.InterfaceActionService) { interface_action_service = (InterfaceActionService)args.Service; } else if (args.Service is GtkElementsService) { elements_service = (GtkElementsService)args.Service; } ServiceStartup (); } private bool ServiceStartup () { if (elements_service == null || interface_action_service == null) { return false; } interface_action_service.GlobalActions.Add (new ActionEntry [] { new ActionEntry ("CloseAction", Stock.Close, Catalog.GetString ("_Close"), "<Control>W", Catalog.GetString ("Close"), CloseWindow) }); ui_manager_id = interface_action_service.UIManager.AddUiFromString (@" <ui> <menubar name=""MainMenu""> <menu name=""MediaMenu"" action=""MediaMenuAction""> <placeholder name=""ClosePlaceholder""> <menuitem name=""Close"" action=""CloseAction""/> </placeholder> </menu> </menubar> </ui> "); interface_action_service.GlobalActions.UpdateAction ("QuitAction", false); InstallPreferences (); sound_menu = new SoundMenuProxy (); if (Enabled) { sound_menu.Register (true); } ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.EndOfStream | PlayerEvent.TrackInfoUpdated | PlayerEvent.StateChange); artwork_manager_service = ServiceManager.Get<ArtworkManager> (); artwork_manager_service.AddCachedSize (icon_size); RegisterCloseHandler (); ServiceManager.ServiceStarted -= OnServiceStarted; return true; } public void Dispose () { if (current_nf != null) { try { current_nf.Close (); } catch {} } UninstallPreferences (); ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); elements_service.PrimaryWindowClose = null; interface_action_service.UIManager.RemoveUi (ui_manager_id); Gtk.Action close_action = interface_action_service.GlobalActions["CloseAction"]; if (close_action != null) { interface_action_service.GlobalActions.Remove (close_action); } interface_action_service.GlobalActions.UpdateAction ("QuitAction", true); AddinManager.AddinLoaded -= OnAddinLoaded; sound_menu = null; elements_service = null; interface_action_service = null; } void OnAddinLoaded (object sender, AddinEventArgs args) { if (args.AddinId == "Banshee.NotificationArea" || args.AddinId == "Banshee.AppIndicator") { Log.Debug("SoundMenu conflicts with " + args.AddinId + ", disabling SoundMenu"); AddinManager.Registry.GetAddin("Banshee.SoundMenu").Enabled = false; } } #region Notifications private bool ActionsSupported { get { if (!actions_supported.HasValue) { actions_supported = Notifications.Global.Capabilities != null && Array.IndexOf (Notifications.Global.Capabilities, "actions") > -1; } return actions_supported.Value; } } private bool OnPrimaryWindowClose () { CloseWindow (null, null); return true; } private void CloseWindow (object o, EventArgs args) { if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing) { elements_service.PrimaryWindow.Visible = false; } else { Banshee.ServiceStack.Application.Shutdown (); } } private void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.StartOfStream: case PlayerEvent.TrackInfoUpdated: current_track = ServiceManager.PlayerEngine.CurrentTrack; ShowTrackNotification (); break; case PlayerEvent.EndOfStream: current_track = null; break; } } private void OnSongSkipped (object o, ActionArgs args) { if (args.Action == "skip-song") { ServiceManager.PlaybackController.Next (); } } private string GetByFrom (string artist, string display_artist, string album, string display_album) { 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 Artist Name and // Album Title, respectively; // e.g. 'by Parkway Drive from Killing with a Smile' markup = String.Format (Catalog.GetString ("by '{0}' from '{1}'"), display_artist, display_album); } else if (has_album) { // Translators: {0} is for Album Title; // e.g. 'from Killing with a Smile' markup = String.Format (Catalog.GetString ("from '{0}'"), display_album); } else { // Translators: {0} is for Artist Name; // e.g. 'by Parkway Drive' markup = String.Format(Catalog.GetString ("by '{0}'"), display_artist); } return markup; } private void ShowTrackNotification () { // This has to happen before the next if, otherwise the last_* members aren't set correctly. if (current_track == null || (notify_last_title == current_track.DisplayTrackTitle && notify_last_artist == current_track.DisplayArtistName)) { return; } notify_last_title = current_track.DisplayTrackTitle; notify_last_artist = current_track.DisplayArtistName; if (!ShowNotificationsSchema.Get ()) { return; } foreach (var window in elements_service.ContentWindows) { if (window.HasToplevelFocus) { return; } } bool is_notification_daemon = false; try { var name = Notifications.Global.ServerInformation.Name; is_notification_daemon = name == "notification-daemon" || name == "Notification Daemon"; } catch { // This will be reached if no notification daemon is running return; } string message = GetByFrom ( current_track.ArtistName, current_track.DisplayArtistName, current_track.AlbumTitle, current_track.DisplayAlbumTitle); string image = null; image = is_notification_daemon ? CoverArtSpec.GetPathForSize (current_track.ArtworkId, icon_size) : CoverArtSpec.GetPath (current_track.ArtworkId); if (!File.Exists (new SafeUri(image))) { if (artwork_manager_service != null) { // artwork does not exist, try looking up the pixbuf to trigger scaling or conversion Gdk.Pixbuf tmp_pixbuf = is_notification_daemon ? artwork_manager_service.LookupScalePixbuf (current_track.ArtworkId, icon_size) : artwork_manager_service.LookupPixbuf (current_track.ArtworkId); if (tmp_pixbuf == null) { image = "audio-x-generic"; } else { tmp_pixbuf.Dispose (); } } } try { if (current_nf == null) { current_nf = new Notification (current_track.DisplayTrackTitle, message, image); } else { current_nf.Summary = current_track.DisplayTrackTitle; current_nf.Body = message; current_nf.IconName = image; } current_nf.Urgency = Urgency.Low; current_nf.Timeout = 4500; if (!current_track.IsLive && ActionsSupported && interface_action_service.PlaybackActions["NextAction"].Sensitive) { current_nf.AddAction ("skip-song", Catalog.GetString ("Skip this item"), OnSongSkipped); } current_nf.Show (); } catch (Exception e) { Log.Warning ("Cannot show notification", e.Message, false); } } private void RegisterCloseHandler () { if (elements_service.PrimaryWindowClose == null) { elements_service.PrimaryWindowClose = OnPrimaryWindowClose; } } private void UnregisterCloseHandler () { if (elements_service.PrimaryWindowClose != null) { elements_service.PrimaryWindowClose = null; } } #endregion #region Preferences private PreferenceBase enabled_pref; private void InstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } enabled_pref = service["general"]["misc"].Add ( new SchemaPreference<bool> (EnabledSchema, Catalog.GetString ("_Show Banshee in the sound menu"), Catalog.GetString ("Control Banshee through the sound menu"), delegate { Enabled = EnabledSchema.Get (); }) ); } private void UninstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } service["general"]["misc"].Remove (enabled_pref); } public bool Enabled { get { return EnabledSchema.Get (); } set { if (value) { sound_menu.Register (false); RegisterCloseHandler (); } else { sound_menu.Unregister (); UnregisterCloseHandler (); } } } private static readonly SchemaEntry<bool> EnabledSchema = new SchemaEntry<bool> ( "plugins.soundmenu", "enabled", true, "Show Banshee in the sound menu", "Show Banshee in the sound menu" ); public static readonly SchemaEntry<bool> ShowNotificationsSchema = new SchemaEntry<bool> ( "plugins.soundmenu", "show_notifications", true, "Show notifications", "Show information notifications when item starts playing" ); #endregion string IService.ServiceName { get { return "SoundMenuService"; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Drawing; using System.IO; using System.Linq; using Newtonsoft.Json; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.API.Requests; using osu.Game.Tournament.IPC; using osu.Game.Tournament.Models; using osu.Game.Users; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Tournament { [Cached(typeof(TournamentGameBase))] public abstract class TournamentGameBase : OsuGameBase { private const string bracket_filename = "bracket.json"; private LadderInfo ladder; private Storage storage; private TournamentStorage tournamentStorage; private DependencyContainer dependencies; private Bindable<Size> windowSize; private FileBasedIPC ipc; private Drawable heightWarning; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { return dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); } [BackgroundDependencyLoader] private void load(Storage storage, FrameworkConfigManager frameworkConfig) { Resources.AddStore(new DllResourceStore(typeof(TournamentGameBase).Assembly)); dependencies.CacheAs(tournamentStorage = new TournamentStorage(storage)); Textures.AddStore(new TextureLoaderStore(tournamentStorage)); this.storage = storage; windowSize = frameworkConfig.GetBindable<Size>(FrameworkSetting.WindowedSize); windowSize.BindValueChanged(size => ScheduleAfterChildren(() => { var minWidth = (int)(size.NewValue.Height / 9f * 16 + 400); heightWarning.Alpha = size.NewValue.Width < minWidth ? 1 : 0; }), true); readBracket(); ladder.CurrentMatch.Value = ladder.Matches.FirstOrDefault(p => p.Current.Value); dependencies.CacheAs<MatchIPCInfo>(ipc = new FileBasedIPC()); Add(ipc); AddRange(new[] { new Container { CornerRadius = 10, Depth = float.MinValue, Position = new Vector2(5), Masking = true, AutoSizeAxes = Axes.Both, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, Children = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new TourneyButton { Text = "Save Changes", Width = 140, Height = 50, Padding = new MarginPadding { Top = 10, Left = 10, }, Margin = new MarginPadding { Right = 10, Bottom = 10, }, Action = SaveChanges, }, } }, heightWarning = new Container { Masking = true, CornerRadius = 5, Depth = float.MinValue, Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.Red, RelativeSizeAxes = Axes.Both, }, new TournamentSpriteText { Text = "Please make the window wider", Font = OsuFont.Torus.With(weight: FontWeight.Bold), Colour = Color4.White, Padding = new MarginPadding(20) } } }, }); } private void readBracket() { if (storage.Exists(bracket_filename)) { using (Stream stream = storage.GetStream(bracket_filename, FileAccess.Read, FileMode.Open)) using (var sr = new StreamReader(stream)) ladder = JsonConvert.DeserializeObject<LadderInfo>(sr.ReadToEnd()); } if (ladder == null) ladder = new LadderInfo(); if (ladder.Ruleset.Value == null) ladder.Ruleset.Value = RulesetStore.AvailableRulesets.First(); Ruleset.BindTo(ladder.Ruleset); dependencies.Cache(ladder); bool addedInfo = false; // assign teams foreach (var match in ladder.Matches) { match.Team1.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == match.Team1Acronym); match.Team2.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == match.Team2Acronym); foreach (var conditional in match.ConditionalMatches) { conditional.Team1.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == conditional.Team1Acronym); conditional.Team2.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == conditional.Team2Acronym); conditional.Round.Value = match.Round.Value; } } // assign progressions foreach (var pair in ladder.Progressions) { var src = ladder.Matches.FirstOrDefault(p => p.ID == pair.SourceID); var dest = ladder.Matches.FirstOrDefault(p => p.ID == pair.TargetID); if (src == null) continue; if (dest != null) { if (pair.Losers) src.LosersProgression.Value = dest; else src.Progression.Value = dest; } } // link matches to rounds foreach (var round in ladder.Rounds) { foreach (var id in round.Matches) { var found = ladder.Matches.FirstOrDefault(p => p.ID == id); if (found != null) { found.Round.Value = round; if (round.StartDate.Value > found.Date.Value) found.Date.Value = round.StartDate.Value; } } } addedInfo |= addPlayers(); addedInfo |= addBeatmaps(); if (addedInfo) SaveChanges(); } /// <summary> /// Add missing player info based on user IDs. /// </summary> /// <returns></returns> private bool addPlayers() { bool addedInfo = false; foreach (var t in ladder.Teams) { foreach (var p in t.Players) { if (string.IsNullOrEmpty(p.Username) || p.Statistics == null) { PopulateUser(p); addedInfo = true; } } } return addedInfo; } /// <summary> /// Add missing beatmap info based on beatmap IDs /// </summary> private bool addBeatmaps() { bool addedInfo = false; foreach (var r in ladder.Rounds) { foreach (var b in r.Beatmaps.ToList()) { if (b.BeatmapInfo != null) continue; if (b.ID > 0) { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = b.ID }); API.Perform(req); b.BeatmapInfo = req.Result?.ToBeatmap(RulesetStore); addedInfo = true; } if (b.BeatmapInfo == null) // if online population couldn't be performed, ensure we don't leave a null value behind r.Beatmaps.Remove(b); } } foreach (var t in ladder.Teams) { foreach (var s in t.SeedingResults) { foreach (var b in s.Beatmaps) { if (b.BeatmapInfo == null && b.ID > 0) { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = b.ID }); req.Perform(API); b.BeatmapInfo = req.Result?.ToBeatmap(RulesetStore); addedInfo = true; } } } } return addedInfo; } public void PopulateUser(User user, Action success = null, Action failure = null) { var req = new GetUserRequest(user.Id, Ruleset.Value); req.Success += res => { user.Username = res.Username; user.Statistics = res.Statistics; user.Country = res.Country; user.Cover = res.Cover; success?.Invoke(); }; req.Failure += _ => { user.Id = 1; failure?.Invoke(); }; API.Queue(req); } protected override void LoadComplete() { MenuCursorContainer.Cursor.AlwaysPresent = true; // required for tooltip display MenuCursorContainer.Cursor.Alpha = 0; base.LoadComplete(); } protected virtual void SaveChanges() { foreach (var r in ladder.Rounds) r.Matches = ladder.Matches.Where(p => p.Round.Value == r).Select(p => p.ID).ToList(); ladder.Progressions = ladder.Matches.Where(p => p.Progression.Value != null).Select(p => new TournamentProgression(p.ID, p.Progression.Value.ID)).Concat( ladder.Matches.Where(p => p.LosersProgression.Value != null).Select(p => new TournamentProgression(p.ID, p.LosersProgression.Value.ID, true))) .ToList(); using (var stream = storage.GetStream(bracket_filename, FileAccess.Write, FileMode.Create)) using (var sw = new StreamWriter(stream)) { sw.Write(JsonConvert.SerializeObject(ladder, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, })); } } protected override UserInputManager CreateUserInputManager() => new TournamentInputManager(); private class TournamentInputManager : UserInputManager { protected override MouseButtonEventManager CreateButtonEventManagerFor(MouseButton button) { switch (button) { case MouseButton.Right: return new RightMouseManager(button); } return base.CreateButtonEventManagerFor(button); } private class RightMouseManager : MouseButtonEventManager { public RightMouseManager(MouseButton button) : base(button) { } public override bool EnableDrag => true; // allow right-mouse dragging for absolute scroll in scroll containers. public override bool EnableClick => true; public override bool ChangeFocusOnClick => false; } } } }
using System; using System.Threading; namespace Lucene.Net.Search { using Lucene.Net.Support; /* * 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 IndexWriter = Lucene.Net.Index.IndexWriter; using TrackingIndexWriter = Lucene.Net.Index.TrackingIndexWriter; /// <summary> /// Utility class that runs a thread to manage periodicc /// reopens of a <seealso cref="ReferenceManager"/>, with methods to wait for a specific /// index changes to become visible. To use this class you /// must first wrap your <seealso cref="IndexWriter"/> with a {@link /// TrackingIndexWriter} and always use it to make changes /// to the index, saving the returned generation. Then, /// when a given search request needs to see a specific /// index change, call the {#waitForGeneration} to wait for /// that change to be visible. Note that this will only /// scale well if most searches do not need to wait for a /// specific index generation. /// /// @lucene.experimental /// </summary> public class ControlledRealTimeReopenThread<T> : ThreadClass, IDisposable where T : class { private bool InstanceFieldsInitialized = false; /*private void InitializeInstanceFields() { ReopenCond = ReopenLock.NewCondition(); }*/ private readonly ReferenceManager<T> Manager; private readonly long TargetMaxStaleNS; private readonly long TargetMinStaleNS; private readonly TrackingIndexWriter Writer; private volatile bool Finish; private long WaitingGen; private long SearchingGen; private long RefreshStartGen; private readonly ReentrantLock ReopenLock = new ReentrantLock(); private ManualResetEvent ReopenCond = new ManualResetEvent(false); /// <summary> /// Create ControlledRealTimeReopenThread, to periodically /// reopen the a <seealso cref="ReferenceManager"/>. /// </summary> /// <param name="targetMaxStaleSec"> Maximum time until a new /// reader must be opened; this sets the upper bound /// on how slowly reopens may occur, when no /// caller is waiting for a specific generation to /// become visible. /// </param> /// <param name="targetMinStaleSec"> Mininum time until a new /// reader can be opened; this sets the lower bound /// on how quickly reopens may occur, when a caller /// is waiting for a specific generation to /// become visible. </param> public ControlledRealTimeReopenThread(TrackingIndexWriter writer, ReferenceManager<T> manager, double targetMaxStaleSec, double targetMinStaleSec) { /*if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; }*/ if (targetMaxStaleSec < targetMinStaleSec) { throw new System.ArgumentException("targetMaxScaleSec (= " + targetMaxStaleSec + ") < targetMinStaleSec (=" + targetMinStaleSec + ")"); } this.Writer = writer; this.Manager = manager; this.TargetMaxStaleNS = (long)(1000000000 * targetMaxStaleSec); this.TargetMinStaleNS = (long)(1000000000 * targetMinStaleSec); manager.AddListener(new HandleRefresh(this)); } private class HandleRefresh : ReferenceManager.RefreshListener { private readonly ControlledRealTimeReopenThread<T> OuterInstance; public HandleRefresh(ControlledRealTimeReopenThread<T> outerInstance) { this.OuterInstance = outerInstance; } public void BeforeRefresh() { } public void AfterRefresh(bool didRefresh) { OuterInstance.RefreshDone(); } } private void RefreshDone() { lock (this) { SearchingGen = RefreshStartGen; Monitor.PulseAll(this); } } public void Dispose() { lock (this) { //System.out.println("NRT: set finish"); Finish = true; // So thread wakes up and notices it should finish: ReopenLock.Lock(); try { ReopenCond.Set(); } finally { ReopenLock.Unlock(); } try { Join(); } catch (ThreadInterruptedException ie) { throw new ThreadInterruptedException("Thread Interrupted Exception", ie); } // Max it out so any waiting search threads will return: SearchingGen = long.MaxValue; Monitor.PulseAll(this); } } /// <summary> /// Waits for the target generation to become visible in /// the searcher. /// If the current searcher is older than the /// target generation, this method will block /// until the searcher is reopened, by another via /// <seealso cref="ReferenceManager#maybeRefresh"/> or until the <seealso cref="ReferenceManager"/> is closed. /// </summary> /// <param name="targetGen"> the generation to wait for </param> public virtual void WaitForGeneration(long targetGen) { WaitForGeneration(targetGen, -1); } /// <summary> /// Waits for the target generation to become visible in /// the searcher, up to a maximum specified milli-seconds. /// If the current searcher is older than the target /// generation, this method will block until the /// searcher has been reopened by another thread via /// <seealso cref="ReferenceManager#maybeRefresh"/>, the given waiting time has elapsed, or until /// the <seealso cref="ReferenceManager"/> is closed. /// <p> /// NOTE: if the waiting time elapses before the requested target generation is /// available the current <seealso cref="SearcherManager"/> is returned instead. /// </summary> /// <param name="targetGen"> /// the generation to wait for </param> /// <param name="maxMS"> /// maximum milliseconds to wait, or -1 to wait indefinitely </param> /// <returns> true if the targetGeneration is now available, /// or false if maxMS wait time was exceeded </returns> public virtual bool WaitForGeneration(long targetGen, int maxMS) { lock (this) { long curGen = Writer.Generation; if (targetGen > curGen) { throw new System.ArgumentException("targetGen=" + targetGen + " was never returned by the ReferenceManager instance (current gen=" + curGen + ")"); } if (targetGen > SearchingGen) { // Notify the reopen thread that the waitingGen has // changed, so it may wake up and realize it should // not sleep for much or any longer before reopening: ReopenLock.Lock(); // Need to find waitingGen inside lock as its used to determine // stale time WaitingGen = Math.Max(WaitingGen, targetGen); try { ReopenCond.Set(); } finally { ReopenLock.Unlock(); } long startMS = Environment.TickCount;//System.nanoTime() / 1000000; while (targetGen > SearchingGen) { if (maxMS < 0) { Monitor.Wait(this); } else { long msLeft = (startMS + maxMS) - Environment.TickCount;//(System.nanoTime()) / 1000000; if (msLeft <= 0) { return false; } else { Monitor.Wait(this, TimeSpan.FromMilliseconds(msLeft)); } } } } return true; } } public override void Run() { // TODO: maybe use private thread ticktock timer, in // case clock shift messes up nanoTime? long lastReopenStartNS = DateTime.Now.Ticks * 100; //System.out.println("reopen: start"); while (!Finish) { // TODO: try to guestimate how long reopen might // take based on past data? // Loop until we've waiting long enough before the // next reopen: while (!Finish) { // Need lock before finding out if has waiting ReopenLock.Lock(); try { // True if we have someone waiting for reopened searcher: bool hasWaiting = WaitingGen > SearchingGen; long nextReopenStartNS = lastReopenStartNS + (hasWaiting ? TargetMinStaleNS : TargetMaxStaleNS); long sleepNS = nextReopenStartNS - (DateTime.Now.Ticks * 100); if (sleepNS > 0) { ReopenCond.WaitOne(new TimeSpan(sleepNS / 100));//Convert NS to Ticks } else { break; } } catch (ThreadInterruptedException ie) { Thread.CurrentThread.Interrupt(); return; } finally { ReopenLock.Unlock(); } } if (Finish) { break; } lastReopenStartNS = DateTime.Now.Ticks * 100; // Save the gen as of when we started the reopen; the // listener (HandleRefresh above) copies this to // searchingGen once the reopen completes: RefreshStartGen = Writer.AndIncrementGeneration; try { Manager.MaybeRefreshBlocking(); } catch (System.IO.IOException ioe) { throw new Exception(ioe.Message, ioe); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { internal const string ExtendedPathPrefix = @"\\?\"; internal const string UncPathPrefix = @"\\"; internal const string UncExtendedPrefixToInsert = @"?\UNC\"; internal const string UncExtendedPathPrefix = @"\\?\UNC\"; internal const int MaxShortPath = 260; internal const int MaxShortDirectoryPath = 248; internal const int MaxExtendedPath = short.MaxValue; internal static readonly char[] InvalidPathChars = { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31 }; internal static readonly char[] InvalidPathCharsWithAdditionalChecks = // This is used by HasIllegalCharacters { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, '*', '?' }; /// <summary> /// Returns true if the path is too long /// </summary> internal static bool IsPathTooLong(string fullPath) { if (IsExtended(fullPath)) { return fullPath.Length >= MaxExtendedPath; } else { // Will need to be updated with #2581 to allow all paths to MaxExtendedPath // minus legth of extended local or UNC prefix. return fullPath.Length >= MaxShortPath; } } /// <summary> /// Returns true if the directory is too long /// </summary> internal static bool IsDirectoryTooLong(string fullPath) { if (IsExtended(fullPath)) { return fullPath.Length >= MaxExtendedPath; } else { // Will need to be updated with #2581 to allow all paths to MaxExtendedPath // minus legth of extended local or UNC prefix. return fullPath.Length >= MaxShortDirectoryPath; } } /// <summary> /// Adds the extended path prefix (\\?\) if not already present. /// </summary> internal static string AddExtendedPathPrefix(string path) { if (IsExtended(path)) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) return path.Insert(2, PathInternal.UncExtendedPrefixToInsert); return PathInternal.ExtendedPathPrefix + path; } /// <summary> /// Removes the extended path prefix (\\?\) if present. /// </summary> internal static string RemoveExtendedPathPrefix(string path) { if (!IsExtended(path)) return path; // Given \\?\UNC\server\share we return \\server\share if (IsExtendedUnc(path)) return path.Remove(2, 6); return path.Substring(4); } /// <summary> /// Removes the extended path prefix (\\?\) if present. /// </summary> internal static StringBuilder RemoveExtendedPathPrefix(StringBuilder path) { if (!IsExtended(path)) return path; // Given \\?\UNC\server\share we return \\server\share if (IsExtendedUnc(path)) return path.Remove(2, 6); return path.Remove(0, 4); } /// <summary> /// Returns true if the path uses the extended syntax (\\?\) /// </summary> internal static bool IsExtended(string path) { return path != null && path.StartsWith(ExtendedPathPrefix, StringComparison.Ordinal); } /// <summary> /// Returns true if the path uses the extended syntax (\\?\) /// </summary> internal static bool IsExtended(StringBuilder path) { return path != null && path.StartsWithOrdinal(ExtendedPathPrefix); } /// <summary> /// Returns true if the path uses the extended UNC syntax (\\?\UNC\) /// </summary> internal static bool IsExtendedUnc(string path) { return path != null && path.StartsWith(UncExtendedPathPrefix, StringComparison.Ordinal); } /// <summary> /// Returns true if the path uses the extended UNC syntax (\\?\UNC\) /// </summary> internal static bool IsExtendedUnc(StringBuilder path) { return path != null && path.StartsWithOrdinal(UncExtendedPathPrefix); } private static bool StartsWithOrdinal(this StringBuilder builder, string value) { if (value == null || builder.Length < value.Length) return false; for (int i = 0; i < value.Length; i++) { if (builder[i] != value[i]) return false; } return true; } /// <summary> /// Returns a value indicating if the given path contains invalid characters (", &lt;, &gt;, | /// NUL, or any ASCII char whose integer representation is in the range of 1 through 31), /// optionally checking for ? and *. /// </summary> internal static bool HasIllegalCharacters(string path, bool checkAdditional = false) { // See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx Contract.Requires(path != null); // Question mark is a normal part of extended path syntax (\\?\) int startIndex = PathInternal.IsExtended(path) ? ExtendedPathPrefix.Length : 0; return path.IndexOfAny(checkAdditional ? InvalidPathCharsWithAdditionalChecks : InvalidPathChars, startIndex) >= 0; } /// <summary> /// Gets the length of the root of the path (drive, share, etc.). /// </summary> internal static int GetRootLength(string path) { CheckInvalidPathChars(path); int i = 0; int length = path.Length; int volumeSeparatorLength = 2; // Length to the colon "C:" int uncRootLength = 2; // Length to the start of the server name "\\" bool extendedSyntax = IsExtended(path); bool extendedUncSyntax = IsExtendedUnc(path); if (extendedSyntax) { // Shift the position we look for the root from to account for the extended prefix if (extendedUncSyntax) { // "\\" -> "\\?\UNC\" uncRootLength = UncExtendedPathPrefix.Length; } else { // "C:" -> "\\?\C:" volumeSeparatorLength += ExtendedPathPrefix.Length; } } if ((!extendedSyntax || extendedUncSyntax) && length > 0 && IsDirectorySeparator(path[0])) { // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo") i = 1; // Drive rooted (\foo) is one character if (extendedUncSyntax || (length > 1 && (IsDirectorySeparator(path[1])))) { // UNC (\\?\UNC\ or \\), scan past the next two directory separators at most // (e.g. to \\?\UNC\Server\Share or \\Server\Share\) i = uncRootLength; int n = 2; // Maximum separators to skip while (i < length && (!IsDirectorySeparator(path[i]) || --n > 0)) i++; } } else if (length >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == Path.VolumeSeparatorChar) { // Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:) // If the colon is followed by a directory separator, move past it i = volumeSeparatorLength; if (length >= volumeSeparatorLength + 1 && (IsDirectorySeparator(path[volumeSeparatorLength]))) i++; } return i; } internal static bool IsDirectorySeparator(char c) { return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework.Internal; using NUnit.TestUtilities.Collections; namespace NUnit.Framework.Assertions { /// <summary> /// Summary description for ArrayEqualsFailureMessageFixture. /// </summary> // TODO: Exact tests of messages are fragile - revisit this [TestFixture] public class ArrayEqualsFailureMessageFixture { private readonly string NL = Environment.NewLine; [Test] public void ArraysHaveDifferentRanks() { int[] expected = new int[] { 1, 2, 3, 4 }; int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } }; var expectedMessage = " Expected is <System.Int32[4]>, actual is <System.Int32[2,2]>" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ExpectedArrayIsLonger() { int[] expected = new int[] { 1, 2, 3, 4, 5 }; int[] actual = new int[] { 1, 2, 3 }; var expectedMessage = " Expected is <System.Int32[5]>, actual is <System.Int32[3]>" + NL + " Values differ at index [3]" + NL + " Missing: < 4, 5 >"; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ActualArrayIsLonger() { int[] expected = new int[] { 1, 2, 3 }; int[] actual = new int[] { 1, 2, 3, 4, 5, 6, 7 }; var expectedMessage = " Expected is <System.Int32[3]>, actual is <System.Int32[7]>" + NL + " Values differ at index [3]" + NL + " Extra: < 4, 5, 6... >"; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void FailureOnSingleDimensionedArrays() { int[] expected = new int[] { 1, 2, 3 }; int[] actual = new int[] { 1, 5, 3 }; var expectedMessage = " Expected and actual are both <System.Int32[3]>" + NL + " Values differ at index [1]" + NL + TextMessageWriter.Pfx_Expected + "2" + NL + TextMessageWriter.Pfx_Actual + "5" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DoubleDimensionedArrays() { int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] actual = new int[,] { { 1, 3, 2 }, { 4, 0, 6 } }; var expectedMessage = " Expected and actual are both <System.Int32[2,3]>" + NL + " Values differ at index [0,1]" + NL + TextMessageWriter.Pfx_Expected + "2" + NL + TextMessageWriter.Pfx_Actual + "3" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void TripleDimensionedArrays() { int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; int[, ,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 0, 6 }, { 7, 8 } } }; var expectedMessage = " Expected and actual are both <System.Int32[2,2,2]>" + NL + " Values differ at index [1,0,0]" + NL + TextMessageWriter.Pfx_Expected + "5" + NL + TextMessageWriter.Pfx_Actual + "0" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void FiveDimensionedArrays() { int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 4, 3 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; var expectedMessage = " Expected and actual are both <System.Int32[2,2,2,2,2]>" + NL + " Values differ at index [0,0,0,1,0]" + NL + TextMessageWriter.Pfx_Expected + "3" + NL + TextMessageWriter.Pfx_Actual + "4" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void JaggedArrays() { int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 0, 7 }, new int[] { 8, 9 } }; var expectedMessage = " Expected and actual are both <System.Int32[3][]>" + NL + " Values differ at index [1]" + NL + " Expected and actual are both <System.Int32[4]>" + NL + " Values differ at index [2]" + NL + TextMessageWriter.Pfx_Expected + "6" + NL + TextMessageWriter.Pfx_Actual + "0" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void JaggedArrayComparedToSimpleArray() { int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 0, 7 }, new int[] { 8, 9 } }; var expectedMessage = " Expected is <System.Int32[9]>, actual is <System.Int32[3][]>" + NL + " Values differ at index [0]" + NL + TextMessageWriter.Pfx_Expected + "1" + NL + TextMessageWriter.Pfx_Actual + "< 1, 2, 3 >" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ArraysWithDifferentRanksAsCollection() { int[] expected = new int[] { 1, 2, 3, 4 }; int[,] actual = new int[,] { { 1, 0 }, { 3, 4 } }; var expectedMessage = " Expected is <System.Int32[4]>, actual is <System.Int32[2,2]>" + NL + " Values differ at expected index [1], actual index [0,1]" + NL + TextMessageWriter.Pfx_Expected + "2" + NL + TextMessageWriter.Pfx_Actual + "0" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected).AsCollection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ArraysWithDifferentDimensionsAsCollection() { int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] actual = new int[,] { { 1, 2 }, { 3, 0 }, { 5, 6 } }; var expectedMessage = " Expected is <System.Int32[2,3]>, actual is <System.Int32[3,2]>" + NL + " Values differ at expected index [1,0], actual index [1,1]" + NL + TextMessageWriter.Pfx_Expected + "4" + NL + TextMessageWriter.Pfx_Actual + "0" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected).AsCollection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void SameLengthDifferentContent() { string[] actual = { "one", "two", "three" }; string[] expected = { "one", "two", "ten" }; var expectedMessage = " Expected and actual are both <System.String[3]>" + NL + " Values differ at index [2]" + NL + " Expected string length 3 but was 5. Strings differ at index 1." + NL + " Expected: \"ten\"" + NL + " But was: \"three\"" + NL + " ------------^" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ArraysDeclaredAsDifferentTypes() { string[] actual = { "one", "two", "three" }; object[] expected = { "one", "three", "two" }; var expectedMessage = " Expected is <System.Object[3]>, actual is <System.String[3]>" + NL + " Values differ at index [1]" + NL + " Expected string length 5 but was 3. Strings differ at index 1." + NL + " Expected: \"three\"" + NL + " But was: \"two\"" + NL + " ------------^" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ArrayAndCollection_Failure() { int[] expected = new int[] { 1, 2, 3 }; var actual = new List<int>(new int[] { 1, 3 }); var expectedMessage = " Expected is <System.Int32[3]>, actual is <System.Collections.Generic.List`1[System.Int32]> with 2 elements" + NL + " Values differ at index [1]" + NL + " Expected: 2" + NL + " But was: 3" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(actual, Is.EqualTo(expected).AsCollection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DifferentArrayTypesEqualFails() { string[] array1 = { "one", "two", "three" }; object[] array2 = { "one", "three", "two" }; var expectedMessage = " Expected is <System.String[3]>, actual is <System.Object[3]>" + NL + " Values differ at index [1]" + NL + " Expected string length 3 but was 5. Strings differ at index 1." + NL + " Expected: \"two\"" + NL + " But was: \"three\"" + NL + " ------------^" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(array2, Is.EqualTo(array1))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { [global::System.CLSCompliantAttribute(false)] [global::System.Security.SecurityCriticalAttribute] public static partial class WindowsRuntimeSystemExtensions { public static global::Windows.Foundation.IAsyncAction AsAsyncAction(this global::System.Threading.Tasks.Task source) { return default(global::Windows.Foundation.IAsyncAction); } public static global::Windows.Foundation.IAsyncOperation<TResult> AsAsyncOperation<TResult>(this global::System.Threading.Tasks.Task<TResult> source) { return default(global::Windows.Foundation.IAsyncOperation<TResult>); } public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { return default(global::System.Threading.Tasks.Task<TResult>); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task<TResult>); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { return default(global::System.Threading.Tasks.Task<TResult>); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task<TResult>); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken) { return default(global::System.Threading.Tasks.Task<TResult>); } public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { return default(global::System.Threading.Tasks.Task<TResult>); } [global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))] public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter); } [global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))] public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter); } [global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))] public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter<TResult>); } [global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))] public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { return default(global::System.Runtime.CompilerServices.TaskAwaiter<TResult>); } } } namespace System.IO { [global::System.Security.SecurityCriticalAttribute] public static partial class WindowsRuntimeStorageExtensions { [global::System.CLSCompliantAttribute(false)] public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); } [global::System.CLSCompliantAttribute(false)] public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); } [global::System.CLSCompliantAttribute(false)] public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); } [global::System.CLSCompliantAttribute(false)] public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, global::Windows.Storage.CreationCollisionOption creationCollisionOption) { return default(global::System.Threading.Tasks.Task<global::System.IO.Stream>); } } [global::System.Security.SecurityCriticalAttribute] public static partial class WindowsRuntimeStreamExtensions { [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IInputStream AsInputStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IInputStream); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IOutputStream AsOutputStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IOutputStream); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IRandomAccessStream AsRandomAccessStream(this global::System.IO.Stream stream) { return default(global::Windows.Storage.Streams.IRandomAccessStream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream, int bufferSize) { return default(global::System.IO.Stream); } } } namespace System.Runtime.InteropServices.WindowsRuntime { [global::System.CLSCompliantAttribute(false)] [global::System.Security.SecurityCriticalAttribute] public static partial class AsyncInfo { public static global::Windows.Foundation.IAsyncAction Run(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task> taskProvider) { return default(global::Windows.Foundation.IAsyncAction); } public static global::Windows.Foundation.IAsyncActionWithProgress<TProgress> Run<TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task> taskProvider) { return default(global::Windows.Foundation.IAsyncActionWithProgress<TProgress>); } public static global::Windows.Foundation.IAsyncOperation<TResult> Run<TResult>(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task<TResult>> taskProvider) { return default(global::Windows.Foundation.IAsyncOperation<TResult>); } public static global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> Run<TResult, TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task<TResult>> taskProvider) { return default(global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress>); } } [global::System.Security.SecurityCriticalAttribute] public sealed partial class WindowsRuntimeBuffer { internal WindowsRuntimeBuffer() { } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer Create(byte[] data, int offset, int length, int capacity) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer Create(int capacity) { return default(global::Windows.Storage.Streams.IBuffer); } } [global::System.Security.SecurityCriticalAttribute] public static partial class WindowsRuntimeBufferExtensions { [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length, int capacity) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IBuffer source) { return default(global::System.IO.Stream); } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this byte[] source, int sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, int count) { } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this byte[] source, global::Windows.Storage.Streams.IBuffer destination) { } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, byte[] destination) { } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, byte[] destination, int destinationIndex, int count) { } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, uint count) { } [global::System.CLSCompliantAttribute(false)] public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, global::Windows.Storage.Streams.IBuffer destination) { } [global::System.CLSCompliantAttribute(false)] public static byte GetByte(this global::Windows.Storage.Streams.IBuffer source, uint byteOffset) { return default(byte); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream, int positionInStream, int length) { return default(global::Windows.Storage.Streams.IBuffer); } [global::System.CLSCompliantAttribute(false)] public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer otherBuffer) { return default(bool); } [global::System.CLSCompliantAttribute(false)] public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { return default(byte[]); } [global::System.CLSCompliantAttribute(false)] public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, int count) { return default(byte[]); } } } namespace Windows.Foundation { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Point { public Point(double x, double y) { throw new global::System.NotImplementedException(); } public double X { get { return default(double); } set { } } public double Y { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.Foundation.Point value) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { return default(bool); } public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider provider) { return default(string); } } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Rect { public Rect(double x, double y, double width, double height) { throw new global::System.NotImplementedException(); } public Rect(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw new global::System.NotImplementedException(); } public Rect(global::Windows.Foundation.Point location, global::Windows.Foundation.Size size) { throw new global::System.NotImplementedException(); } public double Bottom { get { return default(double); } } public static global::Windows.Foundation.Rect Empty { get { return default(global::Windows.Foundation.Rect); } } public double Height { get { return default(double); } set { } } public bool IsEmpty { get { return default(bool); } } public double Left { get { return default(double); } } public double Right { get { return default(double); } } public double Top { get { return default(double); } } public double Width { get { return default(double); } set { } } public double X { get { return default(double); } set { } } public double Y { get { return default(double); } set { } } public bool Contains(global::Windows.Foundation.Point point) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.Foundation.Rect value) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public void Intersect(global::Windows.Foundation.Rect rect) { } public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { return default(bool); } public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider provider) { return default(string); } public void Union(global::Windows.Foundation.Point point) { } public void Union(global::Windows.Foundation.Rect rect) { } } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Size { public Size(double width, double height) { throw new global::System.NotImplementedException(); } public static global::Windows.Foundation.Size Empty { get { return default(global::Windows.Foundation.Size); } } public double Height { get { return default(double); } set { } } public bool IsEmpty { get { return default(bool); } } public double Width { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.Foundation.Size value) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { return default(bool); } public static bool operator !=(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } } namespace Windows.UI { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Color { public byte A { get { return default(byte); } set { } } public byte B { get { return default(byte); } set { } } public byte G { get { return default(byte); } set { } } public byte R { get { return default(byte); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.UI.Color color) { return default(bool); } public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { return default(global::Windows.UI.Color); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { return default(bool); } public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider provider) { return default(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.Collections.Generic; using System.Diagnostics; using System.Globalization; #if !FEATURE_SERIALIZATION namespace System.CodeDom #else namespace System.Runtime.Serialization #endif { [Flags] #if !FEATURE_SERIALIZATION public enum CodeTypeReferenceOptions #else internal enum CodeTypeReferenceOptions #endif { GlobalReference = 0x00000001, GenericTypeParameter = 0x00000002 } #if !FEATURE_SERIALIZATION public class CodeTypeReference : CodeObject #else internal class CodeTypeReference : CodeObject #endif { private string _baseType; private readonly bool _isInterface; private CodeTypeReferenceCollection _typeArguments; private bool _needsFixup = false; public CodeTypeReference() { _baseType = string.Empty; ArrayRank = 0; ArrayElementType = null; } public CodeTypeReference(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsArray) { ArrayRank = type.GetArrayRank(); ArrayElementType = new CodeTypeReference(type.GetElementType()); _baseType = null; } else { InitializeFromType(type); ArrayRank = 0; ArrayElementType = null; } _isInterface = type.IsInterface; } public CodeTypeReference(Type type, CodeTypeReferenceOptions codeTypeReferenceOption) : this(type) { Options = codeTypeReferenceOption; } public CodeTypeReference(string typeName, CodeTypeReferenceOptions codeTypeReferenceOption) { Initialize(typeName, codeTypeReferenceOption); } public CodeTypeReference(string typeName) { Initialize(typeName); } private void InitializeFromType(Type type) { _baseType = type.Name; if (!type.IsGenericParameter) { Type currentType = type; while (currentType.IsNested) { currentType = currentType.DeclaringType; _baseType = currentType.Name + "+" + _baseType; } if (!string.IsNullOrEmpty(type.Namespace)) { _baseType = type.Namespace + "." + _baseType; } } // pick up the type arguments from an instantiated generic type but not an open one if (type.IsGenericType && !type.ContainsGenericParameters) { Type[] genericArgs = type.GetGenericArguments(); for (int i = 0; i < genericArgs.Length; i++) { TypeArguments.Add(new CodeTypeReference(genericArgs[i])); } } else if (!type.IsGenericTypeDefinition) { // if the user handed us a non-generic type, but later // appends generic type arguments, we'll pretend // it's a generic type for their sake - this is good for // them if they pass in System.Nullable class when they // meant the System.Nullable<T> value type. _needsFixup = true; } } private void Initialize(string typeName) { Initialize(typeName, Options); } private void Initialize(string typeName, CodeTypeReferenceOptions options) { Options = options; if (string.IsNullOrEmpty(typeName)) { typeName = typeof(void).FullName; _baseType = typeName; ArrayRank = 0; ArrayElementType = null; return; } typeName = RipOffAssemblyInformationFromTypeName(typeName); int end = typeName.Length - 1; int current = end; _needsFixup = true; // default to true, and if we find arity or generic type args, we'll clear the flag. // Scan the entire string for valid array tails and store ranks for array tails // we found in a queue. var q = new Queue<int>(); while (current >= 0) { int rank = 1; if (typeName[current--] == ']') { while (current >= 0 && typeName[current] == ',') { rank++; current--; } if (current >= 0 && typeName[current] == '[') { // found a valid array tail q.Enqueue(rank); current--; end = current; continue; } } break; } // Try find generic type arguments current = end; var typeArgumentList = new List<CodeTypeReference>(); var subTypeNames = new Stack<string>(); if (current > 0 && typeName[current--] == ']') { _needsFixup = false; int unmatchedRightBrackets = 1; int subTypeNameEndIndex = end; // Try find the matching '[', if we can't find it, we will not try to parse the string while (current >= 0) { if (typeName[current] == '[') { // break if we found matched brackets if (--unmatchedRightBrackets == 0) break; } else if (typeName[current] == ']') { ++unmatchedRightBrackets; } else if (typeName[current] == ',' && unmatchedRightBrackets == 1) { // // Type name can contain nested generic types. Following is an example: // System.Collections.Generic.Dictionary`2[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], // [System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], // mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] // // Spliltting by ',' won't work. We need to do first-level split by ','. // if (current + 1 < subTypeNameEndIndex) { subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1)); } subTypeNameEndIndex = current; } --current; } if (current > 0 && (end - current - 1) > 0) { // push the last generic type argument name if there is any if (current + 1 < subTypeNameEndIndex) { subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1)); } // we found matched brackets and the brackets contains some characters. while (subTypeNames.Count > 0) { string name = RipOffAssemblyInformationFromTypeName(subTypeNames.Pop()); typeArgumentList.Add(new CodeTypeReference(name)); } end = current - 1; } } if (end < 0) { // this can happen if we have some string like "[...]" _baseType = typeName; return; } if (q.Count > 0) { CodeTypeReference type = new CodeTypeReference(typeName.Substring(0, end + 1), Options); for (int i = 0; i < typeArgumentList.Count; i++) { type.TypeArguments.Add(typeArgumentList[i]); } while (q.Count > 1) { type = new CodeTypeReference(type, q.Dequeue()); } // we don't need to create a new CodeTypeReference for the last one. Debug.Assert(q.Count == 1, "We should have one and only one in the rank queue."); _baseType = null; ArrayRank = q.Dequeue(); ArrayElementType = type; } else if (typeArgumentList.Count > 0) { for (int i = 0; i < typeArgumentList.Count; i++) { TypeArguments.Add(typeArgumentList[i]); } _baseType = typeName.Substring(0, end + 1); } else { _baseType = typeName; } // Now see if we have some arity. baseType could be null if this is an array type. if (_baseType != null && _baseType.IndexOf('`') != -1) { _needsFixup = false; } } public CodeTypeReference(string typeName, params CodeTypeReference[] typeArguments) : this(typeName) { if (typeArguments != null && typeArguments.Length > 0) { TypeArguments.AddRange(typeArguments); } } #if !FEATURE_SERIALIZATION public CodeTypeReference(CodeTypeParameter typeParameter) : this(typeParameter?.Name) { Options = CodeTypeReferenceOptions.GenericTypeParameter; } #endif public CodeTypeReference(string baseType, int rank) { _baseType = null; ArrayRank = rank; ArrayElementType = new CodeTypeReference(baseType); } public CodeTypeReference(CodeTypeReference arrayType, int rank) { _baseType = null; ArrayRank = rank; ArrayElementType = arrayType; } public CodeTypeReference ArrayElementType { get; set; } public int ArrayRank { get; set; } internal int NestedArrayDepth => ArrayElementType == null ? 0 : 1 + ArrayElementType.NestedArrayDepth; public string BaseType { get { if (ArrayRank > 0 && ArrayElementType != null) { return ArrayElementType.BaseType; } if (string.IsNullOrEmpty(_baseType)) { return string.Empty; } string returnType = _baseType; return _needsFixup && TypeArguments.Count > 0 ? returnType + '`' + TypeArguments.Count.ToString(CultureInfo.InvariantCulture) : returnType; } set { _baseType = value; Initialize(_baseType); } } public CodeTypeReferenceOptions Options { get; set; } public CodeTypeReferenceCollection TypeArguments { get { if (ArrayRank > 0 && ArrayElementType != null) { return ArrayElementType.TypeArguments; } if (_typeArguments == null) { _typeArguments = new CodeTypeReferenceCollection(); } return _typeArguments; } } internal bool IsInterface => _isInterface; // Note that this only works correctly if the Type ctor was used. Otherwise, it's always false. // // The string for generic type argument might contain assembly information and square bracket pair. // There might be leading spaces in front the type name. // Following function will rip off assembly information and brackets // Following is an example: // " [System.Collections.Generic.List[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, // PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]" // private string RipOffAssemblyInformationFromTypeName(string typeName) { int start = 0; int end = typeName.Length - 1; string result = typeName; // skip whitespace in the beginning while (start < typeName.Length && char.IsWhiteSpace(typeName[start])) start++; while (end >= 0 && char.IsWhiteSpace(typeName[end])) end--; if (start < end) { if (typeName[start] == '[' && typeName[end] == ']') { start++; end--; } // if we still have a ] at the end, there's no assembly info. if (typeName[end] != ']') { int commaCount = 0; for (int index = end; index >= start; index--) { if (typeName[index] == ',') { commaCount++; if (commaCount == 4) { result = typeName.Substring(start, index - start); break; } } } } } return result; } } }
using Discord.API.Rest; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; using UserModel = Discord.API.User; namespace Discord.Rest { internal static class ChannelHelper { //General public static async Task DeleteAsync(IChannel channel, BaseDiscordClient client, RequestOptions options) { await client.ApiClient.DeleteChannelAsync(channel.Id, options).ConfigureAwait(false); } public static async Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client, Action<GuildChannelProperties> func, RequestOptions options) { var args = new GuildChannelProperties(); func(args); var apiArgs = new API.Rest.ModifyGuildChannelParams { Name = args.Name, Position = args.Position, CategoryId = args.CategoryId }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } public static async Task<Model> ModifyAsync(ITextChannel channel, BaseDiscordClient client, Action<TextChannelProperties> func, RequestOptions options) { var args = new TextChannelProperties(); func(args); var apiArgs = new API.Rest.ModifyTextChannelParams { Name = args.Name, Position = args.Position, CategoryId = args.CategoryId, Topic = args.Topic, IsNsfw = args.IsNsfw, SlowModeInterval = args.SlowModeInterval, }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } public static async Task<Model> ModifyAsync(IVoiceChannel channel, BaseDiscordClient client, Action<VoiceChannelProperties> func, RequestOptions options) { var args = new VoiceChannelProperties(); func(args); var apiArgs = new API.Rest.ModifyVoiceChannelParams { Bitrate = args.Bitrate, Name = args.Name, Position = args.Position, CategoryId = args.CategoryId, UserLimit = args.UserLimit.IsSpecified ? (args.UserLimit.Value ?? 0) : Optional.Create<int>() }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } //Invites public static async Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(IGuildChannel channel, BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetChannelInvitesAsync(channel.Id, options).ConfigureAwait(false); return models.Select(x => RestInviteMetadata.Create(client, null, channel, x)).ToImmutableArray(); } /// <exception cref="ArgumentException"> /// <paramref name="channel.Id"/> may not be equal to zero. /// -and- /// <paramref name="maxAge"/> and <paramref name="maxUses"/> must be greater than zero. /// -and- /// <paramref name="maxAge"/> must be lesser than 86400. /// </exception> public static async Task<RestInviteMetadata> CreateInviteAsync(IGuildChannel channel, BaseDiscordClient client, int? maxAge, int? maxUses, bool isTemporary, bool isUnique, RequestOptions options) { var args = new API.Rest.CreateChannelInviteParams { IsTemporary = isTemporary, IsUnique = isUnique, MaxAge = maxAge ?? 0, MaxUses = maxUses ?? 0 }; var model = await client.ApiClient.CreateChannelInviteAsync(channel.Id, args, options).ConfigureAwait(false); return RestInviteMetadata.Create(client, null, channel, model); } //Messages public static async Task<RestMessage> GetMessageAsync(IMessageChannel channel, BaseDiscordClient client, ulong id, RequestOptions options) { var guildId = (channel as IGuildChannel)?.GuildId; var guild = guildId != null ? await (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).ConfigureAwait(false) : null; var model = await client.ApiClient.GetChannelMessageAsync(channel.Id, id, options).ConfigureAwait(false); if (model == null) return null; var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); return RestMessage.Create(client, channel, author, model); } public static IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessageChannel channel, BaseDiscordClient client, ulong? fromMessageId, Direction dir, int limit, RequestOptions options) { if (dir == Direction.Around) throw new NotImplementedException(); //TODO: Impl var guildId = (channel as IGuildChannel)?.GuildId; var guild = guildId != null ? (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).Result : null; return new PagedAsyncEnumerable<RestMessage>( DiscordConfig.MaxMessagesPerBatch, async (info, ct) => { var args = new GetChannelMessagesParams { RelativeDirection = dir, Limit = info.PageSize }; if (info.Position != null) args.RelativeMessageId = info.Position.Value; var models = await client.ApiClient.GetChannelMessagesAsync(channel.Id, args, options).ConfigureAwait(false); var builder = ImmutableArray.CreateBuilder<RestMessage>(); foreach (var model in models) { var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); builder.Add(RestMessage.Create(client, channel, author, model)); } return builder.ToImmutable(); }, nextPage: (info, lastPage) => { if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch) return false; if (dir == Direction.Before) info.Position = lastPage.Min(x => x.Id); else info.Position = lastPage.Max(x => x.Id); return true; }, start: fromMessageId, count: limit ); } public static async Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(IMessageChannel channel, BaseDiscordClient client, RequestOptions options) { var guildId = (channel as IGuildChannel)?.GuildId; var guild = guildId != null ? await (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).ConfigureAwait(false) : null; var models = await client.ApiClient.GetPinsAsync(channel.Id, options).ConfigureAwait(false); var builder = ImmutableArray.CreateBuilder<RestMessage>(); foreach (var model in models) { var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); builder.Add(RestMessage.Create(client, channel, author, model)); } return builder.ToImmutable(); } /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public static async Task<RestUserMessage> SendMessageAsync(IMessageChannel channel, BaseDiscordClient client, string text, bool isTTS, Embed embed, RequestOptions options) { var args = new CreateMessageParams(text) { IsTTS = isTTS, Embed = embed?.ToModel() }; var model = await client.ApiClient.CreateMessageAsync(channel.Id, args, options).ConfigureAwait(false); return RestUserMessage.Create(client, channel, client.CurrentUser, model); } /// <exception cref="ArgumentException"> /// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more /// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="filePath" /> is <c>null</c>. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. For example, on /// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 /// characters. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// The specified path is invalid, (for example, it is on an unmapped drive). /// </exception> /// <exception cref="UnauthorizedAccessException"> /// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission. /// </exception> /// <exception cref="FileNotFoundException"> /// The file specified in <paramref name="filePath" /> was not found. /// </exception> /// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception> /// <exception cref="IOException">An I/O error occurred while opening the file.</exception> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client, string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler) { string filename = Path.GetFileName(filePath); using (var file = File.OpenRead(filePath)) return await SendFileAsync(channel, client, file, filename, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false); } /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public static async Task<RestUserMessage> SendFileAsync(IMessageChannel channel, BaseDiscordClient client, Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler) { var args = new UploadFileParams(stream) { Filename = filename, Content = text, IsTTS = isTTS, Embed = embed != null ? embed.ToModel() : Optional<API.Embed>.Unspecified, IsSpoiler = isSpoiler }; var model = await client.ApiClient.UploadFileAsync(channel.Id, args, options).ConfigureAwait(false); return RestUserMessage.Create(client, channel, client.CurrentUser, model); } public static Task DeleteMessageAsync(IMessageChannel channel, ulong messageId, BaseDiscordClient client, RequestOptions options) => MessageHelper.DeleteAsync(channel.Id, messageId, client, options); public static async Task DeleteMessagesAsync(ITextChannel channel, BaseDiscordClient client, IEnumerable<ulong> messageIds, RequestOptions options) { const int BATCH_SIZE = 100; var msgs = messageIds.ToArray(); int batches = msgs.Length / BATCH_SIZE; for (int i = 0; i <= batches; i++) { ArraySegment<ulong> batch; if (i < batches) { batch = new ArraySegment<ulong>(msgs, i * BATCH_SIZE, BATCH_SIZE); } else { batch = new ArraySegment<ulong>(msgs, i * BATCH_SIZE, msgs.Length - batches * BATCH_SIZE); if (batch.Count == 0) { break; } } var args = new DeleteMessagesParams(batch.ToArray()); await client.ApiClient.DeleteMessagesAsync(channel.Id, args, options).ConfigureAwait(false); } } //Permission Overwrites public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client, IUser user, OverwritePermissions perms, RequestOptions options) { var args = new ModifyChannelPermissionsParams("member", perms.AllowValue, perms.DenyValue); await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, user.Id, args, options).ConfigureAwait(false); } public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client, IRole role, OverwritePermissions perms, RequestOptions options) { var args = new ModifyChannelPermissionsParams("role", perms.AllowValue, perms.DenyValue); await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, role.Id, args, options).ConfigureAwait(false); } public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client, IUser user, RequestOptions options) { await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options).ConfigureAwait(false); } public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client, IRole role, RequestOptions options) { await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options).ConfigureAwait(false); } //Users /// <exception cref="InvalidOperationException">Resolving permissions requires the parent guild to be downloaded.</exception> public static async Task<RestGuildUser> GetUserAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetGuildMemberAsync(channel.GuildId, id, options).ConfigureAwait(false); if (model == null) return null; var user = RestGuildUser.Create(client, guild, model); if (!user.GetPermissions(channel).ViewChannel) return null; return user; } /// <exception cref="InvalidOperationException">Resolving permissions requires the parent guild to be downloaded.</exception> public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuildChannel channel, IGuild guild, BaseDiscordClient client, ulong? fromUserId, int? limit, RequestOptions options) { return new PagedAsyncEnumerable<RestGuildUser>( DiscordConfig.MaxUsersPerBatch, async (info, ct) => { var args = new GetGuildMembersParams { Limit = info.PageSize }; if (info.Position != null) args.AfterUserId = info.Position.Value; var models = await client.ApiClient.GetGuildMembersAsync(guild.Id, args, options).ConfigureAwait(false); return models .Select(x => RestGuildUser.Create(client, guild, x)) .Where(x => x.GetPermissions(channel).ViewChannel) .ToImmutableArray(); }, nextPage: (info, lastPage) => { if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch) return false; info.Position = lastPage.Max(x => x.Id); return true; }, start: fromUserId, count: limit ); } //Typing public static async Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client, RequestOptions options = null) { await client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options).ConfigureAwait(false); } public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client, RequestOptions options) => new TypingNotifier(channel, options); //Webhooks public static async Task<RestWebhook> CreateWebhookAsync(ITextChannel channel, BaseDiscordClient client, string name, Stream avatar, RequestOptions options) { var args = new CreateWebhookParams { Name = name }; if (avatar != null) args.Avatar = new API.Image(avatar); var model = await client.ApiClient.CreateWebhookAsync(channel.Id, args, options).ConfigureAwait(false); return RestWebhook.Create(client, channel, model); } public static async Task<RestWebhook> GetWebhookAsync(ITextChannel channel, BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetWebhookAsync(id, options: options).ConfigureAwait(false); if (model == null) return null; return RestWebhook.Create(client, channel, model); } public static async Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(ITextChannel channel, BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetChannelWebhooksAsync(channel.Id, options).ConfigureAwait(false); return models.Select(x => RestWebhook.Create(client, channel, x)) .ToImmutableArray(); } // Categories public static async Task<ICategoryChannel> GetCategoryAsync(INestedChannel channel, BaseDiscordClient client, RequestOptions options) { // if no category id specified, return null if (!channel.CategoryId.HasValue) return null; // CategoryId will contain a value here var model = await client.ApiClient.GetChannelAsync(channel.CategoryId.Value, options).ConfigureAwait(false); return RestCategoryChannel.Create(client, model) as ICategoryChannel; } /// <exception cref="InvalidOperationException">This channel does not have a parent channel.</exception> public static async Task SyncPermissionsAsync(INestedChannel channel, BaseDiscordClient client, RequestOptions options) { var category = await GetCategoryAsync(channel, client, options).ConfigureAwait(false); if (category == null) throw new InvalidOperationException("This channel does not have a parent channel."); var apiArgs = new ModifyGuildChannelParams { Overwrites = category.PermissionOverwrites .Select(overwrite => new API.Overwrite{ TargetId = overwrite.TargetId, TargetType = overwrite.TargetType, Allow = overwrite.Permissions.AllowValue, Deny = overwrite.Permissions.DenyValue }).ToArray() }; await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } //Helpers private static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId) { IUser author = null; if (guild != null) author = guild.GetUserAsync(model.Id, CacheMode.CacheOnly).Result; if (author == null) author = RestUser.Create(client, guild, model, webhookId); return author; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security.Cryptography.EcDsa.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDsa.OpenSsl.Tests { public class EcDsaOpenSslTests : ECDsaTestsBase { [Fact] public void DefaultCtor() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void Ctor256() { int expectedKeySize = 256; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor384() { int expectedKeySize = 384; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor521() { int expectedKeySize = 521; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [ConditionalFact(nameof(ECDsa224Available))] public void CtorHandle224() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P224_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle384() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P384_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle521() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandleDuplicate() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did his own ref-count bump. Interop.Crypto.EcKeyDestroy(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void KeySizePropWithExercise() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); ECParameters p384 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p384.Curve.CurveType); e.KeySize = 521; Assert.Equal(521, e.KeySize); e.Exercise(); ECParameters p521 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p521.Curve.CurveType); // ensure the key was regenerated Assert.NotEqual(p384.Curve.Oid.Value, p521.Curve.Oid.Value); } } [Fact] public void VerifyDuplicateKey_ValidHandle() { byte[] data = ByteUtils.RepeatByte(0x71, 11); using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { using (ECDsa second = new ECDsaOpenSsl(firstHandle)) { byte[] signed = second.SignData(data, HashAlgorithmName.SHA512); Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512)); } } } [Fact] public void VerifyDuplicateKey_DistinctHandles() { using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public void VerifyDuplicateKey_RefCounts() { byte[] data = ByteUtils.RepeatByte(0x74, 11); byte[] signature; ECDsa second; using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { signature = first.SignData(data, HashAlgorithmName.SHA384); second = new ECDsaOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) { Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384)); } } [Fact] public void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new ECDsaOpenSsl(pkey)); } [Fact] public void VerifyDuplicateKey_InvalidHandle() { using (ECDsaOpenSsl ecdsa = new ECDsaOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDsaOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDsaOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public void LookupCurveByOidValue() { ECDsaOpenSsl ec = null; ec = new ECDsaOpenSsl(ECCurve.CreateFromValue(ECDSA_P256_OID_VALUE)); // Same as nistP256 ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); } [Fact] public void LookupCurveByOidFriendlyName() { ECDsaOpenSsl ec = null; // prime256v1 is alias for nistP256 for OpenSsl ec = new ECDsaOpenSsl(ECCurve.CreateFromFriendlyName("prime256v1")); ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); // OpenSsl maps prime256v1 to ECDSA_P256 Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); // secp521r1 is same as nistP521; note Windows uses secP521r1 (uppercase P) ec = new ECDsaOpenSsl(ECCurve.CreateFromFriendlyName("secp521r1")); param = ec.ExportParameters(false); param.Validate(); Assert.Equal(521, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P521", param.Curve.Oid.FriendlyName); // OpenSsl maps secp521r1 to ECDSA_P521 Assert.Equal(ECDSA_P521_OID_VALUE, param.Curve.Oid.Value); } } } internal static partial class Interop { internal static class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")] internal static extern IntPtr EcKeyCreateByOid(string oid); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGenerateKey")] internal static extern int EcKeyGenerateKey(IntPtr ecKey); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] internal static extern void EcKeyDestroy(IntPtr r); } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace PlayFab.Json.Utilities { internal static class EnumUtils { /// <summary> /// Parses the specified enum member name, returning it's value. /// </summary> /// <param name="enumMemberName">Name of the enum member.</param> /// <returns></returns> public static T Parse<T>(string enumMemberName) where T : struct { return Parse<T>(enumMemberName, false); } /// <summary> /// Parses the specified enum member name, returning it's value. /// </summary> /// <param name="enumMemberName">Name of the enum member.</param> /// <param name="ignoreCase">If set to <c>true</c> ignore case.</param> /// <returns></returns> public static T Parse<T>(string enumMemberName, bool ignoreCase) where T : struct { ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); return (T)Enum.Parse(typeof(T), enumMemberName, ignoreCase); } public static bool TryParse<T>(string enumMemberName, bool ignoreCase, out T value) where T : struct { ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); return MiscellaneousUtils.TryAction(() => Parse<T>(enumMemberName, ignoreCase), out value); } public static IList<T> GetFlagsValues<T>(T value) where T : struct { Type enumType = typeof(T); if (!enumType.IsDefined(typeof(FlagsAttribute), false)) throw new Exception("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); Type underlyingType = Enum.GetUnderlyingType(value.GetType()); ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture); EnumValues<ulong> enumNameValues = GetNamesAndValues<T>(); IList<T> selectedFlagsValues = new List<T>(); foreach (EnumValue<ulong> enumNameValue in enumNameValues) { if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0) selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture)); } if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null) selectedFlagsValues.Add(default(T)); return selectedFlagsValues; } /// <summary> /// Gets a dictionary of the names and values of an Enum type. /// </summary> /// <returns></returns> public static EnumValues<ulong> GetNamesAndValues<T>() where T : struct { return GetNamesAndValues<ulong>(typeof(T)); } /// <summary> /// Gets a dictionary of the names and values of an Enum type. /// </summary> /// <returns></returns> public static EnumValues<TUnderlyingType> GetNamesAndValues<TEnum, TUnderlyingType>() where TEnum : struct where TUnderlyingType : struct { return GetNamesAndValues<TUnderlyingType>(typeof(TEnum)); } /// <summary> /// Gets a dictionary of the names and values of an Enum type. /// </summary> /// <param name="enumType">The enum type to get names and values for.</param> /// <returns></returns> public static EnumValues<TUnderlyingType> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct { if (enumType == null) throw new ArgumentNullException("enumType"); ValidationUtils.ArgumentTypeIsEnum(enumType, "enumType"); IList<object> enumValues = GetValues(enumType); IList<string> enumNames = GetNames(enumType); EnumValues<TUnderlyingType> nameValues = new EnumValues<TUnderlyingType>(); for (int i = 0; i < enumValues.Count; i++) { try { nameValues.Add(new EnumValue<TUnderlyingType>(enumNames[i], (TUnderlyingType)Convert.ChangeType(enumValues[i], typeof(TUnderlyingType), CultureInfo.CurrentCulture))); } catch (OverflowException e) { throw new Exception( string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}", Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e); } } return nameValues; } public static IList<T> GetValues<T>() { return GetValues(typeof(T)).Cast<T>().ToList(); } public static IList<object> GetValues(Type enumType) { if (!enumType.IsEnum) throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); List<object> values = new List<object>(); var fields = from field in enumType.GetFields() where field.IsLiteral select field; foreach (FieldInfo field in fields) { object value = field.GetValue(enumType); values.Add(value); } return values; } public static IList<string> GetNames<T>() { return GetNames(typeof(T)); } public static IList<string> GetNames(Type enumType) { if (!enumType.IsEnum) throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); List<string> values = new List<string>(); var fields = from field in enumType.GetFields() where field.IsLiteral select field; foreach (FieldInfo field in fields) { values.Add(field.Name); } return values; } /// <summary> /// Gets the maximum valid value of an Enum type. Flags enums are ORed. /// </summary> /// <typeparam name="TEnumType">The type of the returned value. Must be assignable from the enum's underlying value type.</typeparam> /// <param name="enumType">The enum type to get the maximum value for.</param> /// <returns></returns> public static TEnumType GetMaximumValue<TEnumType>(Type enumType) where TEnumType : IConvertible, IComparable<TEnumType> { if (enumType == null) throw new ArgumentNullException("enumType"); Type enumUnderlyingType = Enum.GetUnderlyingType(enumType); if (!typeof(TEnumType).IsAssignableFrom(enumUnderlyingType)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TEnumType is not assignable from the enum's underlying type of {0}.", enumUnderlyingType.Name)); ulong maximumValue = 0; IList<object> enumValues = GetValues(enumType); if (enumType.IsDefined(typeof(FlagsAttribute), false)) { foreach (TEnumType value in enumValues) { maximumValue = maximumValue | value.ToUInt64(CultureInfo.InvariantCulture); } } else { foreach (TEnumType value in enumValues) { ulong tempValue = value.ToUInt64(CultureInfo.InvariantCulture); // maximumValue is smaller than the enum value if (maximumValue.CompareTo(tempValue) == -1) maximumValue = tempValue; } } return (TEnumType)Convert.ChangeType(maximumValue, typeof(TEnumType), CultureInfo.InvariantCulture); } } } #endif
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Created by Alex Maitland, maitlandalex@gmail.com */ using NUnit.Framework; using Google.GData.Analytics; using System; namespace Google.GData.Client.UnitTests.Analytics { /// <summary> ///This is a test class for DataQueryTest and is intended ///to contain all DataQueryTest Unit Tests ///</summary> [TestFixture, Category("Analytics")] public class DataQueryTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } /// <summary> ///A test for Dimensions property ///</summary> [Test] public void DimensionPropertyTest() { DataQuery target = new DataQuery(); const string expected = "ga:productCategory,ga:productName"; target.Dimensions = expected; string actual = target.Dimensions; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Dimensions parsing ///</summary> [Test] public void DimensionParseTest() { const string expected = "ga:productCategory,ga:productName"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?dimensions=" + expected); string actual = target.Dimensions; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Metric parsing ///</summary> [Test] public void MetricParseTest() { const string expected = "ga:itemRevenue,ga:itemQuantity"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?metrics=" + expected); string actual = target.Metrics; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Ids parsing ///</summary> [Test] public void IdsParseTest() { const string expected = "ga:1234"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?ids=" + expected); string actual = target.Ids; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Filters parsing ///</summary> [Test] public void FiltersParseTest() { const string expected = "ga:country%3D%3DCanada"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?filters=" + expected); string actual = target.Filters; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Dynamic Advanced-Segment parsing ///</summary> [Test] public void DynamicSegmentParseTest() { const string expected = "dynamic::ga:country%3D%3DCanada"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?segment=" + expected); string actual = target.Segment; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Indexed Advanced-Segment parsing (Advanced Segments saved via web interface) ///</summary> [Test] public void IndexedSegmentParseTest() { const string expected = "gaid::-2"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?segment=" + expected); string actual = target.Segment; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Sort parsing ///</summary> [Test] public void SortParseTest() { const string expected = "ga:productCategory"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?sort=" + expected); string actual = target.Sort; Assert.AreEqual(expected, actual); } /// <summary> ///A test for GAStartDate parsing ///</summary> [Test] public void GAStartDateParseTest() { const string expected = "2009-04-1"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?start-date=" + expected); string actual = target.GAStartDate; Assert.AreEqual(expected, actual); } /// <summary> ///A test for GAEndDate parsing ///</summary> [Test] public void GAEndDateParseTest() { const string expected = "2009-04-25"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?end-date=" + expected); string actual = target.GAEndDate; Assert.AreEqual(expected, actual); } /// <summary> /// A test for parsing of a complete query /// Parse complete query URL and check the results ///</summary> [Test] public void ParseTest() { const string dimensionExpected = "ga:productCategory,ga:productName"; const string metricExpected = "ga:itemRevenue,ga:itemQuantity"; const string idsExpected = "ga:1234"; const string filtersExpected = "ga:country%3D%3DCanada"; const string sortExpected = "ga:productCategory"; const string startDateExpected = "2009-04-1"; const string endDateExpected = "2009-04-25"; DataQuery target = new DataQuery(); target.Uri = new Uri(string.Format("http://test.com?ids={0}&dimensions={1}&metrics={2}&filters={3}&sort={4}&start-date={5}&end-date={6}", idsExpected, dimensionExpected, metricExpected, filtersExpected, sortExpected, startDateExpected, endDateExpected)); Assert.AreEqual("http://test.com/", target.BaseAddress); Assert.AreEqual(dimensionExpected, target.Dimensions); Assert.AreEqual(metricExpected, target.Metrics); Assert.AreEqual(idsExpected, target.Ids); Assert.AreEqual(filtersExpected, target.Filters); Assert.AreEqual(sortExpected, target.Sort); Assert.AreEqual(startDateExpected, target.GAStartDate); Assert.AreEqual(endDateExpected, target.GAEndDate); } /// <summary> /// A test for calculating the query by setting the paramaters /// Parse complete query URL and check the results ///</summary> [Test] public void CalculateQueryTest() { const string baseUrlExpected = "http://test.com/"; const string dimensionExpected = "ga:productCategory,ga:productName"; const string metricExpected = "ga:itemRevenue,ga:itemQuantity"; const string idsExpected = "ga:1234"; const string filtersExpected = "ga:country%3D%3DCanada"; const string sortExpected = "ga:productCategory"; const string startDateExpected = "2009-04-1"; const string endDateExpected = "2009-04-25"; DataQuery target = new DataQuery(); target.BaseAddress = baseUrlExpected; target.Dimensions = dimensionExpected; target.Metrics = metricExpected; target.Ids = idsExpected; target.Filters = filtersExpected; target.Sort = sortExpected; target.GAStartDate = startDateExpected; target.GAEndDate = endDateExpected; Uri expectedResult = new Uri(string.Format("http://test.com?dimensions={0}&end-date={1}&filters={2}&ids={3}&metrics={4}&sort={5}&start-date={6}", Utilities.UriEncodeReserved(dimensionExpected), Utilities.UriEncodeReserved(endDateExpected), Utilities.UriEncodeReserved(filtersExpected), Utilities.UriEncodeReserved(idsExpected), Utilities.UriEncodeReserved(metricExpected), Utilities.UriEncodeReserved(sortExpected), Utilities.UriEncodeReserved(startDateExpected))); Assert.AreEqual(expectedResult.AbsoluteUri, target.Uri.AbsoluteUri); } /// <summary> ///A test for Uri ///</summary> [Test] public void UriTest() { DataQuery target = new DataQuery(); Uri expected = new Uri("http://www.test.com/"); Uri actual; target.Uri = expected; actual = target.Uri; Assert.AreEqual(expected, actual); } /// <summary> ///A test for StartDate ///</summary> [Test] public void StartDateTest() { DataQuery target = new DataQuery(); DateTime expected = DateTime.Now; DateTime actual; target.StartDate = expected; actual = target.StartDate; Assert.AreEqual(expected, actual); } /// <summary> ///A test for Query ///</summary> [Test] public void QueryTest() { DataQuery target = new DataQuery(); string expected = "TestValue"; string actual; target.Query = expected; actual = target.Query; Assert.AreEqual(expected, actual); } /// <summary> ///A test for NumberToRetrieve ///</summary> [Test] public void NumberToRetrieveTest() { DataQuery target = new DataQuery(); int expected = 12; int actual; target.NumberToRetrieve = expected; actual = target.NumberToRetrieve; Assert.AreEqual(expected, actual); } /// <summary> ///A test for ExtraParameters ///</summary> [Test] public void ExtraParametersTest() { DataQuery target = new DataQuery(); string expected = "TestValue"; string actual; target.ExtraParameters = expected; actual = target.ExtraParameters; Assert.AreEqual(expected, actual); } /// <summary> ///A test for EndDate ///</summary> [Test] public void EndDateTest() { DataQuery target = new DataQuery(); DateTime expected = DateTime.Now; DateTime actual; target.EndDate = expected; actual = target.EndDate; Assert.AreEqual(expected, actual); } /// <summary> ///A test for DataQuery Constructor ///</summary> [Test] public void DataQueryConstructorTest1() { DataQuery target = new DataQuery(); Assert.IsNotNull(target); } /// <summary> ///A test for DataQuery Constructor ///</summary> [Test] public void FeedQueryConstructorTest() { const string baseUri = "http://www.test.com/"; DataQuery target = new DataQuery(baseUri); Assert.AreEqual(target.Uri, new Uri(baseUri)); } } }
/* * * (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. * */ using System; using System.Threading; using System.Web; using System.Web.UI; using ASC.Core; using ASC.Core.Users; using ASC.MessagingSystem; using ASC.Web.Core; using ASC.Web.Studio.Core.SMS; using ASC.Web.Studio.Core.TFA; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.Utility; using Constants = ASC.Core.Users.Constants; namespace ASC.Web.Studio.UserControls.Management { public partial class ConfirmActivation : UserControl { public static string Location { get { return "~/UserControls/Management/ConfirmActivation/ConfirmActivation.ascx"; } } private UserInfo User { get; set; } protected ConfirmType Type { get; set; } protected bool isPersonal { get { return CoreContext.Configuration.Personal; } } protected void Page_Load(object sender, EventArgs e) { Page.RegisterBodyScripts( "~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmActivation/js/confirmactivation.js") .RegisterStyle("~/UserControls/Management/ConfirmActivation/css/confirmactivation.less"); Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization); var email = (Request["email"] ?? "").Trim(); if (string.IsNullOrEmpty(email)) { ShowError(Resource.ErrorNotCorrectEmail); return; } Type = typeof(ConfirmType).TryParseEnum(Request["type"] ?? "", ConfirmType.EmpInvite); try { if (Type == ConfirmType.EmailChange) { User = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); User.Email = email; CoreContext.UserManager.SaveUserInfo(User); MessageService.Send(Request, MessageAction.UserUpdatedEmail); ActivateMail(User); const string successParam = "email_change=success"; CookiesManager.ResetUserCookie(); if (User.IsVisitor()) { Response.Redirect(CommonLinkUtility.ToAbsolute("~/My.aspx?" + successParam), true); } Response.Redirect(string.Format("{0}&{1}", User.GetUserProfilePageURL(), successParam), true); return; } User = CoreContext.UserManager.GetUserByEmail(email); if (User.ID.Equals(Constants.LostUser.ID)) { ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email)); return; } if (!User.ID.Equals(SecurityContext.CurrentAccount.ID)) { Auth.ProcessLogout(); } UserAuth(User); ActivateMail(User); passwordSetter.Visible = true; ButtonEmailAndPasswordOK.Text = Resource.EmailAndPasswordOK; } catch (ThreadAbortException) { } catch (Exception ex) { ShowError(ex.Message); } if (IsPostBack) { LoginToPortal(); } } private void UserAuth(UserInfo user) { if (SecurityContext.IsAuthenticated) return; if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable) { Session["refererURL"] = Request.GetUrlRewriter().AbsoluteUri; Response.Redirect(Confirm.SmsConfirmUrl(user), true); return; } if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable) { Session["refererURL"] = Request.GetUrlRewriter().AbsoluteUri; Response.Redirect(Confirm.TfaConfirmUrl(user), true); return; } var cookiesKey = SecurityContext.AuthenticateMe(user.ID); CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey); MessageService.Send(Request, MessageAction.LoginSuccess); } private void ActivateMail(UserInfo user) { if (user.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated)) return; user.ActivationStatus = EmployeeActivationStatus.Activated; CoreContext.UserManager.SaveUserInfo(user); MessageService.Send(Request, user.IsVisitor() ? MessageAction.GuestActivated : MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false)); } private void ShowError(string message, bool redirect = true) { var confirm = Page as Confirm; if (confirm != null) confirm.ErrorMessage = HttpUtility.HtmlEncode(message); Auth.ProcessLogout(); if (redirect) RegisterRedirect(); } private void RegisterRedirect() { Page.ClientScript.RegisterStartupScript(GetType(), "redirect", string.Format("setTimeout('location.href = \"{0}\";',10000);", CommonLinkUtility.GetDefault()), true); } protected void LoginToPortal() { try { var passwordHash = Request["passwordHash"]; if (string.IsNullOrEmpty(passwordHash)) throw new Exception(Resource.ErrorPasswordEmpty); SecurityContext.SetUserPasswordHash(User.ID, passwordHash); MessageService.Send(Request, MessageAction.UserUpdatedPassword); CookiesManager.ResetUserCookie(); MessageService.Send(Request, MessageAction.CookieSettingsUpdated); } catch (SecurityContext.PasswordException) { ShowError(Resource.ErrorPasswordRechange, false); return; } catch (Exception ex) { ShowError(ex.Message, false); return; } Response.Redirect(CommonLinkUtility.GetDefault()); } } }
// 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 gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcdv = Google.Cloud.Dialogflow.V2; using sys = System; namespace Google.Cloud.Dialogflow.V2 { /// <summary>Resource name for the <c>Conversation</c> resource.</summary> public sealed partial class ConversationName : gax::IResourceName, sys::IEquatable<ConversationName> { /// <summary>The possible contents of <see cref="ConversationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/conversations/{conversation}</c>.</summary> ProjectConversation = 1, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/conversations/{conversation}</c> /// . /// </summary> ProjectLocationConversation = 2, } private static gax::PathTemplate s_projectConversation = new gax::PathTemplate("projects/{project}/conversations/{conversation}"); private static gax::PathTemplate s_projectLocationConversation = new gax::PathTemplate("projects/{project}/locations/{location}/conversations/{conversation}"); /// <summary>Creates a <see cref="ConversationName"/> 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="ConversationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ConversationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ConversationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ConversationName"/> with the pattern <c>projects/{project}/conversations/{conversation}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConversationName"/> constructed from the provided ids.</returns> public static ConversationName FromProjectConversation(string projectId, string conversationId) => new ConversationName(ResourceNameType.ProjectConversation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId))); /// <summary> /// Creates a <see cref="ConversationName"/> with the pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConversationName"/> constructed from the provided ids.</returns> public static ConversationName FromProjectLocationConversation(string projectId, string locationId, string conversationId) => new ConversationName(ResourceNameType.ProjectLocationConversation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/conversations/{conversation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/conversations/{conversation}</c>. /// </returns> public static string Format(string projectId, string conversationId) => FormatProjectConversation(projectId, conversationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/conversations/{conversation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/conversations/{conversation}</c>. /// </returns> public static string FormatProjectConversation(string projectId, string conversationId) => s_projectConversation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConversationName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}</c>. /// </returns> public static string FormatProjectLocationConversation(string projectId, string locationId, string conversationId) => s_projectLocationConversation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId))); /// <summary>Parses the given resource name string into a new <see cref="ConversationName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/conversations/{conversation}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/conversations/{conversation}</c></description> /// </item> /// </list> /// </remarks> /// <param name="conversationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ConversationName"/> if successful.</returns> public static ConversationName Parse(string conversationName) => Parse(conversationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ConversationName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/conversations/{conversation}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/conversations/{conversation}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversationName">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="ConversationName"/> if successful.</returns> public static ConversationName Parse(string conversationName, bool allowUnparsed) => TryParse(conversationName, allowUnparsed, out ConversationName 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="ConversationName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/conversations/{conversation}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/conversations/{conversation}</c></description> /// </item> /// </list> /// </remarks> /// <param name="conversationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConversationName"/>, 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 conversationName, out ConversationName result) => TryParse(conversationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConversationName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/conversations/{conversation}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/conversations/{conversation}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversationName">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="ConversationName"/>, 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 conversationName, bool allowUnparsed, out ConversationName result) { gax::GaxPreconditions.CheckNotNull(conversationName, nameof(conversationName)); gax::TemplatedResourceName resourceName; if (s_projectConversation.TryParseName(conversationName, out resourceName)) { result = FromProjectConversation(resourceName[0], resourceName[1]); return true; } if (s_projectLocationConversation.TryParseName(conversationName, out resourceName)) { result = FromProjectLocationConversation(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(conversationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ConversationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversationId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversationId = conversationId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ConversationName"/> class from the component parts of pattern /// <c>projects/{project}/conversations/{conversation}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> public ConversationName(string projectId, string conversationId) : this(ResourceNameType.ProjectConversation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId))) { } /// <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>Conversation</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConversationId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { 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.ProjectConversation: return s_projectConversation.Expand(ProjectId, ConversationId); case ResourceNameType.ProjectLocationConversation: return s_projectLocationConversation.Expand(ProjectId, LocationId, ConversationId); 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 ConversationName); /// <inheritdoc/> public bool Equals(ConversationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ConversationName a, ConversationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ConversationName a, ConversationName b) => !(a == b); } public partial class Conversation { /// <summary> /// <see cref="gcdv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ConversationName ConversationName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ConversationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="ConversationProfileName"/>-typed view over the <see cref="ConversationProfile"/> resource name /// property. /// </summary> public ConversationProfileName ConversationProfileAsConversationProfileName { get => string.IsNullOrEmpty(ConversationProfile) ? null : ConversationProfileName.Parse(ConversationProfile, allowUnparsed: true); set => ConversationProfile = value?.ToString() ?? ""; } } public partial class CreateConversationRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location)) { return location; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class ListConversationsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location)) { return location; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class GetConversationRequest { /// <summary> /// <see cref="gcdv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ConversationName ConversationName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ConversationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CompleteConversationRequest { /// <summary> /// <see cref="gcdv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ConversationName ConversationName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ConversationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListMessagesRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Data.ProviderBase { // DbBuffer is abstract to require derived class to exist // so that when debugging, we can tell the difference between one DbBuffer and another internal abstract class DbBuffer : SafeHandle { internal const int LMEM_FIXED = 0x0000; internal const int LMEM_MOVEABLE = 0x0002; internal const int LMEM_ZEROINIT = 0x0040; private readonly int _bufferLength; private DbBuffer(int initialSize, bool zeroBuffer) : base(IntPtr.Zero, true) { if (0 < initialSize) { int flags = ((zeroBuffer) ? LMEM_ZEROINIT : LMEM_FIXED); _bufferLength = initialSize; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { base.handle = SafeNativeMethods.LocalAlloc(flags, (IntPtr)initialSize); } if (IntPtr.Zero == base.handle) { throw new OutOfMemoryException(); } } } protected DbBuffer(int initialSize) : this(initialSize, true) { } protected DbBuffer(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) { } private int BaseOffset { get { return 0; } } public override bool IsInvalid { get { return (IntPtr.Zero == base.handle); } } internal int Length { get { return _bufferLength; } } internal string PtrToStringUni(int offset, int length) { offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); string value = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); value = Marshal.PtrToStringUni(ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal byte ReadByte(int offset) { offset += BaseOffset; ValidateCheck(offset, 1); Debug.Assert(0 == offset % 4, "invalid alignment"); byte value; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); value = Marshal.ReadByte(ptr, offset); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal byte[] ReadBytes(int offset, int length) { byte[] value = new byte[length]; return ReadBytes(offset, value, 0, length); } internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int length) { offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(ptr, destination, startIndex, length); } finally { if (mustRelease) { DangerousRelease(); } } return destination; } internal char ReadChar(int offset) { short value = ReadInt16(offset); return unchecked((char)value); } internal char[] ReadChars(int offset, char[] destination, int startIndex, int length) { offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(ptr, destination, startIndex, length); } finally { if (mustRelease) { DangerousRelease(); } } return destination; } internal double ReadDouble(int offset) { long value = ReadInt64(offset); return BitConverter.Int64BitsToDouble(value); } internal short ReadInt16(int offset) { offset += BaseOffset; ValidateCheck(offset, 2); Debug.Assert(0 == offset % 2, "invalid alignment"); short value; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); value = Marshal.ReadInt16(ptr, offset); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal void ReadInt16Array(int offset, short[] destination, int startIndex, int length) { offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(ptr, destination, startIndex, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal int ReadInt32(int offset) { offset += BaseOffset; ValidateCheck(offset, 4); Debug.Assert(0 == offset % 4, "invalid alignment"); int value; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); value = Marshal.ReadInt32(ptr, offset); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal void ReadInt32Array(int offset, int[] destination, int startIndex, int length) { offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != destination, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(ptr, destination, startIndex, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal long ReadInt64(int offset) { offset += BaseOffset; ValidateCheck(offset, 8); Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment"); long value; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); value = Marshal.ReadInt64(ptr, offset); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal IntPtr ReadIntPtr(int offset) { offset += BaseOffset; ValidateCheck(offset, IntPtr.Size); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); IntPtr value; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); value = Marshal.ReadIntPtr(ptr, offset); } finally { if (mustRelease) { DangerousRelease(); } } return value; } internal unsafe float ReadSingle(int offset) { int value = ReadInt32(offset); return *(float*)&value; } protected override bool ReleaseHandle() { // NOTE: The SafeHandle class guarantees this will be called exactly once. IntPtr ptr = base.handle; base.handle = IntPtr.Zero; if (IntPtr.Zero != ptr) { SafeNativeMethods.LocalFree(ptr); } return true; } private void StructureToPtr(int offset, object structure) { Debug.Assert(null != structure, "null structure"); offset += BaseOffset; ValidateCheck(offset, Marshal.SizeOf(structure.GetType())); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.StructureToPtr(structure, ptr, false/*fDeleteOld*/); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteByte(int offset, byte value) { offset += BaseOffset; ValidateCheck(offset, 1); Debug.Assert(0 == offset % 4, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); Marshal.WriteByte(ptr, offset, value); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteBytes(int offset, byte[] source, int startIndex, int length) { offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(source, startIndex, ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteCharArray(int offset, char[] source, int startIndex, int length) { offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(source, startIndex, ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteDouble(int offset, double value) { WriteInt64(offset, BitConverter.DoubleToInt64Bits(value)); } internal void WriteInt16(int offset, short value) { offset += BaseOffset; ValidateCheck(offset, 2); Debug.Assert(0 == offset % 2, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); Marshal.WriteInt16(ptr, offset, value); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteInt16Array(int offset, short[] source, int startIndex, int length) { offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(source, startIndex, ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteInt32(int offset, int value) { offset += BaseOffset; ValidateCheck(offset, 4); Debug.Assert(0 == offset % 4, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); Marshal.WriteInt32(ptr, offset, value); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteInt32Array(int offset, int[] source, int startIndex, int length) { offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment"); Debug.Assert(null != source, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); Marshal.Copy(source, startIndex, ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteInt64(int offset, long value) { offset += BaseOffset; ValidateCheck(offset, 8); Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); Marshal.WriteInt64(ptr, offset, value); } finally { if (mustRelease) { DangerousRelease(); } } } internal void WriteIntPtr(int offset, IntPtr value) { offset += BaseOffset; ValidateCheck(offset, IntPtr.Size); Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment"); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); Marshal.WriteIntPtr(ptr, offset, value); } finally { if (mustRelease) { DangerousRelease(); } } } internal unsafe void WriteSingle(int offset, float value) { WriteInt32(offset, *(int*)&value); } internal Guid ReadGuid(int offset) { // faster than Marshal.PtrToStructure(offset, typeof(Guid)) byte[] buffer = new byte[16]; ReadBytes(offset, buffer, 0, 16); return new Guid(buffer); } internal void WriteGuid(int offset, Guid value) { // faster than Marshal.Copy(value.GetByteArray() StructureToPtr(offset, value); } internal DateTime ReadDate(int offset) { short[] buffer = new short[3]; ReadInt16Array(offset, buffer, 0, 3); return new DateTime( unchecked((ushort)buffer[0]), // Year unchecked((ushort)buffer[1]), // Month unchecked((ushort)buffer[2])); // Day } internal void WriteDate(int offset, DateTime value) { short[] buffer = new short[3] { unchecked((short)value.Year), unchecked((short)value.Month), unchecked((short)value.Day), }; WriteInt16Array(offset, buffer, 0, 3); } internal TimeSpan ReadTime(int offset) { short[] buffer = new short[3]; ReadInt16Array(offset, buffer, 0, 3); return new TimeSpan( unchecked((ushort)buffer[0]), // Hours unchecked((ushort)buffer[1]), // Minutes unchecked((ushort)buffer[2])); // Seconds } internal void WriteTime(int offset, TimeSpan value) { short[] buffer = new short[3] { unchecked((short)value.Hours), unchecked((short)value.Minutes), unchecked((short)value.Seconds), }; WriteInt16Array(offset, buffer, 0, 3); } internal DateTime ReadDateTime(int offset) { short[] buffer = new short[6]; ReadInt16Array(offset, buffer, 0, 6); int ticks = ReadInt32(offset + 12); DateTime value = new DateTime( unchecked((ushort)buffer[0]), // Year unchecked((ushort)buffer[1]), // Month unchecked((ushort)buffer[2]), // Day unchecked((ushort)buffer[3]), // Hours unchecked((ushort)buffer[4]), // Minutes unchecked((ushort)buffer[5])); // Seconds return value.AddTicks(ticks / 100); } internal void WriteDateTime(int offset, DateTime value) { int ticks = (int)(value.Ticks % 10000000L) * 100; short[] buffer = new short[6] { unchecked((short)value.Year), unchecked((short)value.Month), unchecked((short)value.Day), unchecked((short)value.Hour), unchecked((short)value.Minute), unchecked((short)value.Second), }; WriteInt16Array(offset, buffer, 0, 6); WriteInt32(offset + 12, ticks); } internal decimal ReadNumeric(int offset) { byte[] bits = new byte[20]; ReadBytes(offset, bits, 1, 19); int[] buffer = new int[4]; buffer[3] = ((int)bits[2]) << 16; // scale if (0 == bits[3]) { buffer[3] |= unchecked((int)0x80000000); //sign } buffer[0] = BitConverter.ToInt32(bits, 4); // low buffer[1] = BitConverter.ToInt32(bits, 8); // mid buffer[2] = BitConverter.ToInt32(bits, 12); // high if (0 != BitConverter.ToInt32(bits, 16)) { throw ADP.NumericToDecimalOverflow(); } return new decimal(buffer); } internal void WriteNumeric(int offset, decimal value, byte precision) { int[] tmp = decimal.GetBits(value); byte[] buffer = new byte[20]; buffer[1] = precision; Buffer.BlockCopy(tmp, 14, buffer, 2, 2); // copy sign and scale buffer[3] = (byte)((0 == buffer[3]) ? 1 : 0); // flip sign for native Buffer.BlockCopy(tmp, 0, buffer, 4, 12); buffer[16] = 0; buffer[17] = 0; buffer[18] = 0; buffer[19] = 0; WriteBytes(offset, buffer, 1, 19); } [Conditional("DEBUG")] protected void ValidateCheck(int offset, int count) { Validate(offset, count); } protected void Validate(int offset, int count) { if ((offset < 0) || (count < 0) || (Length < checked(offset + count))) { throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer); } } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Input; using IRTaktiks.Input.EventArgs; using IRTaktiks.Components.Playable; using IRTaktiks.Components.Logic; using IRTaktiks.Components.Manager; using IRTaktiks.Components.Config; namespace IRTaktiks.Components.Screen { /// <summary> /// Config screen of the game. /// </summary> public class ConfigScreen : IScreen { #region Properties /// <summary> /// The configuration manager of the player one. /// </summary> private ConfigurationManager PlayerOneConfigurationManagerField; /// <summary> /// The configuration manager of the player one. /// </summary> public ConfigurationManager PlayerOneConfigurationManager { get { return PlayerOneConfigurationManagerField; } set { PlayerOneConfigurationManagerField = value; } } /// <summary> /// The configuration manager of the player two. /// </summary> private ConfigurationManager PlayerTwoConfigurationManagerField; /// <summary> /// The configuration manager of the player two. /// </summary> public ConfigurationManager PlayerTwoConfigurationManager { get { return PlayerTwoConfigurationManagerField; } set { PlayerTwoConfigurationManagerField = value; } } /// <summary> /// Indicates that the player one done its configuration. /// </summary> private bool PlayerOneConfigurated; /// <summary> /// Indicates that the player two done its configuration. /// </summary> private bool PlayerTwoConfigurated; #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> /// <param name="game">The instance of game that is running.</param> /// <param name="priority">Drawing priority of screen. Higher indicates that the screen will be at the top of the others.</param> public ConfigScreen(Game game, int priority) : base(game, priority) { this.PlayerOneConfigurationManagerField = new ConfigurationManager(game, PlayerIndex.One); this.PlayerTwoConfigurationManagerField = new ConfigurationManager(game, PlayerIndex.Two); this.PlayerOneConfigurated = false; this.PlayerTwoConfigurated = false; this.PlayerOneConfigurationManager.Configurated += new ConfigurationManager.ConfiguratedEventHandler(PlayerOne_Configurated); this.PlayerTwoConfigurationManager.Configurated += new ConfigurationManager.ConfiguratedEventHandler(PlayerTwo_Configurated); } #endregion #region Component Methods /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // Configuration managers this.Components.Add(this.PlayerOneConfigurationManager); this.Components.Add(this.PlayerTwoConfigurationManager); // Player one configuration items. this.Components.Add(this.PlayerOneConfigurationManager.Keyboard); this.Components.Add(this.PlayerOneConfigurationManager.PlayerConfig); for (int index = 0; index < this.PlayerOneConfigurationManager.UnitsConfig.Count; index++) { this.Components.Add(this.PlayerOneConfigurationManager.UnitsConfig[index]); } // Player two configuration items. this.Components.Add(this.PlayerTwoConfigurationManager.Keyboard); this.Components.Add(this.PlayerTwoConfigurationManager.PlayerConfig); for (int index = 0; index < this.PlayerTwoConfigurationManager.UnitsConfig.Count; index++) { this.Components.Add(this.PlayerTwoConfigurationManager.UnitsConfig[index]); } // Shows the map. IRTGame game = this.Game as IRTGame; game.MapManager.Visible = true; base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { if (this.PlayerOneConfigurated && this.PlayerTwoConfigurated) { this.ConfigGame(); (this.Game as IRTGame).ChangeScreen(IRTGame.GameScreens.GameScreen); } base.Update(gameTime); } /// <summary> /// Called when the DrawableGameComponent needs to be drawn. Override this method /// with component-specific drawing code. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { base.Draw(gameTime); } #endregion #region Methods /// <summary> /// Configure the game, creating all players and its units. /// </summary> private void ConfigGame() { IRTGame game = this.Game as IRTGame; game.PlayerOne = this.ConfigPlayer(this.PlayerOneConfigurationManager); game.PlayerTwo = this.ConfigPlayer(this.PlayerTwoConfigurationManager); } /// <summary> /// Configure one player, based on the given ConfigurationManager informations. /// </summary> /// <param name="configurationManager">The ConfigurationManager used to configure the player.</param> /// <returns>One player with its units configured.</returns> private Player ConfigPlayer(ConfigurationManager configurationManager) { Player player = new Player(this.Game, configurationManager.PlayerConfig.DisplayText.ToString(), configurationManager.PlayerIndex); for (int index = 0; index < configurationManager.UnitsConfig.Count; index++) { Attributes unitAttribute = new Attributes( IRTSettings.Default.BaseLevel, Character.Instance[configurationManager.UnitsConfig[index].CharacterIndex].Job, Element.Holy, configurationManager.UnitsConfig[index].Strength, configurationManager.UnitsConfig[index].Agility, configurationManager.UnitsConfig[index].Vitality, configurationManager.UnitsConfig[index].Inteligence, configurationManager.UnitsConfig[index].Dexterity ); string unitName = configurationManager.UnitsConfig[index].DisplayText.ToString(); Texture2D unitTexture = Character.Instance[configurationManager.UnitsConfig[index].CharacterIndex].Texture; Vector2 unitPosition = default(Vector2); Orientation unitOrientation = default(Orientation); switch (configurationManager.PlayerIndex) { case PlayerIndex.One: unitPosition = new Vector2((TextureManager.Instance.Sprites.Menu.Background.Width + 50), TextureManager.Instance.Sprites.Menu.Background.Width + (index * 60)); unitOrientation = Orientation.Right; break; case PlayerIndex.Two: unitPosition = new Vector2(IRTSettings.Default.Width - (TextureManager.Instance.Sprites.Menu.Background.Width + 50), TextureManager.Instance.Sprites.Menu.Background.Width + (index * 60)); unitOrientation = Orientation.Left; break; } Unit unit = new Unit(this.Game, player, unitPosition, unitAttribute, unitOrientation, unitTexture, unitName); player.Units.Add(unit); } return player; } #endregion #region Event Handling /// <summary> /// Executes when the player one done its configuration. /// </summary> private void PlayerOne_Configurated() { this.PlayerOneConfigurated = true; this.PlayerOneConfigurationManager.Unregister(); this.PlayerOneConfigurationManager.Keyboard.Unregister(); this.PlayerOneConfigurationManager.PlayerConfig.Unregister(); for (int index = 0; index < this.PlayerOneConfigurationManager.UnitsConfig.Count; index++) { this.PlayerOneConfigurationManager.UnitsConfig[index].Unregister(); } } /// <summary> /// Executes when the player two done its configuration. /// </summary> private void PlayerTwo_Configurated() { this.PlayerTwoConfigurated = true; this.PlayerTwoConfigurationManager.Unregister(); this.PlayerTwoConfigurationManager.Keyboard.Unregister(); this.PlayerTwoConfigurationManager.PlayerConfig.Unregister(); for (int index = 0; index < this.PlayerTwoConfigurationManager.UnitsConfig.Count; index++) { this.PlayerTwoConfigurationManager.UnitsConfig[index].Unregister(); } } #endregion } }
using System; using System.Runtime.CompilerServices; using System.Collections.Generic; using Sannel.House.Thermostat.Base.Models; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; using System.Text; using Sannel.House.Thermostat.Base.Enums; namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIDataContext : IDataContext { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); global::Microsoft.EntityFrameworkCore.DbSet<global::Sannel.House.Thermostat.Base.Models.Device> global::Sannel.House.Thermostat.Base.Interfaces.IDataContext.Devices { get { return ((Devices_Get_Delegate)_stubs[nameof(Devices_Get_Delegate)]).Invoke(); } set { ((Devices_Set_Delegate)_stubs[nameof(Devices_Set_Delegate)]).Invoke(value); } } public delegate global::Microsoft.EntityFrameworkCore.DbSet<global::Sannel.House.Thermostat.Base.Models.Device> Devices_Get_Delegate(); public StubIDataContext Devices_Get(Devices_Get_Delegate del) { _stubs[nameof(Devices_Get_Delegate)] = del; return this; } public delegate void Devices_Set_Delegate(global::Microsoft.EntityFrameworkCore.DbSet<global::Sannel.House.Thermostat.Base.Models.Device> value); public StubIDataContext Devices_Set(Devices_Set_Delegate del) { _stubs[nameof(Devices_Set_Delegate)] = del; return this; } int global::Sannel.House.Thermostat.Base.Interfaces.IDataContext.SaveChanges() { return ((SaveChanges_Delegate)_stubs[nameof(SaveChanges_Delegate)]).Invoke(); } public delegate int SaveChanges_Delegate(); public StubIDataContext SaveChanges(SaveChanges_Delegate del) { _stubs[nameof(SaveChanges_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<int> global::Sannel.House.Thermostat.Base.Interfaces.IDataContext.SaveChangesAsync(global::System.Threading.CancellationToken cancellationToken) { return ((SaveChangesAsync_CancellationTokenCancellationToken_Delegate)_stubs[nameof(SaveChangesAsync_CancellationTokenCancellationToken_Delegate)]).Invoke(cancellationToken); } public delegate global::System.Threading.Tasks.Task<int> SaveChangesAsync_CancellationTokenCancellationToken_Delegate(global::System.Threading.CancellationToken cancellationToken); public StubIDataContext SaveChangesAsync(SaveChangesAsync_CancellationTokenCancellationToken_Delegate del) { _stubs[nameof(SaveChangesAsync_CancellationTokenCancellationToken_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIDataContext Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIAppSettings : IAppSettings { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); string global::Sannel.House.Thermostat.Base.Interfaces.IAppSettings.ServerUrl { get { return ((ServerUrl_Get_Delegate)_stubs[nameof(ServerUrl_Get_Delegate)]).Invoke(); } set { ((ServerUrl_Set_Delegate)_stubs[nameof(ServerUrl_Set_Delegate)]).Invoke(value); } } public delegate string ServerUrl_Get_Delegate(); public StubIAppSettings ServerUrl_Get(ServerUrl_Get_Delegate del) { _stubs[nameof(ServerUrl_Get_Delegate)] = del; return this; } public delegate void ServerUrl_Set_Delegate(string value); public StubIAppSettings ServerUrl_Set(ServerUrl_Set_Delegate del) { _stubs[nameof(ServerUrl_Set_Delegate)] = del; return this; } string global::Sannel.House.Thermostat.Base.Interfaces.IAppSettings.Username { get { return ((Username_Get_Delegate)_stubs[nameof(Username_Get_Delegate)]).Invoke(); } set { ((Username_Set_Delegate)_stubs[nameof(Username_Set_Delegate)]).Invoke(value); } } public delegate string Username_Get_Delegate(); public StubIAppSettings Username_Get(Username_Get_Delegate del) { _stubs[nameof(Username_Get_Delegate)] = del; return this; } public delegate void Username_Set_Delegate(string value); public StubIAppSettings Username_Set(Username_Set_Delegate del) { _stubs[nameof(Username_Set_Delegate)] = del; return this; } string global::Sannel.House.Thermostat.Base.Interfaces.IAppSettings.Password { get { return ((Password_Get_Delegate)_stubs[nameof(Password_Get_Delegate)]).Invoke(); } set { ((Password_Set_Delegate)_stubs[nameof(Password_Set_Delegate)]).Invoke(value); } } public delegate string Password_Get_Delegate(); public StubIAppSettings Password_Get(Password_Get_Delegate del) { _stubs[nameof(Password_Get_Delegate)] = del; return this; } public delegate void Password_Set_Delegate(string value); public StubIAppSettings Password_Set(Password_Set_Delegate del) { _stubs[nameof(Password_Set_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIHumiditySensor : IHumiditySensor { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.IHumiditySensor.GetHumidityAsync() { return ((GetHumidityAsync_Delegate)_stubs[nameof(GetHumidityAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> GetHumidityAsync_Delegate(); public StubIHumiditySensor GetHumidityAsync(GetHumidityAsync_Delegate del) { _stubs[nameof(GetHumidityAsync_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((ISmallDevice_IsInitalized_Get_Delegate)_stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool ISmallDevice_IsInitalized_Get_Delegate(); public StubIHumiditySensor IsInitalized_Get(ISmallDevice_IsInitalized_Get_Delegate del) { _stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((ISmallDevice_InitializeAsync_Delegate)_stubs[nameof(ISmallDevice_InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> ISmallDevice_InitializeAsync_Delegate(); public StubIHumiditySensor InitializeAsync(ISmallDevice_InitializeAsync_Delegate del) { _stubs[nameof(ISmallDevice_InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIHumiditySensor Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIPressureSensor : IPressureSensor { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.IPressureSensor.GetPressureAsync() { return ((GetPressureAsync_Delegate)_stubs[nameof(GetPressureAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> GetPressureAsync_Delegate(); public StubIPressureSensor GetPressureAsync(GetPressureAsync_Delegate del) { _stubs[nameof(GetPressureAsync_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((ISmallDevice_IsInitalized_Get_Delegate)_stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool ISmallDevice_IsInitalized_Get_Delegate(); public StubIPressureSensor IsInitalized_Get(ISmallDevice_IsInitalized_Get_Delegate del) { _stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((ISmallDevice_InitializeAsync_Delegate)_stubs[nameof(ISmallDevice_InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> ISmallDevice_InitializeAsync_Delegate(); public StubIPressureSensor InitializeAsync(ISmallDevice_InitializeAsync_Delegate del) { _stubs[nameof(ISmallDevice_InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIPressureSensor Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIRelay : IRelay { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); bool global::Sannel.House.Thermostat.Base.Interfaces.IRelay.IsOn { get { return ((IsOn_Get_Delegate)_stubs[nameof(IsOn_Get_Delegate)]).Invoke(); } } public delegate bool IsOn_Get_Delegate(); public StubIRelay IsOn_Get(IsOn_Get_Delegate del) { _stubs[nameof(IsOn_Get_Delegate)] = del; return this; } void global::Sannel.House.Thermostat.Base.Interfaces.IRelay.TurnOn() { ((TurnOn_Delegate)_stubs[nameof(TurnOn_Delegate)]).Invoke(); } public delegate void TurnOn_Delegate(); public StubIRelay TurnOn(TurnOn_Delegate del) { _stubs[nameof(TurnOn_Delegate)] = del; return this; } void global::Sannel.House.Thermostat.Base.Interfaces.IRelay.TurnOff() { ((TurnOff_Delegate)_stubs[nameof(TurnOff_Delegate)]).Invoke(); } public delegate void TurnOff_Delegate(); public StubIRelay TurnOff(TurnOff_Delegate del) { _stubs[nameof(TurnOff_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((ISmallDevice_IsInitalized_Get_Delegate)_stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool ISmallDevice_IsInitalized_Get_Delegate(); public StubIRelay IsInitalized_Get(ISmallDevice_IsInitalized_Get_Delegate del) { _stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((ISmallDevice_InitializeAsync_Delegate)_stubs[nameof(ISmallDevice_InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> ISmallDevice_InitializeAsync_Delegate(); public StubIRelay InitializeAsync(ISmallDevice_InitializeAsync_Delegate del) { _stubs[nameof(ISmallDevice_InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIRelay Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubISmallDevice : ISmallDevice { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((IsInitalized_Get_Delegate)_stubs[nameof(IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool IsInitalized_Get_Delegate(); public StubISmallDevice IsInitalized_Get(IsInitalized_Get_Delegate del) { _stubs[nameof(IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((InitializeAsync_Delegate)_stubs[nameof(InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> InitializeAsync_Delegate(); public StubISmallDevice InitializeAsync(InitializeAsync_Delegate del) { _stubs[nameof(InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubISmallDevice Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIServerSource : IServerSource { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); bool global::Sannel.House.Thermostat.Base.Interfaces.IServerSource.IsAuthenticated { get { return ((IsAuthenticated_Get_Delegate)_stubs[nameof(IsAuthenticated_Get_Delegate)]).Invoke(); } } public delegate bool IsAuthenticated_Get_Delegate(); public StubIServerSource IsAuthenticated_Get(IsAuthenticated_Get_Delegate del) { _stubs[nameof(IsAuthenticated_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<global::Sannel.House.Thermostat.Base.Enums.LoginStatus> global::Sannel.House.Thermostat.Base.Interfaces.IServerSource.LoginAsync(string username, string password) { return ((LoginAsync_String_String_Delegate)_stubs[nameof(LoginAsync_String_String_Delegate)]).Invoke(username, password); } public delegate global::System.Threading.Tasks.Task<global::Sannel.House.Thermostat.Base.Enums.LoginStatus> LoginAsync_String_String_Delegate(string username, string password); public StubIServerSource LoginAsync(LoginAsync_String_String_Delegate del) { _stubs[nameof(LoginAsync_String_String_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<global::Sannel.House.Thermostat.Base.Models.Device>> global::Sannel.House.Thermostat.Base.Interfaces.IServerSource.GetDevicesAsync() { return ((GetDevicesAsync_Delegate)_stubs[nameof(GetDevicesAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<global::System.Collections.Generic.IList<global::Sannel.House.Thermostat.Base.Models.Device>> GetDevicesAsync_Delegate(); public StubIServerSource GetDevicesAsync(GetDevicesAsync_Delegate del) { _stubs[nameof(GetDevicesAsync_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubISyncService : ISyncService { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); public event global::System.EventHandler<global::Sannel.House.Thermostat.Base.Models.LogEventArgs> LogMessage; protected void On_LogMessage(object sender, LogEventArgs args) { global::System.EventHandler<global::Sannel.House.Thermostat.Base.Models.LogEventArgs> handler = LogMessage; if (handler != null) { handler(sender, args); } } public void LogMessage_Raise(object sender, LogEventArgs args) { On_LogMessage(sender, args); } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISyncService.LoginAsync() { return ((LoginAsync_Delegate)_stubs[nameof(LoginAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> LoginAsync_Delegate(); public StubISyncService LoginAsync(LoginAsync_Delegate del) { _stubs[nameof(LoginAsync_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISyncService.SyncDevicesAsync() { return ((SyncDevicesAsync_Delegate)_stubs[nameof(SyncDevicesAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> SyncDevicesAsync_Delegate(); public StubISyncService SyncDevicesAsync(SyncDevicesAsync_Delegate del) { _stubs[nameof(SyncDevicesAsync_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubITemperatureSensor : ITemperatureSensor { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.ITemperatureSensor.GetTemperatureCelsiusAsync() { return ((GetTemperatureCelsiusAsync_Delegate)_stubs[nameof(GetTemperatureCelsiusAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> GetTemperatureCelsiusAsync_Delegate(); public StubITemperatureSensor GetTemperatureCelsiusAsync(GetTemperatureCelsiusAsync_Delegate del) { _stubs[nameof(GetTemperatureCelsiusAsync_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.ITemperatureSensor.GetTemperatureFahrenheitAsync() { return ((GetTemperatureFahrenheitAsync_Delegate)_stubs[nameof(GetTemperatureFahrenheitAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> GetTemperatureFahrenheitAsync_Delegate(); public StubITemperatureSensor GetTemperatureFahrenheitAsync(GetTemperatureFahrenheitAsync_Delegate del) { _stubs[nameof(GetTemperatureFahrenheitAsync_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((ISmallDevice_IsInitalized_Get_Delegate)_stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool ISmallDevice_IsInitalized_Get_Delegate(); public StubITemperatureSensor IsInitalized_Get(ISmallDevice_IsInitalized_Get_Delegate del) { _stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((ISmallDevice_InitializeAsync_Delegate)_stubs[nameof(ISmallDevice_InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> ISmallDevice_InitializeAsync_Delegate(); public StubITemperatureSensor InitializeAsync(ISmallDevice_InitializeAsync_Delegate del) { _stubs[nameof(ISmallDevice_InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubITemperatureSensor Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubITempreatureHumidityPressureSensor : ITempreatureHumidityPressureSensor { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.ITemperatureSensor.GetTemperatureCelsiusAsync() { return ((ITemperatureSensor_GetTemperatureCelsiusAsync_Delegate)_stubs[nameof(ITemperatureSensor_GetTemperatureCelsiusAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> ITemperatureSensor_GetTemperatureCelsiusAsync_Delegate(); public StubITempreatureHumidityPressureSensor GetTemperatureCelsiusAsync(ITemperatureSensor_GetTemperatureCelsiusAsync_Delegate del) { _stubs[nameof(ITemperatureSensor_GetTemperatureCelsiusAsync_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.ITemperatureSensor.GetTemperatureFahrenheitAsync() { return ((ITemperatureSensor_GetTemperatureFahrenheitAsync_Delegate)_stubs[nameof(ITemperatureSensor_GetTemperatureFahrenheitAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> ITemperatureSensor_GetTemperatureFahrenheitAsync_Delegate(); public StubITempreatureHumidityPressureSensor GetTemperatureFahrenheitAsync(ITemperatureSensor_GetTemperatureFahrenheitAsync_Delegate del) { _stubs[nameof(ITemperatureSensor_GetTemperatureFahrenheitAsync_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.IHumiditySensor.GetHumidityAsync() { return ((IHumiditySensor_GetHumidityAsync_Delegate)_stubs[nameof(IHumiditySensor_GetHumidityAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> IHumiditySensor_GetHumidityAsync_Delegate(); public StubITempreatureHumidityPressureSensor GetHumidityAsync(IHumiditySensor_GetHumidityAsync_Delegate del) { _stubs[nameof(IHumiditySensor_GetHumidityAsync_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<double> global::Sannel.House.Thermostat.Base.Interfaces.IPressureSensor.GetPressureAsync() { return ((IPressureSensor_GetPressureAsync_Delegate)_stubs[nameof(IPressureSensor_GetPressureAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<double> IPressureSensor_GetPressureAsync_Delegate(); public StubITempreatureHumidityPressureSensor GetPressureAsync(IPressureSensor_GetPressureAsync_Delegate del) { _stubs[nameof(IPressureSensor_GetPressureAsync_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.IsInitalized { get { return ((ISmallDevice_IsInitalized_Get_Delegate)_stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)]).Invoke(); } } public delegate bool ISmallDevice_IsInitalized_Get_Delegate(); public StubITempreatureHumidityPressureSensor IsInitalized_Get(ISmallDevice_IsInitalized_Get_Delegate del) { _stubs[nameof(ISmallDevice_IsInitalized_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.ISmallDevice.InitializeAsync() { return ((ISmallDevice_InitializeAsync_Delegate)_stubs[nameof(ISmallDevice_InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> ISmallDevice_InitializeAsync_Delegate(); public StubITempreatureHumidityPressureSensor InitializeAsync(ISmallDevice_InitializeAsync_Delegate del) { _stubs[nameof(ISmallDevice_InitializeAsync_Delegate)] = del; return this; } void global::System.IDisposable.Dispose() { ((IDisposable_Dispose_Delegate)_stubs[nameof(IDisposable_Dispose_Delegate)]).Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubITempreatureHumidityPressureSensor Dispose(IDisposable_Dispose_Delegate del) { _stubs[nameof(IDisposable_Dispose_Delegate)] = del; return this; } } } namespace Sannel.House.Thermostat.Base.Interfaces { [CompilerGenerated] public class StubIThermostatService : IThermostatService { private readonly Dictionary<string, object> _stubs = new Dictionary<string, object>(); bool global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.HasDevices { get { return ((HasDevices_Get_Delegate)_stubs[nameof(HasDevices_Get_Delegate)]).Invoke(); } } public delegate bool HasDevices_Get_Delegate(); public StubIThermostatService HasDevices_Get(HasDevices_Get_Delegate del) { _stubs[nameof(HasDevices_Get_Delegate)] = del; return this; } global::System.Threading.Tasks.Task<bool> global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.InitializeAsync() { return ((InitializeAsync_Delegate)_stubs[nameof(InitializeAsync_Delegate)]).Invoke(); } public delegate global::System.Threading.Tasks.Task<bool> InitializeAsync_Delegate(); public StubIThermostatService InitializeAsync(InitializeAsync_Delegate del) { _stubs[nameof(InitializeAsync_Delegate)] = del; return this; } double global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.TemperatureC { get { return ((TemperatureC_Get_Delegate)_stubs[nameof(TemperatureC_Get_Delegate)]).Invoke(); } } public delegate double TemperatureC_Get_Delegate(); public StubIThermostatService TemperatureC_Get(TemperatureC_Get_Delegate del) { _stubs[nameof(TemperatureC_Get_Delegate)] = del; return this; } double global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.CoolOnTemperatureC { get { return ((CoolOnTemperatureC_Get_Delegate)_stubs[nameof(CoolOnTemperatureC_Get_Delegate)]).Invoke(); } } public delegate double CoolOnTemperatureC_Get_Delegate(); public StubIThermostatService CoolOnTemperatureC_Get(CoolOnTemperatureC_Get_Delegate del) { _stubs[nameof(CoolOnTemperatureC_Get_Delegate)] = del; return this; } double global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.HeatOnTemperatureC { get { return ((HeatOnTemperatureC_Get_Delegate)_stubs[nameof(HeatOnTemperatureC_Get_Delegate)]).Invoke(); } } public delegate double HeatOnTemperatureC_Get_Delegate(); public StubIThermostatService HeatOnTemperatureC_Get(HeatOnTemperatureC_Get_Delegate del) { _stubs[nameof(HeatOnTemperatureC_Get_Delegate)] = del; return this; } bool global::Sannel.House.Thermostat.Base.Interfaces.IThermostatService.FanOn { get { return ((FanOn_Get_Delegate)_stubs[nameof(FanOn_Get_Delegate)]).Invoke(); } set { ((FanOn_Set_Delegate)_stubs[nameof(FanOn_Set_Delegate)]).Invoke(value); } } public delegate bool FanOn_Get_Delegate(); public StubIThermostatService FanOn_Get(FanOn_Get_Delegate del) { _stubs[nameof(FanOn_Get_Delegate)] = del; return this; } public delegate void FanOn_Set_Delegate(bool value); public StubIThermostatService FanOn_Set(FanOn_Set_Delegate del) { _stubs[nameof(FanOn_Set_Delegate)] = del; return this; } } }
using CilJs.JSAst; using CilJs.Loading.Model; using Managed.Reflection; using System; using System.Collections.Generic; using System.Linq; using Type = Managed.Reflection.Type; namespace CilJs.JsTranslation { abstract class AbstractTranslator { protected readonly Context context; protected readonly SourceMapBuilder sourceMapBuilder; public AbstractTranslator(Context context, SourceMapBuilder sourceMapBuilder) { this.context = context; this.sourceMapBuilder = sourceMapBuilder; } protected JSIdentifier GetAssemblyIdentifier(Type type) { var asm = context.Assemblies.FirstOrDefault(c => c.ReflectionAssembly == type.Assembly); if (asm == null) { throw new Exception("Cannot resolve assembly of type " + type); } return new JSIdentifier { Name = asm.Identifier }; } protected virtual JSExpression GetTypeIdentifier(Type type, MethodBase methodScope = null, Type typeScope = null, JSExpression thisScope = null, ICollection<Type> typesInScope = null) { if (IsIgnoredType(type)) throw new InvalidOperationException("type is marked as ignored and cannot be referenced"); if (typesInScope != null) { var idx = typesInScope.IndexOf(type); if (idx != -1) return JSFactory.Identifier("t" + idx); } if (type.IsArray) { var genericArray = context.ReflectionUniverse.GetType("System.Array`1"); return GetTypeIdentifier( genericArray.MakeGenericType(type.GetElementType()), methodScope, typeScope, thisScope, typesInScope); } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null || // For static methods on generic classes, the type arguments are passed to // the method at the call site rather than wired through the generic class type. // So, the type argument is available as an argument in the closure of the // javascript function, which is why we emit an identifier. (methodScope != null && methodScope.IsStatic && type.DeclaringType.GetGenericTypeDefinition() == methodScope.DeclaringType)) { return new JSIdentifier { Name = type.Name }; } else if (thisScope == null) { return (IsInScope(type.DeclaringType, typeScope)) ? JSFactory.Identifier(GetSimpleName(type)) : // to my awareness, this only happens when you do "typeof(C<>)", ie not specifying any args GetTypeIdentifier(context.SystemTypes.UnboundGenericParameter); } else { var metadataName = GetTypeMetadataName(typeScope); return new JSArrayLookupExpression { Array = JSFactory.Identifier(thisScope, "constructor", "GenericArguments", metadataName), Indexer = new JSNumberLiteral { Value = typeScope.GetGenericArguments().IndexOf(type) } }; } } else if (type.IsGenericType) { return new JSCallExpression { Function = JSFactory.Identifier( GetAssemblyIdentifier(type), type.GetGenericTypeDefinition().FullName), Arguments = type .GetGenericArguments() .Select( g => GetTypeIdentifier(g, methodScope, typeScope, thisScope, typesInScope)) .ToList() }; } else { return new JSCallExpression { Function = JSFactory.Identifier(GetAssemblyIdentifier(type), type.FullName) }; } } protected string GetTypeMetadataName(Type current) { current = (current.IsGenericType && !current.IsGenericTypeDefinition) ? current.GetGenericTypeDefinition() : current; return GetAssemblyIdentifier(current).Name + ".t" + current.MetadataToken.ToString("x"); } protected bool IsIgnoredType(Type type) { return type.GetCustomAttributesData().Any(a => a.AttributeType.Name == "JsIgnoreAttribute"); } private static bool IsInScope(Type type, Type typeScope) { if (typeScope == null) return false; return typeScope == type || IsInScope(type, typeScope.DeclaringType) || IsInScope(type, typeScope.BaseType); } private static string ConstructFullName(Type type) { var name = ""; if (type.Namespace != null) name = type.Namespace + "."; if (type.DeclaringType != null) name += type.DeclaringType.Name + "+"; name += type.Name; return name; } protected static string GetSimpleName(Type type) { var n = type.Name.Replace("<", "_").Replace(">", "_").Replace("`", "_").Replace("{", "_").Replace("}", "_").Replace("-", "_").Replace("=", "_"); if (n == "String" || n == "Number" || n == "Boolean" || n == "Object" || n == "function") return "$$" + n; return n; } protected static string GetSimpleName(MethodBase method) { return method.Name.Replace("<", "_").Replace(">", "_").Replace("`", "_").Replace(".", "_").Replace(",", "_"); } protected string GetTranslatedFieldName(FieldInfo f) { if (f.IsStatic == false && f.IsPrivate && f.DeclaringType.IsValueType == false) { var ns = (f.DeclaringType.Namespace ?? "").Replace('.', '_'); return ns + GetSimpleName(f.DeclaringType) + f.Name; } else { return f.Name; } } protected string GetVirtualMethodIdentifier(MethodInfo m) { return String.Format("{0}.{1}", GetAssemblyIdentifier(m.GetBaseDefinition().DeclaringType), GetMethodIdentifier(m.GetBaseDefinition())); } /// <summary> /// Gets an expression that accesses the JavaScript function which is the implementation of the method /// </summary> /// <param name="mi">Method to be accessed</param> /// <param name="callingScope">The method making a call to <paramref name="mi"/>. Used to make generic argument lookup. </param> /// <param name="typeScope">The declaring type of the method making a call to <paramref name="mi"/>. Used to make generic argument lookup. </param> /// <param name="thisScope">The this object of the call to <paramref name="mi"/>. Used to make generic argument lookup. Null for static methods.</param> /// <returns></returns> protected JSExpression GetMethodAccessor(MethodBase mi, MethodBase callingScope = null, Type typeScope = null, JSExpression thisScope = null) { var function = GetUnboundMethodAccessor(mi); return BindGenericMethodArguments(function, mi, callingScope, typeScope, thisScope); } protected JSExpression BindGenericMethodArguments(JSExpression function, MethodBase mi, MethodBase callingScope, Type typeScope, JSExpression thisScope) { if (mi.IsGenericMethod || (mi.IsStatic && mi.DeclaringType.IsGenericType)) { // For static methods on generic classes, the type arguments are passed to // the method at the call site rather than wired through the generic class type. // This is the same behavior as generic static methods (on nongeneric class), so both are handled here. // Of course, this also extends to generic static methods on generic classes. var classGenArgs = (mi.IsStatic && mi.DeclaringType.IsGenericType) ? mi.DeclaringType.GetGenericArguments() : new Type[0]; var methodGenArgs = mi.IsGenericMethod ? mi.GetGenericArguments() : new Type[0]; return new JSCallExpression { Function = function, Arguments = Enumerable .Concat( classGenArgs, methodGenArgs) .Select(t => GetTypeIdentifier(t, methodScope: callingScope, typeScope: typeScope, thisScope: thisScope)) .ToList() }; } else { return function; } } protected JSExpression GetUnboundMethodAccessor(MethodBase mi) { return new JSPropertyAccessExpression { Host = GetAssemblyIdentifier(mi.DeclaringType), Property = GetMethodIdentifier(mi) }; } protected string GetMethodIdentifier(MethodBase m) { return "x" + m.MetadataToken.ToString("x"); } protected JSExpression GetDefaultValue(Type fieldType, MethodBase methodScope = null, Type typeScope = null, JSExpression thisScope = null) { return fieldType.IsGenericParameter ? GetGenericDefaultValue(fieldType, methodScope, typeScope, thisScope) : fieldType.IsPrimitive ? new JSNumberLiteral { Value = 0 } as JSExpression : fieldType.IsValueType ? new JSNewExpression { Constructor = GetTypeIdentifier(fieldType, methodScope, typeScope, thisScope) } as JSExpression : new JSNullLiteral(); } private JSExpression GetGenericDefaultValue(Type fieldType, MethodBase methodScope = null, Type typeScope = null, JSExpression thisScope = null) { var t = GetTypeIdentifier(fieldType, methodScope, typeScope, thisScope); return JSFactory.Identifier(t, "Default"); } //private JSExpression GetGenericDefaultValue(Type fieldType, MethodBase methodScope = null, Type typeScope = null, JSExpression thisScope = null) //{ // var t = GetTypeIdentifier(fieldType, methodScope, typeScope, thisScope); // return new JSConditionalExpression // { // Condition = JSFactory.Identifier(t, "IsValueType"), // TrueValue = new JSConditionalExpression // { // Condition = JSFactory.Identifier(t, "IsPrimitive"), // TrueValue = new JSNumberLiteral { Value = 0 }, // FalseValue = new JSNewExpression { Constructor = t } // }, // FalseValue = new JSNullLiteral() // }; //} protected JSExpression GetThisScope(MethodBase methodScope, Type typeScope) { var thisScope = methodScope.IsStatic ? null : JSFactory.Identifier("arg0"); if (thisScope != null && typeScope.IsValueType) thisScope = new JSCallExpression { Function = JSFactory.Identifier(thisScope, "r") }; return thisScope; } } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:41 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.tree { #region Panel /// <inheritdocs /> /// <summary> /// <p>The TreePanel provides tree-structured UI representation of tree-structured data. /// A TreePanel must be bound to a <see cref="Ext.data.TreeStore">Ext.data.TreeStore</see>. TreePanel's support /// multiple columns through the <see cref="Ext.tree.PanelConfig.columns">columns</see> configuration.</p> /// <p>Simple TreePanel using inline data:</p> /// <pre><code>var store = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.data.TreeStore">Ext.data.TreeStore</see>', { /// root: { /// expanded: true, /// children: [ /// { text: "detention", leaf: true }, /// { text: "homework", expanded: true, children: [ /// { text: "book report", leaf: true }, /// { text: "alegrbra", leaf: true} /// ] }, /// { text: "buy lottery tickets", leaf: true } /// ] /// } /// }); /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.tree.Panel">Ext.tree.Panel</see>', { /// title: 'Simple Tree', /// width: 200, /// height: 150, /// store: store, /// rootVisible: false, /// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>() /// }); /// </code></pre> /// <p>For the tree node config options (like <c>text</c>, <c>leaf</c>, <c>expanded</c>), see the documentation of /// <see cref="Ext.data.NodeInterface">NodeInterface</see> config options.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Panel : Ext.panel.Table { /// <summary> /// The field inside the model that will be used as the node's text. /// Defaults to: <c>&quot;text&quot;</c> /// </summary> public JsString displayField; /// <summary> /// True to automatically prepend a leaf sorter to the store. /// </summary> public bool folderSort; /// <summary> /// False to disable tree lines. /// Defaults to: <c>true</c> /// </summary> public bool lines; /// <summary> /// Allows you to not specify a store on this TreePanel. This is useful for creating a simple tree with preloaded /// data without having to specify a TreeStore and Model. A store and model will be created and root will be passed /// to that store. For example: /// <code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.tree.Panel">Ext.tree.Panel</see>', { /// title: 'Simple Tree', /// root: { /// text: "Root node", /// expanded: true, /// children: [ /// { text: "Child 1", leaf: true }, /// { text: "Child 2", leaf: true } /// ] /// }, /// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>() /// }); /// </code> /// Defaults to: <c>null</c> /// </summary> public object root; /// <summary> /// False to hide the root node. /// Defaults to: <c>true</c> /// </summary> public bool rootVisible; /// <summary> /// True if only 1 node per branch may be expanded. /// Defaults to: <c>false</c> /// </summary> public bool singleExpand; /// <summary> /// True to use Vista-style arrows in the tree. /// Defaults to: <c>false</c> /// </summary> public bool useArrows; /// <summary> /// Collapse all nodes /// </summary> /// <param name="callback"><p>A function to execute when the collapse finishes.</p> /// </param> /// <param name="scope"><p>The scope of the callback function</p> /// </param> public void collapseAll(object callback=null, object scope=null){} /// <summary> /// Collapses a record that is loaded in the tree. /// </summary> /// <param name="record"><p>The record to collapse</p> /// </param> /// <param name="deep"><p>True to collapse nodes all the way up the tree hierarchy.</p> /// </param> /// <param name="callback"><p>The function to run after the collapse is completed</p> /// </param> /// <param name="scope"><p>The scope of the callback function.</p> /// </param> public void collapseNode(Ext.data.Model record, object deep=null, object callback=null, object scope=null){} /// <summary> /// Expand all nodes /// </summary> /// <param name="callback"><p>A function to execute when the expand finishes.</p> /// </param> /// <param name="scope"><p>The scope of the callback function</p> /// </param> public void expandAll(object callback=null, object scope=null){} /// <summary> /// Expands a record that is loaded in the tree. /// </summary> /// <param name="record"><p>The record to expand</p> /// </param> /// <param name="deep"><p>True to expand nodes all the way down the tree hierarchy.</p> /// </param> /// <param name="callback"><p>The function to run after the expand is completed</p> /// </param> /// <param name="scope"><p>The scope of the callback function.</p> /// </param> public void expandNode(Ext.data.Model record, object deep=null, object callback=null, object scope=null){} /// <summary> /// Expand the tree to the path of a particular node. /// </summary> /// <param name="path"><p>The path to expand. The path should include a leading separator.</p> /// </param> /// <param name="field"><p>The field to get the data from. Defaults to the model idProperty.</p> /// </param> /// <param name="separator"><p>A separator to use.</p> /// <p>Defaults to: <c>&quot;/&quot;</c></p></param> /// <param name="callback"><p>A function to execute when the expand finishes. The callback will be called with /// (success, lastNode) where success is if the expand was successful and lastNode is the last node that was expanded.</p> /// </param> /// <param name="scope"><p>The scope of the callback function</p> /// </param> public void expandPath(JsString path, object field=null, object separator=null, object callback=null, object scope=null){} /// <summary> /// Retrieve an array of checked records. /// </summary> /// <returns> /// <span><see cref="Ext.data.NodeInterface">Ext.data.NodeInterface</see>[]</span><div><p>An array containing the checked records</p> /// </div> /// </returns> public Ext.data.NodeInterface[] getChecked(){return null;} /// <summary> /// Returns the root node for this tree. /// </summary> /// <returns> /// <span><see cref="Ext.data.NodeInterface">Ext.data.NodeInterface</see></span><div> /// </div> /// </returns> public Ext.data.NodeInterface getRootNode(){return null;} /// <summary> /// Expand the tree to the path of a particular node, then select it. /// </summary> /// <param name="path"><p>The path to select. The path should include a leading separator.</p> /// </param> /// <param name="field"><p>The field to get the data from. Defaults to the model idProperty.</p> /// </param> /// <param name="separator"><p>A separator to use.</p> /// <p>Defaults to: <c>&quot;/&quot;</c></p></param> /// <param name="callback"><p>A function to execute when the select finishes. The callback will be called with /// (bSuccess, oLastNode) where bSuccess is if the select was successful and oLastNode is the last node that was expanded.</p> /// </param> /// <param name="scope"><p>The scope of the callback function</p> /// </param> public void selectPath(JsString path, object field=null, object separator=null, object callback=null, object scope=null){} /// <summary> /// Sets root node of this tree. /// </summary> /// <param name="root"> /// </param> /// <returns> /// <span><see cref="Ext.data.NodeInterface">Ext.data.NodeInterface</see></span><div><p>The new root</p> /// </div> /// </returns> public Ext.data.NodeInterface setRootNode(object root=null){return null;} public Panel(Ext.tree.PanelConfig config){} public Panel(){} public Panel(params object[] args){} } #endregion #region PanelConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class PanelConfig : Ext.panel.TableConfig { /// <summary> /// True to enable animated expand/collapse. Defaults to the value of Ext.enableFx. /// </summary> public bool animate; /// <summary> /// The field inside the model that will be used as the node's text. /// Defaults to: <c>&quot;text&quot;</c> /// </summary> public JsString displayField; /// <summary> /// True to automatically prepend a leaf sorter to the store. /// </summary> public bool folderSort; /// <summary> /// False to disable tree lines. /// Defaults to: <c>true</c> /// </summary> public bool lines; /// <summary> /// Allows you to not specify a store on this TreePanel. This is useful for creating a simple tree with preloaded /// data without having to specify a TreeStore and Model. A store and model will be created and root will be passed /// to that store. For example: /// <code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.tree.Panel">Ext.tree.Panel</see>', { /// title: 'Simple Tree', /// root: { /// text: "Root node", /// expanded: true, /// children: [ /// { text: "Child 1", leaf: true }, /// { text: "Child 2", leaf: true } /// ] /// }, /// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>() /// }); /// </code> /// Defaults to: <c>null</c> /// </summary> public object root; /// <summary> /// False to hide the root node. /// Defaults to: <c>true</c> /// </summary> public bool rootVisible; /// <summary> /// True if only 1 node per branch may be expanded. /// Defaults to: <c>false</c> /// </summary> public bool singleExpand; /// <summary> /// True to use Vista-style arrows in the tree. /// Defaults to: <c>false</c> /// </summary> public bool useArrows; public PanelConfig(params object[] args){} } #endregion #region PanelEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class PanelEvents : Ext.panel.TableEvents { /// <summary> /// Fires after an item has been visually collapsed and is no longer visible in the tree. /// </summary> /// <param name="node"><p>The node that was collapsed</p> /// </param> /// <param name="index"><p>The index of the node</p> /// </param> /// <param name="item"><p>The HTML element for the node that was collapsed</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void afteritemcollapse(Ext.data.NodeInterface node, JsNumber index, object item, object eOpts){} /// <summary> /// Fires after an item has been visually expanded and is visible in the tree. /// </summary> /// <param name="node"><p>The node that was expanded</p> /// </param> /// <param name="index"><p>The index of the node</p> /// </param> /// <param name="item"><p>The HTML element for the node that was expanded</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void afteritemexpand(Ext.data.NodeInterface node, JsNumber index, object item, object eOpts){} /// <summary> /// Fires before a new child is appended, return false to cancel the append. /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The child node to be appended</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeitemappend(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, object eOpts){} /// <summary> /// Fires before this node is collapsed. /// </summary> /// <param name="this"><p>The collapsing node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeitemcollapse(Ext.data.NodeInterface @this, object eOpts){} /// <summary> /// Fires before this node is expanded. /// </summary> /// <param name="this"><p>The expanding node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeitemexpand(Ext.data.NodeInterface @this, object eOpts){} /// <summary> /// Fires before a new child is inserted, return false to cancel the insert. /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The child node to be inserted</p> /// </param> /// <param name="refNode"><p>The child node the node is being inserted before</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeiteminsert(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, Ext.data.NodeInterface refNode, object eOpts){} /// <summary> /// Fires before this node is moved to a new location in the tree. Return false to cancel the move. /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="oldParent"><p>The parent of this node</p> /// </param> /// <param name="newParent"><p>The new parent this node is moving to</p> /// </param> /// <param name="index"><p>The index it is being moved to</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeitemmove(Ext.data.NodeInterface @this, Ext.data.NodeInterface oldParent, Ext.data.NodeInterface newParent, JsNumber index, object eOpts){} /// <summary> /// Fires before a child is removed, return false to cancel the remove. /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The child node to be removed</p> /// </param> /// <param name="isMove"><p><c>true</c> if the child node is being removed so it can be moved to another position in the tree. /// (a side effect of calling <see cref="Ext.data.NodeInterface.appendChild">appendChild</see> or /// <see cref="Ext.data.NodeInterface.insertBefore">insertBefore</see> with a node that already has a parentNode)</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeitemremove(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, bool isMove, object eOpts){} /// <summary> /// Fires before a request is made for a new data object. If the beforeload handler returns false the load /// action will be canceled. /// </summary> /// <param name="store"><p>This Store</p> /// </param> /// <param name="operation"><p>The <see cref="Ext.data.Operation">Ext.data.Operation</see> object that will be passed to the Proxy to /// load the Store</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforeload(Ext.data.Store store, Ext.data.Operation operation, object eOpts){} /// <summary> /// Fires when a node with a checkbox's checked property changes /// </summary> /// <param name="node"><p>The node who's checked property was changed</p> /// </param> /// <param name="checked"><p>The node's new checked state</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void checkchange(Ext.data.NodeInterface node, bool @checked, object eOpts){} /// <summary> /// Fires when a new child node is appended /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The newly appended node</p> /// </param> /// <param name="index"><p>The index of the newly appended node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemappend(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, JsNumber index, object eOpts){} /// <summary> /// Fires when this node is collapsed. /// </summary> /// <param name="this"><p>The collapsing node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemcollapse(Ext.data.NodeInterface @this, object eOpts){} /// <summary> /// Fires when this node is expanded. /// </summary> /// <param name="this"><p>The expanding node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemexpand(Ext.data.NodeInterface @this, object eOpts){} /// <summary> /// Fires when a new child node is inserted. /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The child node inserted</p> /// </param> /// <param name="refNode"><p>The child node the node was inserted before</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void iteminsert(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, Ext.data.NodeInterface refNode, object eOpts){} /// <summary> /// Fires when this node is moved to a new location in the tree /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="oldParent"><p>The old parent of this node</p> /// </param> /// <param name="newParent"><p>The new parent of this node</p> /// </param> /// <param name="index"><p>The index it was moved to</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemmove(Ext.data.NodeInterface @this, Ext.data.NodeInterface oldParent, Ext.data.NodeInterface newParent, JsNumber index, object eOpts){} /// <summary> /// Fires when a child node is removed /// </summary> /// <param name="this"><p>This node</p> /// </param> /// <param name="node"><p>The removed node</p> /// </param> /// <param name="isMove"><p><c>true</c> if the child node is being removed so it can be moved to another position in the tree. /// (a side effect of calling <see cref="Ext.data.NodeInterface.appendChild">appendChild</see> or /// <see cref="Ext.data.NodeInterface.insertBefore">insertBefore</see> with a node that already has a parentNode)</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemremove(Ext.data.NodeInterface @this, Ext.data.NodeInterface node, bool isMove, object eOpts){} /// <summary> /// Fires whenever the store reads data from a remote data source. /// </summary> /// <param name="this"> /// </param> /// <param name="node"><p>The node that was loaded.</p> /// </param> /// <param name="records"><p>An array of records.</p> /// </param> /// <param name="successful"><p>True if the operation was successful.</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void load(Ext.data.TreeStore @this, Ext.data.NodeInterface node, JsArray<Ext.data.Model> records, bool successful, object eOpts){} public PanelEvents(params object[] args){} } #endregion }
using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using Nucleo.EventArguments; namespace Nucleo.Collections { /// <summary> /// This class is a functional collection-base class that offers more than the standard base class. It also includes a series of events and other methods that fire whenever any interaction takes place with it: adding, inserting, or deleting. /// </summary> /// <typeparam name="T">The type of item to store in the collection.</typeparam> [CLSCompliant(true)] public class CollectionBase<T> : IList<T> { private bool _ascending = true; private List<T> _list = null; #region " Events " /// <summary> /// Fires after an item is added to the list. /// </summary> public event DataEventHandler<T> ItemAdded; /// <summary> /// Fires whenever an item is about to be added to the list. /// </summary> public event CancellationEventHandler ItemAdding; /// <summary> /// Fires after the list was cleared. /// </summary> public event EventHandler ItemCleared; /// <summary> /// Fires whenever the list was being cleared, before it is being cleared. /// </summary> public event CancellationEventHandler ItemClearing; /// <summary> /// Fires after the item is being inserted into the list. /// </summary> public event InsertDataEventHandler<T> ItemInserted; /// <summary> /// Fires whenever the item is about to be inserted into the list. /// </summary> public event CancellationEventHandler ItemInserting; /// <summary> /// Fires after the item is being removed from the list. /// </summary> public event DataEventHandler<T> ItemRemoved; /// <summary> /// Fires whenever the item is about to be removed from the list. /// </summary> public event CancellationEventHandler ItemRemoving; #endregion #region " Properties " public int Count { get { return this.List.Count; } } public bool IsReadOnly { get { return false; } } protected List<T> List { get { if (_list == null) _list = new List<T>(); return _list; } } public T this[int index] { get { return this.List[index]; } set { this.List[index] = value; } } #endregion #region " Constructors " public CollectionBase() { _list = new List<T>(); } public CollectionBase(T item) { _list = new List<T>(new T[] { item }); } public CollectionBase(IEnumerable<T> list) { _list = new List<T>(list); } #endregion #region " Methods " /// <summary> /// Adds an item to the list. /// </summary> /// <param name="item">The item to add.</param> /// <remarks>Fires the <see cref="ItemAdding" /> event; if the action is not cancelled, the <see cref="ItemAdded" /> event is fired after the item is added to the collection.</remarks> public virtual void Add(T item) { var args = new CancellationEventArgs(false); this.OnItemAdding(args); if (!args.Cancel) { this.List.Add(item); this.OnItemAdded(new DataEventArgs<T>(item)); } } public void AddRange(T[] items) { foreach (T item in items) this.Add(item); } public void AddRange(IEnumerable items) { IEnumerator list = items.GetEnumerator(); while (list.MoveNext()) { if (list.Current != null && list.Current is T) this.Add((T)list.Current); } } public void AddRange(IEnumerable<T> items) { IEnumerator<T> list = items.GetEnumerator(); while (list.MoveNext()) { if (list.Current != null) this.Add(list.Current); } } /// <summary> /// Clears all of the items out of the list. /// </summary> /// <remarks>The method fires the <see cref="ItemClearing"/> event. If the action isn't cancelled, the <see cref="ItemCleared" /> event is fired after the collection is cleared.</remarks> public virtual void Clear() { var args = new CancellationEventArgs(false); this.OnItemClearing(args); if (!args.Cancel) { this.List.Clear(); this.OnItemCleared(EventArgs.Empty); } } /// <summary> /// Determines whether an item in the list exists. /// </summary> /// <param name="item">The item to check for.</param> /// <returns>Whether the item exists in the list.</returns> public bool Contains(T item) { return this.List.Contains(item); } /// <summary> /// Copies this collection to another array. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="arrayIndex">The index of the item for which copying begins.</param> public virtual void CopyTo(T[] array, int arrayIndex) { this.List.CopyTo(array, arrayIndex); } public IEnumerator<T> GetEnumerator() { return this.List.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.List.GetEnumerator(); } /// <summary> /// Gets a range of items out of the collection using a starting index and total count, and returns it as an array. /// </summary> /// <param name="start">The index of the item to start at.</param> /// <param name="count">The total count of items to collect.</param> /// <returns>An array of items to return.</returns> /// <remarks>If start is 1 and count is 20, the method loops from index 1 to index 21. If the total count is greater than the collection count, the maximum count value is used.</remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if the starting index is outside the array of index values.</exception> public T[] GetRange(int start, int count) { if (start < 0 || start > this.Count) throw new ArgumentOutOfRangeException("start"); List<T> itemsList = new List<T>(); for (int i = start; i <= (start + (count - 1)); i++) { if (i < this.Count) itemsList.Add(this[i]); else return itemsList.ToArray(); } return itemsList.ToArray(); } /// <summary> /// Gets the index of the item in the collection. /// </summary> /// <param name="item">The item to look for.</param> /// <returns>The index of the item in the list.</returns> public int IndexOf(T item) { return this.List.IndexOf(item); } /// <summary> /// Inserts an item to the list. /// </summary> /// <param name="index">The index of the item to insert.</param> /// <param name="item">The item to insert.</param> /// <remarks>Fires the <see cref="ItemInserting" /> event; if the action is not cancelled, the <see cref="ItemInserted" /> event is fired after the item is inserted to the collection.</remarks> public virtual void Insert(int index, T item) { var args = new CancellationEventArgs(false); this.OnItemInserting(args); if (!args.Cancel) { this.List.Insert(index, item); this.OnItemInserted(index, new DataEventArgs<T>(item)); } } public void InsertRange(int index, T[] items) { for (int i = items.Length - 1; i >= 0; i--) this.List.Insert(index, items[i]); } public void InsertRange(int index, IEnumerable items) { IEnumerator list = items.GetEnumerator(); List<T> newList = new List<T>(); while (list.MoveNext()) { if (list.Current != null && list.Current is T) newList.Add((T)list.Current); } this.InsertRange(index, newList.ToArray()); } public void InsertRange(int index, IEnumerable<T> items) { IEnumerator<T> list = items.GetEnumerator(); List<T> newList = new List<T>(); while (list.MoveNext()) { if (list.Current != null) newList.Add(list.Current); } this.InsertRange(index, newList.ToArray()); } protected virtual void OnItemAdded(DataEventArgs<T> e) { if (ItemAdded != null) ItemAdded(this, e); } protected virtual void OnItemAdding(CancellationEventArgs e) { if (ItemAdding != null) ItemAdding(this, e); } protected virtual void OnItemCleared(EventArgs e) { if (ItemCleared != null) ItemCleared(this, e); } protected virtual void OnItemClearing(CancellationEventArgs e) { if (ItemClearing != null) ItemClearing(this, e); } protected virtual void OnItemInserted(int index, DataEventArgs<T> e) { if (ItemInserted != null) ItemInserted(this, index, e); } protected virtual void OnItemInserting(CancellationEventArgs e) { if (ItemInserting != null) ItemInserting(this, e); } protected virtual void OnItemRemoved(DataEventArgs<T> e) { if (ItemRemoved != null) ItemRemoved(this, e); } protected virtual void OnItemRemoving(CancellationEventArgs e) { if (ItemRemoving != null) ItemRemoving(this, e); } public virtual bool Remove(T item) { bool removed = false; var args = new CancellationEventArgs(false); this.OnItemRemoving(args); if (!args.Cancel) { removed = this.List.Remove(item); this.OnItemRemoved(new DataEventArgs<T>(item)); } return removed; } public void RemoveAt(int index) { T item = this.List[index]; this.Remove(item); } /// <summary> /// Converts the list to an array of items. /// </summary> /// <returns>The list in an array form.</returns> public T[] ToArray() { return this.List.ToArray(); } #endregion } public delegate void InsertDataEventHandler<T>(object sender, int index, DataEventArgs<T> data); }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using Komires.MataliPhysics; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Bridge2 { Demo demo; PhysicsScene scene; string instanceIndexName; public Bridge2(Demo demo, int instanceIndex) { this.demo = demo; instanceIndexName = " " + instanceIndex.ToString(); } public void Initialize(PhysicsScene scene) { this.scene = scene; } public static void CreateShapes(Demo demo, PhysicsScene scene) { } public void Create(PhysicsObject startObject, PhysicsObject endObject, Vector3 startPosition, Vector3 endPosition, int boardCount, Vector2 boardXYScale) { Shape sphere = scene.Factory.ShapeManager.Find("Sphere"); Shape box = scene.Factory.ShapeManager.Find("Box"); Shape cylinderY = scene.Factory.ShapeManager.Find("CylinderY"); PhysicsObject objectRoot = null; PhysicsObject objectBase = null; PhysicsObject objectTruss = null; Vector3 position1 = Vector3.Zero; Vector3 position2 = Vector3.Zero; Vector3 scale1 = Vector3.One; Vector3 scale2 = Vector3.One; Quaternion orientation1 = Quaternion.Identity; Quaternion orientation2 = Quaternion.Identity; objectRoot = scene.Factory.PhysicsObjectManager.Create("Bridge 2 " + instanceIndexName); endPosition.Y = startPosition.Y; Vector3 distance = startPosition - endPosition; float length = distance.Length; float boardLength = length / boardCount; Vector3 boardScale = new Vector3(boardXYScale.X, boardXYScale.Y, boardLength * 0.5f); for (int i = 0; i < boardCount; i++) { objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Board " + i.ToString() + instanceIndexName); objectRoot.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.InitLocalTransform.SetPosition(startPosition.X, startPosition.Y, startPosition.Z + i * 2.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(90.0f))); objectBase.InitLocalTransform.SetScale(boardLength * 0.5f, 0.4f, 15.0f); objectBase.Integral.SetDensity(1.0f); objectBase.CreateSound(true); } int trussCount = boardCount / 2; for (int i = 0; i < trussCount; i++) { objectTruss = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Right " + i.ToString() + instanceIndexName); objectRoot.AddChildPhysicsObject(objectTruss); objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Right Base " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.InitLocalTransform.SetPosition(startPosition.X + 14.0f, startPosition.Y + boardLength * 0.25f + 0.4f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(0.4f, boardLength * 0.25f, 0.4f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableBreakRigidGroup = false; objectBase.CreateSound(true); objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Right Light Base " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.RigidGroup = true; objectBase.Material.TwoSidedNormals = true; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(startPosition.X + 14.0f, startPosition.Y + boardLength * 0.5f + 1.0f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(0.6f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableBreakRigidGroup = false; objectBase.CreateSound(true); objectBase.Sound.UserDataStr = "Glass"; objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Right Light " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.Material.RigidGroup = true; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(startPosition.X + 14.0f, startPosition.Y + boardLength * 0.5f + 1.0f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(15.0f); objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(1.0f, 0.7f, 0.0f); objectBase.Light.Range = 15.0f; objectBase.EnableBreakRigidGroup = false; objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; } for (int i = 0; i < trussCount; i++) { objectTruss = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Left " + i.ToString() + instanceIndexName); objectRoot.AddChildPhysicsObject(objectTruss); objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Left Base " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.InitLocalTransform.SetPosition(startPosition.X - 14.0f, startPosition.Y + boardLength * 0.25f + 0.4f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(0.4f, boardLength * 0.25f, 0.4f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableBreakRigidGroup = false; objectBase.CreateSound(true); objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Left Light Base " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.RigidGroup = true; objectBase.Material.TwoSidedNormals = true; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(startPosition.X - 14.0f, startPosition.Y + boardLength * 0.5f + 1.0f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(0.6f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableBreakRigidGroup = false; objectBase.CreateSound(true); objectBase.Sound.UserDataStr = "Glass"; objectBase = scene.Factory.PhysicsObjectManager.Create("Bridge 2 Truss Left Light " + i.ToString() + instanceIndexName); objectTruss.AddChildPhysicsObject(objectBase); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.Material.RigidGroup = true; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(startPosition.X - 14.0f, startPosition.Y + boardLength * 0.5f + 1.0f, startPosition.Z + i * 4.0f * boardScale.Z + boardScale.Z); objectBase.InitLocalTransform.SetScale(15.0f); objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(1.0f, 0.7f, 0.0f); objectBase.Light.Range = 15.0f; objectBase.EnableBreakRigidGroup = false; objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; } objectRoot.UpdateFromInitLocalTransform(); Constraint constraint = null; for (int i = 0; i < trussCount; i++) { constraint = scene.Factory.ConstraintManager.Create("Bridge 2 Truss Right Constraint " + i.ToString() + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Right Base " + i.ToString() + instanceIndexName); constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board " + (i * 2).ToString() + instanceIndexName); constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2); constraint.SetAnchor1(position1 - new Vector3(0.0f, boardLength * 0.25f, 0.0f)); constraint.SetAnchor2(position1 - new Vector3(0.0f, boardLength * 0.25f, 0.0f)); constraint.SetInitWorldOrientation1(ref orientation1); constraint.SetInitWorldOrientation2(ref orientation2); constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.EnableBreak = true; constraint.Update(); } for (int i = 0; i < trussCount; i++) { constraint = scene.Factory.ConstraintManager.Create("Bridge 2 Truss Left Constraint " + i.ToString() + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Left Base " + i.ToString() + instanceIndexName); constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board " + (i * 2).ToString() + instanceIndexName); constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2); constraint.SetAnchor1(position1 - new Vector3(0.0f, boardLength * 0.25f, 0.0f)); constraint.SetAnchor2(position1 - new Vector3(0.0f, boardLength * 0.25f, 0.0f)); constraint.SetInitWorldOrientation1(ref orientation1); constraint.SetInitWorldOrientation2(ref orientation2); constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.EnableBreak = true; constraint.Update(); } constraint = scene.Factory.ConstraintManager.Create("Bridge 2 Constraint 0" + instanceIndexName); constraint.PhysicsObject1 = startObject; constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board 0" + instanceIndexName); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2); constraint.SetAnchor1(ref startPosition); constraint.SetAnchor2(ref startPosition); constraint.SetInitWorldOrientation1(ref orientation1); constraint.SetInitWorldOrientation2(ref orientation2); constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.EnableBreak = true; constraint.AngularDamping = 0.1f; constraint.Update(); for (int i = 0; i < boardCount - 1; i++) { constraint = scene.Factory.ConstraintManager.Create("Bridge 2 Constraint " + (i + 1).ToString() + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board " + i.ToString() + instanceIndexName); constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board " + (i + 1).ToString() + instanceIndexName); constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2); constraint.SetAnchor1(position1 + new Vector3(0.0f, 0.0f, boardScale.Z)); constraint.SetAnchor2(position1 + new Vector3(0.0f, 0.0f, boardScale.Z)); constraint.SetInitWorldOrientation1(ref orientation1); constraint.SetInitWorldOrientation2(ref orientation2); constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.EnableBreak = true; constraint.AngularDamping = 0.1f; constraint.Update(); } constraint = scene.Factory.ConstraintManager.Create("Bridge 2 Constraint " + (boardCount + 1).ToString() + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Board " + (boardCount - 1).ToString() + instanceIndexName); constraint.PhysicsObject2 = endObject; constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2); constraint.SetAnchor1(ref endPosition); constraint.SetAnchor2(ref endPosition); constraint.SetInitWorldOrientation1(ref orientation1); constraint.SetInitWorldOrientation2(ref orientation2); constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.EnableBreak = true; constraint.AngularDamping = 0.1f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectRoot); Rope rope = null; int ropeSegmentCount = 4; PhysicsObject ropeStartObject = null; PhysicsObject ropeEndObject = null; for (int i = 0; i < trussCount - 1; i++) { ropeStartObject = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Left Base " + i.ToString() + instanceIndexName); ropeEndObject = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Left Base " + (i + 1).ToString() + instanceIndexName); ropeStartObject.MainWorldTransform.GetPosition(ref position1); ropeEndObject.MainWorldTransform.GetPosition(ref position2); ropeStartObject.MainWorldTransform.GetScale(ref scale1); ropeEndObject.MainWorldTransform.GetScale(ref scale2); position1 += new Vector3(0.0f, scale1.Y - scale1.Z, scale1.Z); position2 += new Vector3(0.0f, scale2.Y - scale1.Z, -scale2.Z); rope = new Rope(demo, i); rope.Initialize(scene); rope.Create(ropeStartObject, ropeEndObject, position1, position2, ropeSegmentCount); } for (int i = 0; i < trussCount - 1; i++) { ropeStartObject = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Right Base " + i.ToString() + instanceIndexName); ropeEndObject = scene.Factory.PhysicsObjectManager.Find("Bridge 2 Truss Right Base " + (i + 1).ToString() + instanceIndexName); ropeStartObject.MainWorldTransform.GetPosition(ref position1); ropeEndObject.MainWorldTransform.GetPosition(ref position2); ropeStartObject.MainWorldTransform.GetScale(ref scale1); ropeEndObject.MainWorldTransform.GetScale(ref scale2); position1 += new Vector3(0.0f, scale1.Y - scale1.Z, scale1.Z); position2 += new Vector3(0.0f, scale2.Y - scale1.Z, -scale2.Z); rope = new Rope(demo, i + trussCount); rope.Initialize(scene); rope.Create(ropeStartObject, ropeEndObject, position1, position2, ropeSegmentCount); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using osu.Framework.Configuration; using osu.Framework.Extensions.ExceptionExtensions; using osu.Framework.Logging; namespace osu.Framework.IO.Network { public class WebRequest : IDisposable { internal const int MAX_RETRIES = 1; /// <summary> /// Invoked when a response has been received, but not data has been received. /// </summary> public event Action Started; /// <summary> /// Invoked when the <see cref="WebRequest"/> has finished successfully. /// </summary> public event Action Finished; /// <summary> /// Invoked when the <see cref="WebRequest"/> has failed. /// </summary> public event Action<Exception> Failed; /// <summary> /// Invoked when the download progress has changed. /// </summary> public event Action<long, long> DownloadProgress; /// <summary> /// Invoked when the upload progress has changed. /// </summary> public event Action<long, long> UploadProgress; /// <summary> /// Whether the <see cref="WebRequest"/> was aborted due to an exception or a user abort request. /// </summary> public bool Aborted { get; private set; } private bool completed; /// <summary> /// Whether the <see cref="WebRequest"/> has been run. /// </summary> public bool Completed { get { return completed; } private set { completed = value; if (!completed) return; // WebRequests can only be used once - no need to keep events bound // This helps with disposal in PerformAsync usages Started = null; Finished = null; DownloadProgress = null; UploadProgress = null; } } private string url; /// <summary> /// The URL of this request. /// </summary> public string Url { get { return url; } set { #if !DEBUG if (!value.StartsWith(@"https://")) value = @"https://" + value.Replace(@"http://", @""); #endif url = value; } } /// <summary> /// POST parameters. /// </summary> private readonly Dictionary<string, string> parameters = new Dictionary<string, string>(); /// <summary> /// FILE parameters. /// </summary> private readonly IDictionary<string, byte[]> files = new Dictionary<string, byte[]>(); /// <summary> /// The request headers. /// </summary> private readonly IDictionary<string, string> headers = new Dictionary<string, string>(); public const int DEFAULT_TIMEOUT = 10000; public HttpMethod Method; /// <summary> /// The amount of time from last sent or received data to trigger a timeout and abort the request. /// </summary> public int Timeout = DEFAULT_TIMEOUT; /// <summary> /// The type of content expected by this web request. /// </summary> protected virtual string Accept => string.Empty; internal int RetryCount { get; private set; } /// <summary> /// Whether this request should internally retry (up to <see cref="MAX_RETRIES"/> times) on a timeout before throwing an exception. /// </summary> public bool AllowRetryOnTimeout { get; set; } = true; private static readonly Logger logger; private static readonly HttpClient client; static WebRequest() { client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); client.DefaultRequestHeaders.UserAgent.ParseAdd("osu!"); client.DefaultRequestHeaders.ExpectContinue = true; // Timeout is controlled manually through cancellation tokens because // HttpClient does not properly timeout while reading chunked data client.Timeout = System.Threading.Timeout.InfiniteTimeSpan; logger = Logger.GetLogger(LoggingTarget.Network); } public WebRequest(string url = null, params object[] args) { if (!string.IsNullOrEmpty(url)) Url = args.Length == 0 ? url : string.Format(url, args); } ~WebRequest() { Dispose(false); } private int responseBytesRead; private const int buffer_size = 32768; private byte[] buffer; private MemoryStream rawContent; public string ContentType; protected virtual Stream CreateOutputStream() { return new MemoryStream(); } public Stream ResponseStream; public string ResponseString { get { try { ResponseStream.Seek(0, SeekOrigin.Begin); StreamReader r = new StreamReader(ResponseStream, Encoding.UTF8); return r.ReadToEnd(); } catch { return null; } } } public byte[] ResponseData { get { try { byte[] data = new byte[ResponseStream.Length]; ResponseStream.Seek(0, SeekOrigin.Begin); ResponseStream.Read(data, 0, data.Length); return data; } catch { return null; } } } public HttpResponseHeaders ResponseHeaders => response.Headers; private CancellationTokenSource abortToken; private CancellationTokenSource timeoutToken; private LengthTrackingStream requestStream; private HttpResponseMessage response; private long contentLength => requestStream?.Length ?? 0; private const string form_boundary = "-----------------------------28947758029299"; private const string form_content_type = "multipart/form-data; boundary=" + form_boundary; /// <summary> /// Performs the request asynchronously. /// </summary> public async Task PerformAsync() { if (Completed) throw new InvalidOperationException($"The {nameof(WebRequest)} has already been run."); try { await Task.Factory.StartNew(internalPerform, TaskCreationOptions.LongRunning); } catch (AggregateException ae) { ae.RethrowIfSingular(); } } private void internalPerform() { using (abortToken = new CancellationTokenSource()) using (timeoutToken = new CancellationTokenSource()) using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(abortToken.Token, timeoutToken.Token)) { try { PrePerform(); HttpRequestMessage request; switch (Method) { default: throw new InvalidOperationException($"HTTP method {Method} is currently not supported"); case HttpMethod.GET: if (files.Count > 0) throw new InvalidOperationException($"Cannot use {nameof(AddFile)} in a GET request. Please set the {nameof(Method)} to POST."); StringBuilder requestParameters = new StringBuilder(); foreach (var p in parameters) requestParameters.Append($@"{p.Key}={p.Value}&"); string requestString = requestParameters.ToString().TrimEnd('&'); request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, string.IsNullOrEmpty(requestString) ? Url : $"{Url}?{requestString}"); break; case HttpMethod.POST: request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, Url); Stream postContent; if (rawContent != null) { if (parameters.Count > 0) throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddParameter)}"); if (files.Count > 0) throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddFile)}"); postContent = new MemoryStream(); rawContent.Position = 0; rawContent.CopyTo(postContent); postContent.Position = 0; } else { if (!string.IsNullOrEmpty(ContentType) && ContentType != form_content_type) throw new InvalidOperationException($"Cannot use custom {nameof(ContentType)} in a POST request."); ContentType = form_content_type; var formData = new MultipartFormDataContent(form_boundary); foreach (var p in parameters) formData.Add(new StringContent(p.Value), p.Key); foreach (var p in files) { var byteContent = new ByteArrayContent(p.Value); byteContent.Headers.Add("Content-Type", "application/octet-stream"); formData.Add(byteContent, p.Key, p.Key); } postContent = formData.ReadAsStreamAsync().Result; } requestStream = new LengthTrackingStream(postContent); requestStream.BytesRead.ValueChanged += v => { reportForwardProgress(); UploadProgress?.Invoke(v, contentLength); }; request.Content = new StreamContent(requestStream); if (!string.IsNullOrEmpty(ContentType)) request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType); break; } if (!string.IsNullOrEmpty(Accept)) request.Headers.Accept.TryParseAdd(Accept); foreach (var kvp in headers) request.Headers.Add(kvp.Key, kvp.Value); reportForwardProgress(); using (request) { response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, linkedToken.Token).Result; ResponseStream = CreateOutputStream(); switch (Method) { case HttpMethod.GET: //GETs are easy beginResponse(linkedToken.Token); break; case HttpMethod.POST: reportForwardProgress(); UploadProgress?.Invoke(0, contentLength); beginResponse(linkedToken.Token); break; } } } catch (Exception) when (timeoutToken.IsCancellationRequested) { Complete(new WebException($"Request to {Url} timed out after {timeSinceLastAction / 1000} seconds idle (read {responseBytesRead} bytes, retried {RetryCount} times).", WebExceptionStatus.Timeout)); } catch (Exception) when (abortToken.IsCancellationRequested) { Complete(new WebException($"Request to {Url} aborted by user.", WebExceptionStatus.RequestCanceled)); } catch (Exception e) { if (Completed) // we may be coming from one of the exception blocks handled above (as Complete will rethrow all exceptions). throw; Complete(e); } } } /// <summary> /// Performs the request synchronously. /// </summary> public void Perform() { try { PerformAsync().Wait(); } catch (AggregateException ae) { ae.RethrowIfSingular(); } } /// <summary> /// Task to run direct before performing the request. /// </summary> protected virtual void PrePerform() { } private void beginResponse(CancellationToken cancellationToken) { using (var responseStream = response.Content.ReadAsStreamAsync().Result) { reportForwardProgress(); Started?.Invoke(); buffer = new byte[buffer_size]; while (true) { cancellationToken.ThrowIfCancellationRequested(); int read = responseStream.Read(buffer, 0, buffer_size); reportForwardProgress(); if (read > 0) { ResponseStream.Write(buffer, 0, read); responseBytesRead += read; DownloadProgress?.Invoke(responseBytesRead, response.Content.Headers.ContentLength ?? responseBytesRead); } else { ResponseStream.Seek(0, SeekOrigin.Begin); Complete(); break; } } } } protected virtual void Complete(Exception e = null) { if (Aborted) return; var we = e as WebException; bool allowRetry = AllowRetryOnTimeout; if (e != null) allowRetry &= we?.Status == WebExceptionStatus.Timeout; else if (!response.IsSuccessStatusCode) { e = new WebException(response.StatusCode.ToString()); switch (response.StatusCode) { case HttpStatusCode.GatewayTimeout: case HttpStatusCode.RequestTimeout: break; case HttpStatusCode.NotFound: case HttpStatusCode.MethodNotAllowed: case HttpStatusCode.Forbidden: allowRetry = false; break; case HttpStatusCode.Unauthorized: allowRetry = false; break; } } if (e != null) { if (allowRetry && RetryCount < MAX_RETRIES && responseBytesRead == 0) { RetryCount++; logger.Add($@"Request to {Url} failed with {e} (retrying {RetryCount}/{MAX_RETRIES})."); //do a retry internalPerform(); return; } logger.Add($"Request to {Url} failed with {e}."); } else logger.Add($@"Request to {Url} successfully completed!"); try { ProcessResponse(); } catch (Exception se) { logger.Add($"Processing response from {Url} failed with {se}."); e = e == null ? se : new AggregateException(e, se); } Completed = true; if (e == null) { Finished?.Invoke(); } else { Failed?.Invoke(e); Aborted = true; throw e; } } /// <summary> /// Performs any post-processing of the response. /// Exceptions thrown in this method will be passed to <see cref="Finished"/>. /// </summary> protected virtual void ProcessResponse() { } /// <summary> /// Forcefully abort the request. /// </summary> public void Abort() { if (Aborted || Completed) return; Aborted = true; Completed = true; try { abortToken?.Cancel(); } catch (ObjectDisposedException) { } } /// <summary> /// Adds a raw POST body to this request. /// This may not be used in conjunction with <see cref="AddFile"/> and <see cref="AddParameter"/>. /// </summary> /// <param name="text">The text.</param> public void AddRaw(string text) { AddRaw(Encoding.UTF8.GetBytes(text)); } /// <summary> /// Adds a raw POST body to this request. /// This may not be used in conjunction with <see cref="AddFile"/> and <see cref="AddParameter"/>. /// </summary> /// <param name="bytes">The raw data.</param> public void AddRaw(byte[] bytes) { AddRaw(new MemoryStream(bytes)); } /// <summary> /// Adds a raw POST body to this request. /// This may not be used in conjunction with <see cref="AddFile"/> and <see cref="AddParameter"/>. /// </summary> /// <param name="stream">The stream containing the raw data. This stream will _not_ be finalized by this request.</param> public void AddRaw(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (rawContent == null) rawContent = new MemoryStream(); stream.CopyTo(rawContent); } /// <summary> /// Add a new FILE parameter to this request. Replaces any existing file with the same name. /// This may not be used in conjunction with <see cref="AddRaw(Stream)"/>. GET requests may not contain files. /// </summary> /// <param name="name">The name of the file. This becomes the name of the file in a multi-part form POST content.</param> /// <param name="data">The file data.</param> public void AddFile(string name, byte[] data) { if (name == null) throw new ArgumentNullException(nameof(name)); if (data == null) throw new ArgumentNullException(nameof(data)); files[name] = data; } /// <summary> /// Add a new POST parameter to this request. Replaces any existing parameter with the same name. /// This may not be used in conjunction with <see cref="AddRaw(Stream)"/>. /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="value">The parameter value.</param> public void AddParameter(string name, string value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); parameters[name] = value; } /// <summary> /// Adds a new header to this request. Replaces any existing header with the same name. /// </summary> /// <param name="name">The name of the header.</param> /// <param name="value">The header value.</param> public void AddHeader(string name, string value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); headers[name] = value; } #region Timeout Handling private long lastAction; private long timeSinceLastAction => (DateTime.Now.Ticks - lastAction) / TimeSpan.TicksPerMillisecond; private void reportForwardProgress() { lastAction = DateTime.Now.Ticks; timeoutToken.CancelAfter(Timeout); } #endregion #region IDisposable Support private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; Abort(); requestStream?.Dispose(); response?.Dispose(); if (!(ResponseStream is MemoryStream)) ResponseStream?.Dispose(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private class LengthTrackingStream : Stream { public readonly BindableLong BytesRead = new BindableLong(); private readonly Stream baseStream; public LengthTrackingStream(Stream baseStream) { this.baseStream = baseStream; } public override void Flush() { baseStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { int read = baseStream.Read(buffer, offset, count); BytesRead.Value += read; return read; } public override long Seek(long offset, SeekOrigin origin) { return baseStream.Seek(offset, origin); } public override void SetLength(long value) { baseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { baseStream.Write(buffer, offset, count); } public override bool CanRead => baseStream.CanRead; public override bool CanSeek => baseStream.CanSeek; public override bool CanWrite => baseStream.CanWrite; public override long Length => baseStream.Length; public override long Position { get { return baseStream.Position; } set { baseStream.Position = value; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); baseStream.Dispose(); } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Paramore.Darker.Testing; using Shouldly; using Xunit; namespace Paramore.Darker.Tests { public class FakeQueryProcessorTests { [Fact] public void ReturnsExecutedQueries() { // Arrange var guid = Guid.NewGuid(); var queryProcessor = new FakeQueryProcessor(); // Act queryProcessor.Execute(new TestQueryA(guid)); queryProcessor.Execute(new TestQueryB(100)); queryProcessor.Execute(new TestQueryB(200)); queryProcessor.Execute(new TestQueryB(300)); // Assert queryProcessor.GetExecutedQueries().Count().ShouldBe(4); queryProcessor.GetExecutedQueries<TestQueryA>().Count().ShouldBe(1); queryProcessor.GetExecutedQueries<TestQueryB>().Count().ShouldBe(3); queryProcessor.GetExecutedQueries<TestQueryC>().Count().ShouldBe(0); queryProcessor.GetExecutedQueries<TestQueryA>().Single().Id.ShouldBe(guid); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(0).Number.ShouldBe(100); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(1).Number.ShouldBe(200); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(2).Number.ShouldBe(300); } [Fact] public async Task ReturnsExecutedQueriesAsync() { // Arrange var guid = Guid.NewGuid(); var queryProcessor = new FakeQueryProcessor(); // Act await queryProcessor.ExecuteAsync(new TestQueryA(guid)); await queryProcessor.ExecuteAsync(new TestQueryB(100)); await queryProcessor.ExecuteAsync(new TestQueryB(200)); await queryProcessor.ExecuteAsync(new TestQueryB(300)); // Assert queryProcessor.GetExecutedQueries().Count().ShouldBe(4); queryProcessor.GetExecutedQueries<TestQueryA>().Count().ShouldBe(1); queryProcessor.GetExecutedQueries<TestQueryB>().Count().ShouldBe(3); queryProcessor.GetExecutedQueries<TestQueryC>().Count().ShouldBe(0); queryProcessor.GetExecutedQueries<TestQueryA>().Single().Id.ShouldBe(guid); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(0).Number.ShouldBe(100); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(1).Number.ShouldBe(200); queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(2).Number.ShouldBe(300); } [Fact] public void ReturnsDefaultValueOfQueriesWithoutSetup() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(1234); // Act var result = queryProcessor.Execute(new TestQueryA(Guid.NewGuid())); // Assert result.ShouldBe(default(Guid)); } [Fact] public void ReturnsValueThatWasSetUpForQuery() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(1234); // Act var result = queryProcessor.Execute(new TestQueryB(1337)); // Assert result.ShouldBe(1234); } [Fact] public void ReturnsValueThatWasSetUpForQueryWithPredicate() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234); // Act var result = queryProcessor.Execute(new TestQueryB(1337)); // Assert result.ShouldBe(1234); } [Fact] public void ReturnsComputedValueThatWasSetUpForQueryWithPredicate() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, q => (int)q.Number); // Act var result = queryProcessor.Execute(new TestQueryB(1337)); // Assert result.ShouldBe(1337); } [Fact] public void ReturnsDefaultValueIfQueryDoesntMatchPredicate() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234); // Act var result = queryProcessor.Execute(new TestQueryB(9999)); // Assert result.ShouldBe(default(int)); } [Fact] public void ThrowsForQueryWithThrowSetup() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(new AbandonedMutexException()); // Act + Assert Assert.Throws<AbandonedMutexException>(() => queryProcessor.Execute(new TestQueryB(1337))); } [Fact] public void ThrowsForQueryWithThrowSetupMatchingPredicate() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException()); // Act + Assert Assert.Throws<AbandonedMutexException>(() => queryProcessor.Execute(new TestQueryB(1337))); } [Fact] public void DoesNotThrowIfQueryDoesntMatchPredicate() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException()); // Act var result = queryProcessor.Execute(new TestQueryB(9999)); // Assert result.ShouldBe(default(int)); } [Fact] public async Task ReturnsDefaultValueOfQueriesWithoutSetupAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(1234); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryA(Guid.NewGuid())); // Assert result.ShouldBe(default(Guid)); } [Fact] public async Task ReturnsValueThatWasSetUpForQueryAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(1234); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337)); // Assert result.ShouldBe(1234); } [Fact] public async Task ReturnsValueThatWasSetUpForQueryWithPredicateAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337)); // Assert result.ShouldBe(1234); } [Fact] public async Task ReturnsComputedValueThatWasSetUpForQueryWithPredicateAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, q => (int)q.Number); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337)); // Assert result.ShouldBe(1337); } [Fact] public async Task ReturnsDefaultValueIfQueryDoesntMatchPredicateAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryB(9999)); // Assert result.ShouldBe(default(int)); } [Fact] public async Task ThrowsForQueryWithThrowSetupAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(new AbandonedMutexException()); // Act + Assert await Assert.ThrowsAsync<AbandonedMutexException>(async () => await queryProcessor.ExecuteAsync(new TestQueryB(1337))); } [Fact] public async Task ThrowsForQueryWithThrowSetupMatchingPredicateAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException()); // Act + Assert await Assert.ThrowsAsync<AbandonedMutexException>(async () => await queryProcessor.ExecuteAsync(new TestQueryB(1337))); } [Fact] public async Task DoesNotThrowIfQueryDoesntMatchPredicateAsync() { // Arrange var queryProcessor = new FakeQueryProcessor(); queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException()); // Act var result = await queryProcessor.ExecuteAsync(new TestQueryB(9999)); // Assert result.ShouldBe(default(int)); } public class TestQueryA : IQuery<Guid> { public Guid Id { get; } public TestQueryA(Guid id) { Id = id; } } public class TestQueryB : IQuery<int> { public decimal Number { get; } public TestQueryB(decimal number) { Number = number; } } public class TestQueryC : IQuery<object> { } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net.Mail; using System.Text; using System.Net; using System.Net.Sockets; using System.Net.Security; namespace ACSGhana.Web.Framework { namespace Mail { namespace Pop3 { // Supporting classes and structs // ============================== /// <summary> /// Combines Email ID with Email UID for one email /// The POP3 server assigns to each message a unique Email UID, which will not change for the life time /// of the message and no other message should use the same. /// /// Exceptions: /// Throws Pop3Exception if there is a serious communication problem with the POP3 server, otherwise /// /// </summary> public struct EmailUid { /// <summary> /// used in POP3 commands to indicate which message (only valid in the present session) /// </summary> public int EmailId; /// <summary> /// Uid is always the same for a message, regardless of session /// </summary> public string Uid; /// <summary> /// /// </summary> /// <param name="EmailId"></param> /// <param name="Uid"></param> public EmailUid(int EmailId, string Uid) { this.EmailId = EmailId; this.Uid = Uid; } } /// <summary> /// If anything goes wrong within Pop3MailClient, a Pop3Exception is raised /// </summary> public class Pop3Exception : ApplicationException { /// <summary> /// /// </summary> public Pop3Exception() { } /// <summary> /// /// </summary> /// <param name="ErrorMessage"></param> public Pop3Exception(string ErrorMessage) : base(ErrorMessage) { } } /// <summary> /// A pop 3 connection goes through the following states: /// </summary> public enum Pop3ConnectionStateEnum { /// <summary> /// undefined /// </summary> None = 0, /// <summary> /// not connected yet to POP3 server /// </summary> Disconnected, /// <summary> /// TCP connection has been opened and the POP3 server has sent the greeting. POP3 server expects user name and password /// </summary> Authorization, /// <summary> /// client has identified itself successfully with the POP3, server has locked all messages /// </summary> Connected, /// <summary> /// QUIT command was sent, the server has deleted messages marked for deletion and released the resources /// </summary> Closed } // Delegates for Pop3MailClient // ============================ /// <summary> /// If POP3 Server doesn't react as expected or this code has a problem, but /// can continue with the execution, a Warning is called. /// </summary> /// <param name="WarningText"></param> /// <param name="Response">string received from POP3 server</param> public delegate void WarningHandler(string WarningText, string Response); /// <summary> /// Traces all the information exchanged between POP3 client and POP3 server plus some /// status messages from POP3 client. /// Helpful to investigate any problem. /// Console.WriteLine() can be used /// </summary> /// <param name="TraceText"></param> public delegate void TraceHandler(string TraceText); // Pop3MailClient Class // ==================== /// <summary> /// provides access to emails on a POP3 Server /// </summary> public class Pop3MailClient { //Events //------ /// <summary> /// Called whenever POP3 server doesn't react as expected, but no runtime error is thrown. /// </summary> private WarningHandler WarningEvent; public event WarningHandler Warning { add { WarningEvent = (WarningHandler) System.Delegate.Combine(WarningEvent, value); } remove { WarningEvent = (WarningHandler) System.Delegate.Remove(WarningEvent, value); } } /// <summary> /// call warning event /// </summary> /// <param name="methodName">name of the method where warning is needed</param> /// <param name="response">answer from POP3 server causing the warning</param> /// <param name="warningText">explanation what went wrong</param> /// <param name="warningParameters"></param> protected void CallWarning(string methodName, string response, string warningText, params object[] warningParameters) { warningText = string.Format(warningText, warningParameters); if (WarningEvent != null) { if (WarningEvent != null) WarningEvent(methodName + ": " + warningText, response); } CallTrace("!! {0}", warningText); } /// <summary> /// Shows the communication between PopClient and PopServer, including warnings /// </summary> private TraceHandler TraceEvent; public event TraceHandler Trace { add { TraceEvent = (TraceHandler) System.Delegate.Combine(TraceEvent, value); } remove { TraceEvent = (TraceHandler) System.Delegate.Remove(TraceEvent, value); } } /// <summary> /// call Trace event /// </summary> /// <param name="text">string to be traced</param> /// <param name="parameters"></param> protected void CallTrace(string text, params object[] parameters) { if (TraceEvent != null) { if (TraceEvent != null) TraceEvent(DateTime.Now.ToString("hh:mm:ss ") + PopServer + " " + string.Format(text, parameters)); } } /// <summary> /// Trace information received from POP3 server /// </summary> /// <param name="text">string to be traced</param> /// <param name="parameters"></param> protected void TraceFrom(string text, params object[] parameters) { if (TraceEvent != null) { CallTrace(" " + string.Format(text, parameters), null); } } //Properties //---------- /// <summary> /// Get POP3 server name /// </summary> public string PopServer { get { return m_popServer; } } /// <summary> /// POP3 server name /// </summary> protected string m_popServer; /// <summary> /// Get POP3 server port /// </summary> public int Port { get { return m_port; } } /// <summary> /// POP3 server port /// </summary> protected int m_port; /// <summary> /// Should SSL be used for connection with POP3 server /// </summary> public bool UseSSL { get { return m_useSSL; } } /// <summary> /// Should SSL be used for connection with POP3 server /// </summary> private bool m_useSSL; /// <summary> /// should Pop3MailClient automatically reconnect if POP3 server has dropped the /// connection due to a timeout /// </summary> public bool IsAutoReconnect { get { return n_isAutoReconnect; } set { n_isAutoReconnect = value; } } private bool n_isAutoReconnect = false; //timeout has occured, we try to perform an autoreconnect private bool isTimeoutReconnect = false; /// <summary> /// Get / set read timeout (miliseconds) /// </summary> public int ReadTimeout { get { return System.Convert.ToInt32(m_readTimeout == 0 ? System.Threading.Timeout.Infinite : m_readTimeout); } set { m_readTimeout = value; if (pop3Stream != null&& pop3Stream.CanTimeout) { pop3Stream.ReadTimeout = m_readTimeout; } } } /// <summary> /// POP3 server read timeout /// </summary> protected int m_readTimeout = - 1; /// <summary> /// Get owner name of mailbox on POP3 server /// </summary> public string Username { get { return m_username; } } /// <summary> /// Owner name of mailbox on POP3 server /// </summary> protected string m_username; /// <summary> /// Get password for mailbox on POP3 server /// </summary> public string Password { get { return m_password; } } /// <summary> /// Password for mailbox on POP3 server /// </summary> protected string m_password; /// <summary> /// Get connection status with POP3 server /// </summary> public Pop3ConnectionStateEnum Pop3ConnectionState { get { return m_pop3ConnectionState; } } /// <summary> /// connection status with POP3 server /// </summary> protected Pop3ConnectionStateEnum m_pop3ConnectionState = Pop3ConnectionStateEnum.Disconnected; // Methods // ------- /// <summary> /// set POP3 connection state /// </summary> /// <param name="State"></param> protected void setPop3ConnectionState(Pop3ConnectionStateEnum State) { m_pop3ConnectionState = State; CallTrace(" Pop3MailClient Connection State {0} reached", State); } /// <summary> /// throw exception if POP3 connection is not in the required state /// </summary> /// <param name="requiredState"></param> protected void EnsureState(Pop3ConnectionStateEnum requiredState) { if (m_pop3ConnectionState != requiredState) { // wrong connection state throw (new Pop3Exception("GetMailboxStats only accepted during connection state: " + requiredState.ToString() + Constants.vbLf + " The connection to server " + PopServer + " is in state " + Pop3ConnectionState.ToString())); } } //private fields //-------------- /// <summary> /// TCP to POP3 server /// </summary> private TcpClient serverTcpConnection; /// <summary> /// Stream from POP3 server with or without SSL /// </summary> private Stream pop3Stream; /// <summary> /// Reader for POP3 message /// </summary> protected StreamReader pop3StreamReader; /// <summary> /// char 'array' for carriage return / line feed /// </summary> protected string CRLF = Constants.vbCrLf; //public methods //-------------- /// <summary> /// Make POP3 client ready to connect to POP3 server /// </summary> /// <param name="PopServer"><example>pop.gmail.com</example></param> /// <param name="Port"><example>995</example></param> /// <param name="useSSL">True: SSL is used for connection to POP3 server</param> /// <param name="Username"><example>abc@gmail.com</example></param> /// <param name="Password">Secret</param> public Pop3MailClient(string PopServer, int Port, bool useSSL, string Username, string Password) { this.m_popServer = PopServer; this.m_port = Port; this.m_useSSL = useSSL; this.m_username = Username; this.m_password = Password; } /// <summary> /// Connect to POP3 server /// </summary> public void Connect() { if (Pop3ConnectionState != Pop3ConnectionStateEnum.Disconnected && Pop3ConnectionState != Pop3ConnectionStateEnum.Closed && (! isTimeoutReconnect)) { CallWarning("connect", "", "Connect command received, but connection state is: " + Pop3ConnectionState.ToString(), null); } else { //establish TCP connection try { CallTrace(" Connect at port {0}", Port); serverTcpConnection = new TcpClient(PopServer, Port); } catch (System.Exception ex) { throw (new Pop3Exception("Connection to server " + PopServer + ", port " + Port + " failed." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } if (UseSSL) { //get SSL stream try { CallTrace(" Get SSL connection", null); pop3Stream = new SslStream(serverTcpConnection.GetStream(), false); pop3Stream.ReadTimeout = ReadTimeout; } catch (System.Exception ex) { throw (new Pop3Exception("Server " + PopServer + " found, but cannot get SSL data stream." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } //perform SSL authentication try { CallTrace(" Get SSL authentication", null); ((SslStream) pop3Stream).AuthenticateAsClient(PopServer); } catch (System.Exception ex) { throw (new Pop3Exception("Server " + PopServer + " found, but problem with SSL Authentication." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } } else { //create a stream to POP3 server without using SSL try { CallTrace(" Get connection without SSL", null); pop3Stream = serverTcpConnection.GetStream(); pop3Stream.ReadTimeout = ReadTimeout; } catch (System.Exception ex) { throw (new Pop3Exception("Server " + PopServer + " found, but cannot get data stream (without SSL)." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } } //get stream for reading from pop server //POP3 allows only US-ASCII. The message will be translated in the proper encoding in a later step try { pop3StreamReader = new StreamReader(pop3Stream, Encoding.ASCII); } catch (System.Exception ex) { if (UseSSL) { throw (new Pop3Exception("Server " + PopServer + " found, but cannot read from SSL stream." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } else { throw (new Pop3Exception("Server " + PopServer + " found, but cannot read from stream (without SSL)." + Constants.vbLf + "Runtime Error: " + ex.ToString())); } } //ready for authorisation string response = Constants.vbNullString; if (! readSingleLine(ref response)) { throw (new Pop3Exception("Server " + PopServer + " not ready to start AUTHORIZATION." + Constants.vbLf + "Message: " + response)); } setPop3ConnectionState(Pop3ConnectionStateEnum.Authorization); //send user name if (! executeCommand("USER " + Username, ref response)) { throw (new Pop3Exception("Server " + PopServer + " doesn\'t accept username \'" + Username + "\'." + Constants.vbLf + "Message: " + response)); } //send password if (! executeCommand("PASS " + Password, ref response)) { throw (new Pop3Exception("Server " + PopServer + " doesn\'t accept password \'" + Password + "\' for user \'" + Username + "\'." + Constants.vbLf + "Message: " + response)); } setPop3ConnectionState(Pop3ConnectionStateEnum.Connected); } } /// <summary> /// Disconnect from POP3 Server /// </summary> public void Disconnect() { if (Pop3ConnectionState == Pop3ConnectionStateEnum.Disconnected || Pop3ConnectionState == Pop3ConnectionStateEnum.Closed) { CallWarning("disconnect", "", "Disconnect received, but was already disconnected.", null); } else { //ask server to end session and possibly to remove emails marked for deletion try { string response = Constants.vbNullString; if (executeCommand("QUIT", ref response)) { //server says everything is ok setPop3ConnectionState(Pop3ConnectionStateEnum.Closed); } else { //server says there is a problem CallWarning("Disconnect", response, "negative response from server while closing connection: " + response, null); setPop3ConnectionState(Pop3ConnectionStateEnum.Disconnected); } } finally { //close connection if (pop3Stream != null) { pop3Stream.Close(); } pop3StreamReader.Close(); } } } /// <summary> /// Delete message from server. /// The POP3 server marks the message as deleted. Any future /// reference to the message-number associated with the message /// in a POP3 command generates an error. The POP3 server does /// not actually delete the message until the POP3 session /// enters the UPDATE state. /// </summary> /// <param name="msg_number"></param> /// <returns></returns> public bool DeleteEmail(int msg_number) { EnsureState(Pop3ConnectionStateEnum.Connected); string response = Constants.vbNullString; if (! executeCommand("DELE " + msg_number.ToString(), ref response)) { CallWarning("DeleteEmail", response, "negative response for email (Id: {0}) delete request", msg_number); return false; } return true; } /// <summary> /// Get a list of all Email IDs available in mailbox /// </summary> /// <returns></returns> public bool GetEmailIdList([System.Runtime.InteropServices.Out()]ref List<int> EmailIds) { EnsureState(Pop3ConnectionStateEnum.Connected); EmailIds = new List<int>(); //get server response status line string response = Constants.vbNullString; if (! executeCommand("LIST", ref response)) { CallWarning("GetEmailIdList", response, "negative response for email list request", null); return false; } //get every email id int EmailId; while (readMultiLine(ref response)) { if (int.TryParse(response.Split(' ')[0], ref EmailId)) { EmailIds.Add(EmailId); } else { CallWarning("GetEmailIdList", response, "first characters should be integer (EmailId)", null); } } TraceFrom("{0} email ids received", EmailIds.Count); return true; } /// <summary> /// get size of one particular email /// </summary> /// <param name="msg_number"></param> /// <returns></returns> public int GetEmailSize(int msg_number) { EnsureState(Pop3ConnectionStateEnum.Connected); string response = Constants.vbNullString; executeCommand("LIST " + msg_number.ToString(), ref response); int EmailSize = 0; string[] responseSplit = response.Split(' '); if (responseSplit.Length < 2 || (! int.TryParse(responseSplit[2], ref EmailSize))) { CallWarning("GetEmailSize", response, "\'+OK int int\' format expected (EmailId, EmailSize)", null); } return EmailSize; } /// <summary> /// Get a list with the unique IDs of all Email available in mailbox. /// /// Explanation: /// EmailIds for the same email can change between sessions, whereas the unique Email id /// never changes for an email. /// </summary> /// <param name="EmailIds"></param> /// <returns></returns> public bool GetUniqueEmailIdList([System.Runtime.InteropServices.Out()]ref List<EmailUid> EmailIds) { EnsureState(Pop3ConnectionStateEnum.Connected); EmailIds = new List<EmailUid>(); //get server response status line string response = Constants.vbNullString; if (! executeCommand("UIDL ", ref response)) { CallWarning("GetUniqueEmailIdList", response, "negative response for email list request", null); return false; } //get every email unique id int EmailId; while (readMultiLine(ref response)) { string[] responseSplit = response.Split(' '); if (responseSplit.Length < 2) { CallWarning("GetUniqueEmailIdList", response, "response not in format \'int string\'", null); } else if (! int.TryParse(responseSplit[0], ref EmailId)) { CallWarning("GetUniqueEmailIdList", response, "first charaters should be integer (Unique EmailId)", null); } else { EmailIds.Add(new EmailUid(EmailId, responseSplit[1])); } } TraceFrom("{0} unique email ids received", EmailIds.Count); return true; } /// <summary> /// get a list with all currently available messages and the UIDs /// </summary> /// <param name="EmailIds">EmailId Uid list</param> /// <returns>false: server sent negative response (didn't send list)</returns> public bool GetUniqueEmailIdList([System.Runtime.InteropServices.Out()]ref SortedList<string, int> EmailIds) { EnsureState(Pop3ConnectionStateEnum.Connected); EmailIds = new SortedList<string, int>(); //get server response status line string response = Constants.vbNullString; if (! executeCommand("UIDL", ref response)) { CallWarning("GetUniqueEmailIdList", response, "negative response for email list request", null); return false; } //get every email unique id int EmailId; while (readMultiLine(ref response)) { string[] responseSplit = response.Split(' '); if (responseSplit.Length < 2) { CallWarning("GetUniqueEmailIdList", response, "response not in format \'int string\'", null); } else if (! int.TryParse(responseSplit[0], ref EmailId)) { CallWarning("GetUniqueEmailIdList", response, "first charaters should be integer (Unique EmailId)", null); } else { EmailIds.Add(responseSplit[1], EmailId); } } TraceFrom("{0} unique email ids received", EmailIds.Count); return true; } /// <summary> /// get size of one particular email /// </summary> /// <param name="msg_number"></param> /// <returns></returns> public int GetUniqueEmailId(EmailUid msg_number) { EnsureState(Pop3ConnectionStateEnum.Connected); string response = Constants.vbNullString; executeCommand("LIST " + msg_number.ToString(), ref response); int EmailSize = 0; string[] responseSplit = response.Split(' '); if (responseSplit.Length < 2 || (! int.TryParse(responseSplit[2], ref EmailSize))) { CallWarning("GetEmailSize", response, "\'+OK int int\' format expected (EmailId, EmailSize)", null); } return EmailSize; } /// <summary> /// Sends an 'empty' command to the POP3 server. Server has to respond with +OK /// </summary> /// <returns>true: server responds as expected</returns> public bool NOOP() { EnsureState(Pop3ConnectionStateEnum.Connected); string response = Constants.vbNullString; if (! executeCommand("NOOP", ref response)) { CallWarning("NOOP", response, "negative response for NOOP request", null); return false; } return true; } /// <summary> /// Should the raw content, the US-ASCII code as received, be traced /// GetRawEmail will switch it on when it starts and off once finished /// /// Inheritors might use it to get the raw email /// </summary> protected bool isTraceRawEmail = false; /// <summary> /// contains one MIME part of the email in US-ASCII, needs to be translated in .NET string (Unicode) /// contains the complete email in US-ASCII, needs to be translated in .NET string (Unicode) /// For speed reasons, reuse StringBuilder /// </summary> protected StringBuilder RawEmailSB; /// <summary> /// Reads the complete text of a message /// </summary> /// <param name="MessageNo">Email to retrieve</param> /// <param name="EmailText">ASCII string of complete message</param> /// <returns></returns> public bool GetRawEmail(int MessageNo, [System.Runtime.InteropServices.Out()]ref string EmailText) { //send 'RETR int' command to server if (! SendRetrCommand(MessageNo)) { EmailText = null; return false; } //get the lines string response = Constants.vbNullString; int LineCounter = 0; //empty StringBuilder if (RawEmailSB == null) { RawEmailSB = new StringBuilder(100000); } else { RawEmailSB.Length = 0; } isTraceRawEmail = true; while (readMultiLine(ref response)) { LineCounter++; } EmailText = RawEmailSB.ToString(); TraceFrom("email with {0} lines, {1} chars received", LineCounter.ToString(), EmailText.Length); return true; } ///// <summary> ///// Requests from POP3 server a specific email and returns a stream with the message content (header and body) ///// </summary> ///// <param name="MessageNo"></param> ///// <param name="EmailStreamReader"></param> ///// <returns>false: POP3 server cannot provide this message</returns> //public bool GetEmailStream(int MessageNo, out StreamReader EmailStreamReader) { // //send 'RETR int' command to server // if (!SendRetrCommand(MessageNo)) { // EmailStreamReader = null; // return false; // } // EmailStreamReader = sslStreamReader; // return true; //} /// <summary> /// Unmark any emails from deletion. The server only deletes email really /// once the connection is properly closed. /// </summary> /// <returns>true: emails are unmarked from deletion</returns> public bool UndeleteAllEmails() { EnsureState(Pop3ConnectionStateEnum.Connected); string response = Constants.vbNullString; return executeCommand("RSET", ref response); } /// <summary> /// Get mailbox statistics /// </summary> /// <param name="NumberOfMails"></param> /// <param name="MailboxSize"></param> /// <returns></returns> public bool GetMailboxStats([System.Runtime.InteropServices.Out()]ref int NumberOfMails, [System.Runtime.InteropServices.Out()]ref int MailboxSize) { EnsureState(Pop3ConnectionStateEnum.Connected); //interpret response string response = Constants.vbNullString; NumberOfMails = 0; MailboxSize = 0; if (executeCommand("STAT", ref response)) { //got a positive response string[] responseParts = response.Split(' '); if (responseParts.Length < 2) { //response format wrong throw (new Pop3Exception("Server " + PopServer + " sends illegally formatted response." + Constants.vbLf + "Expected format: +OK int int" + Constants.vbLf + "Received response: " + response)); } NumberOfMails = int.Parse(responseParts[1]); MailboxSize = int.Parse(responseParts[2]); return true; } return false; } /// <summary> /// Send RETR command to POP 3 server to fetch one particular message /// </summary> /// <param name="MessageNo">ID of message required</param> /// <returns>false: negative server respond, message not delivered</returns> protected bool SendRetrCommand(int MessageNo) { EnsureState(Pop3ConnectionStateEnum.Connected); // retrieve mail with message number string response = Constants.vbNullString; if (! executeCommand("RETR " + MessageNo.ToString(), ref response)) { CallWarning("GetRawEmail", response, "negative response for email (ID: {0}) request", MessageNo); return false; } return true; } //Helper methodes //--------------- public bool isDebug = false; /// <summary> /// sends the 4 letter command to POP3 server (adds CRLF) and waits for the /// response of the server /// </summary> /// <param name="commandText">command to be sent to server</param> /// <param name="response">answer from server</param> /// <returns>false: server sent negative acknowledge, i.e. server could not execute command</returns> private bool executeCommand(string commandText, [System.Runtime.InteropServices.Out()]ref string response) { //send command to server byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((commandText + CRLF).ToCharArray()); CallTrace("Tx \'{0}\'", commandText); bool isSupressThrow = false; try { pop3Stream.Write(commandBytes, 0, commandBytes.Length); if (isDebug) { isDebug = false; throw (new IOException("Test", new SocketException(10053))); } } catch (IOException ex) { //Unable to write data to the transport connection. Check if reconnection should be tried isSupressThrow = executeReconnect(ex, commandText, commandBytes); if (! isSupressThrow) { throw; } } pop3Stream.Flush(); //read response from server response = null; try { response = pop3StreamReader.ReadLine(); } catch (IOException ex) { //Unable to write data to the transport connection. Check if reconnection should be tried isSupressThrow = executeReconnect(ex, commandText, commandBytes); if (isSupressThrow) { //wait for response one more time response = pop3StreamReader.ReadLine(); } else { throw; } } if (response == null) { throw (new Pop3Exception("Server " + PopServer + " has not responded, timeout has occured.")); } CallTrace("Rx \'{0}\'", response); return (response.Length > 0 && response[0] == '+'); } /// <summary> /// reconnect, if there is a timeout exception and isAutoReconnect is true /// /// </summary> private bool executeReconnect(IOException ex, string command, byte[] commandBytes) { if (ex.InnerException != null&& ex.InnerException is SocketException) { //SocketException SocketException innerEx = (SocketException) ex.InnerException; if (innerEx.ErrorCode == 10053) { //probably timeout: An established connection was aborted by the software in your host machine. CallWarning("ExecuteCommand", "", "probably timeout occured", null); if (IsAutoReconnect) { //try to reconnect and send one more time isTimeoutReconnect = true; try { CallTrace(" try to auto reconnect", null); Connect(); CallTrace(" reconnect successful, try to resend command", null); CallTrace("Tx \'{0}\'", command); pop3Stream.Write(commandBytes, 0, commandBytes.Length); pop3Stream.Flush(); return true; } finally { isTimeoutReconnect = false; } } } } return false; } // ///// <summary> ///// sends the 4 letter command to POP3 server (adds CRLF) ///// </summary> ///// <param name="command"></param> //protected void SendCommand(string command) { //byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray()); //CallTrace("Tx '{0}'", command); //try { //pop3Stream.Write(commandBytes, 0, commandBytes.Length); //} catch (IOException ex) { ////Unable to write data to the transport connection: //if (ex.InnerException!=null && ex.InnerException is SocketException) { ////SocketException //SocketException innerEx = (SocketException)ex.InnerException; //if (innerEx.ErrorCode==10053) { ////probably timeout: An established connection was aborted by the software in your host machine. //CallWarning("SendCommand", "", "probably timeout occured"); //if (isAutoReconnect) { ////try to reconnect and send one more time //isTimeoutReconnect = true; //try { //CallTrace(" try to auto reconnect"); //Connect(); //CallTrace(" reconnect successful, try to resend command"); //CallTrace("Tx '{0}'", command); //pop3Stream.Write(commandBytes, 0, commandBytes.Length); //} finally { //isTimeoutReconnect = false; //} //return; //} //} //} //throw; //} //pop3Stream.Flush(); //} // /// <summary> /// read single line response from POP3 server. /// <example>Example server response: +OK asdfkjahsf</example> /// </summary> /// <param name="response">response from POP3 server</param> /// <returns>true: positive response</returns> protected bool readSingleLine([System.Runtime.InteropServices.Out()]ref string response) { response = null; try { response = pop3StreamReader.ReadLine(); } catch (System.Exception ex) { string s = ex.Message; } if (response == null) { throw (new Pop3Exception("Server " + PopServer + " has not responded, timeout has occured.")); } CallTrace("Rx \'{0}\'", response); return (response.Length > 0 && response[0] == '+'); } /// <summary> /// read one line in multiline mode from the POP3 server. /// </summary> /// <param name="response">line received</param> /// <returns>false: end of message</returns> protected bool readMultiLine([System.Runtime.InteropServices.Out()]ref string response) { response = null; response = pop3StreamReader.ReadLine(); if (response == null) { throw (new Pop3Exception("Server " + PopServer + " has not responded, probably timeout has occured.")); } if (isTraceRawEmail) { //collect all responses as received RawEmailSB.Append(response + CRLF); } //check for byte stuffing, i.e. if a line starts with a '.', another '.' is added, unless //it is the last line if (response.Length > 0 && response[0] == '.') { if (response == ".") { //closing line found return false; } //remove the first '.' response = response.Substring(1, response.Length - 1); } return true; } } } } }
//----------------------------------------------------------------------- // <copyright file="SackCollection.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultData { using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; /// <summary> /// Sack panel types /// </summary> public enum SackType { /// <summary> /// Sack panel /// </summary> Sack = 0, /// <summary> /// Stash panel /// </summary> Stash, /// <summary> /// Equipment panel /// </summary> Equipment, /// <summary> /// Player panel /// </summary> Player, /// <summary> /// Vault panel /// </summary> Vault, /// <summary> /// Trash panel /// </summary> Trash, /// <summary> /// Transfer stash /// </summary> TransferStash } /// <summary> /// Encodes and decodes a Titan Quest item sack from a player file. /// </summary> public class SackCollection : IEnumerable<Item> { /// <summary> /// Cell offsets for the slots in the equipment panel. /// Indicates the upper left cell of the slot. /// </summary> private static Point[] equipmentLocationOffsets = { new Point(4, 0), // Head new Point(4, 3), // Neck new Point(4, 5), // Body new Point(4, 9), // Legs new Point(7, 6), // Arms new Point(4, 12), // Ring1 new Point(5, 12), // Ring2 // Use x = -3 to flag as a weapon // Use y value as index into weaponLocationOffsets new Point(Item.WeaponSlotIndicator, 0), // Weapon1 new Point(Item.WeaponSlotIndicator, 1), // Shield1 new Point(Item.WeaponSlotIndicator, 2), // Weapon2 new Point(Item.WeaponSlotIndicator, 3), // Shield2 new Point(1, 6), // Artifact }; /// <summary> /// Sizes of the slots in the equipment panel /// </summary> private static Size[] equipmentLocationSizes = { new Size(2, 2), // Head new Size(1, 1), // Neck new Size(2, 3), // Body new Size(2, 2), // Legs new Size(2, 2), // Arms new Size(1, 1), // Ring1 new Size(1, 1), // Ring2 new Size(2, 5), // Weapon1 new Size(2, 5), // Shield1 new Size(2, 5), // Weapon2 new Size(2, 5), // Shield2 new Size(2, 2), // Artifact }; /// <summary> /// Used to properly draw the weapon the weapon box on the equipment panel /// These values are the upper left corner of the weapon box /// </summary> private static Point[] weaponLocationOffsets = { new Point(1, 0), // Weapon1 new Point(7, 0), // Shield1 new Point(1, 9), // Weapon2 new Point(7, 9), // Shield2 }; /// <summary> /// Size of the weapon slots in the equipment panel /// </summary> private static Size weaponLocationSize = new Size(2, 5); /// <summary> /// Begin Block header in the file. /// </summary> private int beginBlockCrap; /// <summary> /// End Block header in the file /// </summary> private int endBlockCrap; /// <summary> /// TempBool entry in the file. /// </summary> private int tempBool; /// <summary> /// Number of items in the sack according to TQ. /// </summary> private int size; /// <summary> /// Items contained in this sack /// </summary> private List<Item> items; /// <summary> /// Flag to indicate this sack has been modified. /// </summary> private bool isModified; /// <summary> /// Indicates the type of sack /// </summary> private SackType sackType; /// <summary> /// Indicates whether this is Immortal Throne /// </summary> private bool isImmortalThrone; /// <summary> /// Number of equipment slots /// </summary> private int slots; /// <summary> /// Initializes a new instance of the SackCollection class. /// </summary> public SackCollection() { this.items = new List<Item>(); this.sackType = SackType.Sack; } /// <summary> /// Gets the Weapon slot size /// </summary> public static Size WeaponLocationSize { get { return weaponLocationSize; } } /// <summary> /// Gets the total number of offsets in the weapon location offsets array. /// </summary> public static int NumberOfWeaponSlots { get { return weaponLocationOffsets.Length; } } /// <summary> /// Gets or sets a value indicating whether this sack has been modified /// </summary> public bool IsModified { get { return this.isModified; } set { this.isModified = value; } } /// <summary> /// Gets or sets the sack type /// </summary> public SackType SackType { get { return this.sackType; } set { this.sackType = value; } } /// <summary> /// Gets or sets a value indicating whether this is from Immortal Throne /// </summary> public bool IsImmortalThrone { get { return this.isImmortalThrone; } set { this.isImmortalThrone = value; } } /// <summary> /// Gets the number of equipment slots /// </summary> public int NumberOfSlots { get { return this.slots; } } /// <summary> /// Gets the number of items in the sack. /// </summary> public int Count { get { return this.items.Count; } } /// <summary> /// Gets a value indicating whether the number of items in the sack is equal to zero. /// </summary> public bool IsEmpty { get { return this.items.Count == 0; } } /// <summary> /// Gets offset of the weapon slot /// </summary> /// <param name="weaponSlot">weapon slot number we are looking for</param> /// <returns>Point of the upper left corner cell of the slot</returns> public static Point GetWeaponLocationOffset(int weaponSlot) { if (weaponSlot < 0 || weaponSlot > NumberOfWeaponSlots) { return Point.Empty; } return weaponLocationOffsets[weaponSlot]; } /// <summary> /// Gets the size of an equipment slot /// </summary> /// <param name="equipmentSlot">weapon slot number we are looking for</param> /// <returns>Size of the weapon slot</returns> public static Size GetEquipmentLocationSize(int equipmentSlot) { if (equipmentSlot < 0 || equipmentSlot > equipmentLocationSizes.Length) { return Size.Empty; } return equipmentLocationSizes[equipmentSlot]; } /// <summary> /// Gets the upper left cell of an equipment slot /// </summary> /// <param name="equipmentSlot">equipment slot we are looking for.</param> /// <returns>Point of the upper left cell of the slot.</returns> public static Point GetEquipmentLocationOffset(int equipmentSlot) { if (equipmentSlot < 0 || equipmentSlot > equipmentLocationOffsets.Length) { return Point.Empty; } return equipmentLocationOffsets[equipmentSlot]; } /// <summary> /// Gets whether the item is located in a weapon slot. /// </summary> /// <param name="equipmentSlot">slot that we are checking</param> /// <returns>true if the slot is a weapon slot.</returns> public static bool IsWeaponSlot(int equipmentSlot) { if (equipmentSlot < 0 || equipmentSlot > equipmentLocationOffsets.Length) { return false; } return equipmentLocationOffsets[equipmentSlot].X == Item.WeaponSlotIndicator; } /// <summary> /// IEnumerator interface implementation. Iterates all of the items in the sack. /// </summary> /// <returns>Items in the sack.</returns> public IEnumerator<Item> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this.GetItem(i); } } /// <summary> /// Non Generic enumerator interface. /// </summary> /// <returns>Generic interface implementation.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Gets the index in the item list of a particular Item /// </summary> /// <param name="item">Item that we are looking for</param> /// <returns>index in the item array</returns> public int IndexOfItem(Item item) { return this.items.IndexOf(item); } /// <summary> /// Removes an Item from the item list /// </summary> /// <param name="item">Item we are removing</param> public void RemoveItem(Item item) { this.items.Remove(item); this.IsModified = true; } /// <summary> /// Removes an Item from the item list at the specified index /// </summary> /// <param name="index">index position of the item we are removing</param> public void RemoveAtItem(int index) { this.items.RemoveAt(index); this.IsModified = true; } /// <summary> /// Adds an item to the end of the item list /// </summary> /// <param name="item">Item we are adding</param> public void AddItem(Item item) { this.items.Add(item); this.IsModified = true; } /// <summary> /// Inserts an item at a specific position in the item list. /// </summary> /// <param name="index">index where we are performing the insert.</param> /// <param name="item">item we are inserting</param> public void InsertItem(int index, Item item) { this.items.Insert(index, item); this.IsModified = true; } /// <summary> /// Clears the item list /// </summary> public void EmptySack() { this.items.Clear(); this.IsModified = true; } /// <summary> /// Duplicates the whole sack contents /// </summary> /// <returns>Sack instance of the duplicate sack</returns> public SackCollection Duplicate() { SackCollection newSack = new SackCollection(); foreach (Item item in this) { newSack.AddItem(item.Clone()); } return newSack; } /// <summary> /// Gets an item at the specified index in the item array. /// </summary> /// <param name="index">index in the item array</param> /// <returns>Item from the array at the specified index</returns> public Item GetItem(int index) { return this.items[index]; } /// <summary> /// Gets the number of items according to TQ where each potion counts for 1. /// </summary> /// <returns>integer containing the number of items</returns> public int CountTQItems() { int ans = 0; foreach (Item item in this) { if (item.DoesStack) { ans += item.StackSize; } else { ans++; } } return ans; } /// <summary> /// Encodes the sack into binary form /// </summary> /// <param name="writer">BinaryWriter instance</param> public void Encode(BinaryWriter writer) { if (this.sackType == SackType.Stash) { // Item stacks are stored as single items in the stash TQData.WriteCString(writer, "numItems"); writer.Write(this.Count); } else if (this.sackType == SackType.Equipment) { // Nothing special except to skip all of the other header crap // since the number of items is always fixed. } else { TQData.WriteCString(writer, "begin_block"); writer.Write(this.beginBlockCrap); TQData.WriteCString(writer, "tempBool"); writer.Write(this.tempBool); TQData.WriteCString(writer, "size"); writer.Write(this.CountTQItems()); } int slotNumber = -1; foreach (Item item in this) { ++slotNumber; item.ContainerType = this.sackType; int itemAttached = 0; int alternate = 0; // Additional logic to encode the weapon slots in the equipment section if (this.sackType == SackType.Equipment && (slotNumber == 7 || slotNumber == 9)) { TQData.WriteCString(writer, "begin_block"); writer.Write(this.beginBlockCrap); TQData.WriteCString(writer, "alternate"); if (slotNumber == 9) { // Only set the flag for the second set of weapons alternate = 1; } else { // Otherwise set the flag to false. alternate = 0; } writer.Write(alternate); } item.Encode(writer); if (this.sackType == SackType.Equipment) { TQData.WriteCString(writer, "itemAttached"); if (!string.IsNullOrEmpty(item.BaseItemId) && slotNumber != 9 && slotNumber != 10) { // If there is an item in this slot, set the flag. // Unless it's in the secondary weapon slot. itemAttached = 1; } else { // This is only a dummy item so we do not set the flag. itemAttached = 0; } writer.Write(itemAttached); } // Additional logic to encode the weapon slots in the equipment section if (this.sackType == SackType.Equipment && (slotNumber == 8 || slotNumber == 10)) { TQData.WriteCString(writer, "end_block"); writer.Write(this.endBlockCrap); } } TQData.WriteCString(writer, "end_block"); writer.Write(this.endBlockCrap); } /// <summary> /// Parses the binary sack data to internal data /// </summary> /// <param name="reader">BinaryReader instance</param> public void Parse(BinaryReader reader) { try { this.isModified = false; if (this.sackType == SackType.Stash) { // IL decided to use a different format for the stash files. TQData.ValidateNextString("numItems", reader); this.size = reader.ReadInt32(); } else if (this.sackType == SackType.Equipment) { if (this.isImmortalThrone) { this.size = 12; this.slots = 12; } else { this.size = 11; this.slots = 11; } } else { // This is just a regular sack. TQData.ValidateNextString("begin_block", reader); // make sure we just read a new block this.beginBlockCrap = reader.ReadInt32(); TQData.ValidateNextString("tempBool", reader); this.tempBool = reader.ReadInt32(); TQData.ValidateNextString("size", reader); this.size = reader.ReadInt32(); } this.items = new List<Item>(this.size); Item prevItem = null; for (int i = 0; i < this.size; ++i) { // Additional logic to decode the weapon slots in the equipment section if (this.sackType == SackType.Equipment && (i == 7 || i == 9)) { TQData.ValidateNextString("begin_block", reader); this.beginBlockCrap = reader.ReadInt32(); // Eat the alternate tag and flag TQData.ValidateNextString("alternate", reader); // Skip over the alternateCrap reader.ReadInt32(); } Item item = new Item(); item.ContainerType = this.sackType; item.Parse(reader); // Stack this item with the previous item if necessary if ((prevItem != null) && item.DoesStack && (item.PositionX == -1) && (item.PositionY == -1)) { prevItem.StackSize++; } else { prevItem = item; this.items.Add(item); if (this.sackType == SackType.Equipment) { // Get the item location from the table item.PositionX = GetEquipmentLocationOffset(i).X; item.PositionY = GetEquipmentLocationOffset(i).Y; // Eat the itemAttached tag and flag TQData.ValidateNextString("itemAttached", reader); // Skip over the itemAttachedCrap reader.ReadInt32(); } } // Additional logic to decode the weapon slots in the equipment section if (this.sackType == SackType.Equipment && (i == 8 || i == 10)) { TQData.ValidateNextString("end_block", reader); this.endBlockCrap = reader.ReadInt32(); } } TQData.ValidateNextString("end_block", reader); this.endBlockCrap = reader.ReadInt32(); } catch (ArgumentException) { // The ValidateNextString Method can throw an ArgumentException. // We just pass it along at this point. throw; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ExistingWebApplication.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); } } } }
// 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 ShuffleSByte() { var test = new SimpleBinaryOpTest__ShuffleSByte(); 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(); if (Sse2.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 (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 class works test.RunClassLclFldScenario(); if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__ShuffleSByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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 Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShuffleSByte testClass) { var result = Ssse3.Shuffle(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShuffleSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShuffleSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__ShuffleSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.Shuffle( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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 = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_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 = Ssse3.Shuffle( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_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(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.Shuffle( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.LoadVector128((SByte*)(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<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Ssse3.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Ssse3.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Ssse3.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShuffleSByte(); var result = Ssse3.Shuffle(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__ShuffleSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.Shuffle(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(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 = Ssse3.Shuffle(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 = Ssse3.Shuffle( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.LoadVector128((SByte*)(&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(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((right[0] < 0) ? 0 : left[right[0] & 0x0F])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((right[i] < 0) ? 0 : left[right[i] & 0x0F])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.Shuffle)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Umbraco.Core; using Umbraco.Core.Dictionary; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using umbraco; namespace Umbraco.Web.Models.Mapping { /// <summary> /// Creates the tabs collection with properties assigned for display models /// </summary> internal class TabsAndPropertiesResolver : ValueResolver<IContentBase, IEnumerable<Tab<ContentPropertyDisplay>>> { private ICultureDictionary _cultureDictionary; protected IEnumerable<string> IgnoreProperties { get; set; } public TabsAndPropertiesResolver() { IgnoreProperties = new List<string>(); } public TabsAndPropertiesResolver(IEnumerable<string> ignoreProperties) { if (ignoreProperties == null) throw new ArgumentNullException("ignoreProperties"); IgnoreProperties = ignoreProperties; } /// <summary> /// Maps properties on to the generic properties tab /// </summary> /// <param name="content"></param> /// <param name="display"></param> /// <param name="customProperties"> /// Any additional custom properties to assign to the generic properties tab. /// </param> /// <remarks> /// The generic properties tab is mapped during AfterMap and is responsible for /// setting up the properties such as Created date, updated date, template selected, etc... /// </remarks> public static void MapGenericProperties<TPersisted>( TPersisted content, ContentItemDisplayBase<ContentPropertyDisplay, TPersisted> display, params ContentPropertyDisplay[] customProperties) where TPersisted : IContentBase { var genericProps = display.Tabs.Single(x => x.Id == 0); //store the current props to append to the newly inserted ones var currProps = genericProps.Properties.ToArray(); var labelEditor = PropertyEditorResolver.Current.GetByAlias(Constants.PropertyEditors.NoEditAlias).ValueEditor.View; var contentProps = new List<ContentPropertyDisplay> { new ContentPropertyDisplay { Alias = string.Format("{0}id", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "Id", Value = Convert.ToInt32(display.Id).ToInvariantString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}creator", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "createBy"), Description = ui.Text("content", "createByDesc"), //TODO: Localize this Value = display.Owner.Name, View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}createdate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "createDate"), Description = ui.Text("content", "createDateDesc"), Value = display.CreateDate.ToIsoString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}updatedate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "updateDate"), Description = ui.Text("content", "updateDateDesc"), Value = display.UpdateDate.ToIsoString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "documentType"), Value = TranslateItem(display.ContentTypeName, CreateDictionary()), View = labelEditor } }; //add the custom ones contentProps.AddRange(customProperties); //now add the user props contentProps.AddRange(currProps); //re-assign genericProps.Properties = contentProps; } /// <summary> /// Adds the container (listview) tab to the document /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="display"></param> /// <param name="entityType">This must be either 'content' or 'media'</param> /// <param name="dataTypeService"></param> internal static void AddListView<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display, string entityType, IDataTypeService dataTypeService) where TPersisted : IContentBase { int dtdId; var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + display.ContentTypeAlias; switch (entityType) { case "content": dtdId = Constants.System.DefaultContentListViewDataTypeId; break; case "media": dtdId = Constants.System.DefaultMediaListViewDataTypeId; break; case "member": dtdId = Constants.System.DefaultMembersListViewDataTypeId; break; default: throw new ArgumentOutOfRangeException("entityType does not match a required value"); } //first try to get the custom one if there is one var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName) ?? dataTypeService.GetDataTypeDefinitionById(dtdId); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dt.Id); var editor = PropertyEditorResolver.Current.GetByAlias(dt.PropertyEditorAlias); if (editor == null) { throw new NullReferenceException("The property editor with alias " + dt.PropertyEditorAlias + " does not exist"); } var listViewTab = new Tab<ContentPropertyDisplay>(); listViewTab.Alias = Constants.Conventions.PropertyGroups.ListViewGroupName; listViewTab.Label = ui.Text("content", "childItems"); listViewTab.Id = 25; listViewTab.IsActive = true; var listViewConfig = editor.PreValueEditor.ConvertDbToEditor(editor.DefaultPreValues, preVals); //add the entity type to the config listViewConfig["entityType"] = entityType; var listViewProperties = new List<ContentPropertyDisplay>(); listViewProperties.Add(new ContentPropertyDisplay { Alias = string.Format("{0}containerView", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "", Value = null, View = editor.ValueEditor.View, HideLabel = true, Config = listViewConfig }); listViewTab.Properties = listViewProperties; //Is there a better way? var tabs = new List<Tab<ContentPropertyDisplay>>(); tabs.Add(listViewTab); tabs.AddRange(display.Tabs); display.Tabs = tabs; } protected override IEnumerable<Tab<ContentPropertyDisplay>> ResolveCore(IContentBase content) { var aggregateTabs = new List<Tab<ContentPropertyDisplay>>(); //now we need to aggregate the tabs and properties since we might have duplicate tabs (based on aliases) because // of how content composition works. foreach (var propertyGroups in content.PropertyGroups.OrderBy(x => x.SortOrder).GroupBy(x => x.Name)) { var aggregateProperties = new List<ContentPropertyDisplay>(); //add the properties from each composite property group foreach (var current in propertyGroups) { var propsForGroup = content.GetPropertiesForGroup(current) .Where(x => IgnoreProperties.Contains(x.Alias) == false); //don't include ignored props aggregateProperties.AddRange( Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>( propsForGroup)); } // Not sure whether it's a good idea to add this to the ContentPropertyDisplay mapper foreach (var prop in aggregateProperties) { prop.Label = TranslateItem(prop.Label); prop.Description = TranslateItem(prop.Description); } //then we'll just use the root group's data to make the composite tab var rootGroup = propertyGroups.First(x => x.ParentId == null); aggregateTabs.Add(new Tab<ContentPropertyDisplay> { Id = rootGroup.Id, Alias = rootGroup.Name, Label = TranslateItem(rootGroup.Name), Properties = aggregateProperties, IsActive = false }); } //now add the generic properties tab for any properties that don't belong to a tab var orphanProperties = content.GetNonGroupedProperties() .Where(x => IgnoreProperties.Contains(x.Alias) == false); //don't include ignored props //now add the generic properties tab aggregateTabs.Add(new Tab<ContentPropertyDisplay> { Id = 0, Label = ui.Text("general", "properties"), Alias = "Generic properties", Properties = Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>(orphanProperties) }); //set the first tab to active aggregateTabs.First().IsActive = true; return aggregateTabs; } // TODO: This should really be centralized and used anywhere globalization applies. internal string TranslateItem(string text) { var cultureDictionary = CultureDictionary; return TranslateItem(text, cultureDictionary); } private static string TranslateItem(string text, ICultureDictionary cultureDictionary) { if (text == null) { return null; } if (text.StartsWith("#") == false) return text; text = text.Substring(1); return cultureDictionary[text].IfNullOrWhiteSpace(text); } private ICultureDictionary CultureDictionary { get { return _cultureDictionary ?? (_cultureDictionary = CreateDictionary()); } } private static ICultureDictionary CreateDictionary() { return CultureDictionaryFactoryResolver.Current.Factory.CreateDictionary(); } } }
using System; using System.ComponentModel; using System.Drawing; using MurphyPA.H2D.Interfaces; using System.Drawing.Drawing2D; using System.Collections; namespace MurphyPA.H2D.Implementation { /// <summary> /// Summary description for StateGlyph. /// </summary> public class StateGlyph : GroupGlyphBase, IStateGlyph { Rectangle _Bounds = new Rectangle (10, 10, 150, 150); public StateGlyph () { BuildContactPoints (); } public StateGlyph (string id, Point point) : base (id) { _Bounds = new Rectangle (point.X, point.Y, _Bounds.Width, _Bounds.Height); BuildContactPoints (); } public StateGlyph (string id, Rectangle bounds) : base (id) { _Bounds = bounds; BuildContactPoints (); } public override void Accept (IGlyphVisitor visitor) { visitor.Visit (this); } protected void BuildContactPoints () { int radius = 3; AddContactPoint (new StateContactPointCircleGlyph (new Point (_Bounds.X, _Bounds.Y + _Bounds.Height / 2), radius, this, new OffsetChangedHandler (horizontal_ContactPoint))); AddContactPoint (new StateContactPointCircleGlyph (new Point (_Bounds.X + _Bounds.Width, _Bounds.Y + _Bounds.Height / 2), radius, this, new OffsetChangedHandler (horizontal_ContactPoint))); AddContactPoint (new StateContactPointCircleGlyph (new Point (_Bounds.X + _Bounds.Width / 2, _Bounds.Y), radius, this, new OffsetChangedHandler (vertical_ContactPoint))); AddContactPoint (new StateContactPointCircleGlyph (new Point (_Bounds.X + _Bounds.Width / 2, _Bounds.Y + _Bounds.Height), radius, this, new OffsetChangedHandler (vertical_ContactPoint))); } private void horizontal_ContactPoint (IGlyph glyph, OffsetEventArgs offsetEventArgs) { int expectedYPos = _Bounds.Y + _Bounds.Height / 2; int currentYPos = glyph.Bounds.Y + glyph.Bounds.Height / 2; offsetEventArgs.Offset = new Point (offsetEventArgs.Offset.X, expectedYPos - currentYPos); } private void vertical_ContactPoint (IGlyph glyph, OffsetEventArgs offsetEventArgs) { int expectedXPos = _Bounds.X + _Bounds.Width / 2; int currentXPos = glyph.Bounds.X + glyph.Bounds.Width / 2; offsetEventArgs.Offset = new Point (expectedXPos - currentXPos, offsetEventArgs.Offset.Y); } public int CountParentDepth () { int depth = 0; IGlyph p = _Parent; while (p != null) { depth++; p = p.Parent; } return depth; } public Color StateColor { get { int depth = CountParentDepth (); Color color = _Colors [depth]; return color; } } ColorDepth _Colors = new ColorDepth (); public override void Draw (IGraphicsContext gc) { using (gc.PushGraphicsState ()) { int depth = CountParentDepth (); Color color = _Colors [depth]; // CountParentDepth is expensive - so don't call StateColor here... Color contactColor = color; if (Name == null || Name.Trim () == "") { color = Color.Red; } gc.Color = color; DrawState (gc, _Bounds.Left, _Bounds.Top, _Bounds.Width, _Bounds.Height, 20, 2+depth, color, false); gc.Color = contactColor; gc.Thickness = 2 + depth; if (Selected) { foreach (IGlyph contact in ContactPoints) { contact.Draw (gc); } } } } protected void DrawString (IGraphicsContext g, string s, Brush brush, int thickness, Point point, FontStyle fontStyle) { IDrawStringContext context = new DrawStringContext (s, thickness, StateColor, fontStyle); g.DrawString (context, brush, point, false); } protected void DrawState (IGraphicsContext g, int x_left, int y_top, int width, int height, int radius, int thickness, Color color, bool drawTestRect) { if (drawTestRect) { GraphicsPath path = new GraphicsPath (); Rectangle rect = new Rectangle (x_left, y_top, width, height); path.AddRectangle (rect); path.CloseFigure (); using (Brush brush = new System.Drawing.SolidBrush (Color.Yellow)) { using (Pen pen = new Pen (brush, thickness)) { g.DrawPath (pen, path); } } } if (true) { GraphicsPath path = new GraphicsPath (); path.StartFigure (); path.AddArc (x_left, y_top, radius, radius, 180, 90); if (IsStartState) { path.AddLine (x_left + radius, y_top, x_left, y_top + radius); } path.AddLine (x_left + radius, y_top, x_left + width - radius - radius, y_top); path.AddArc (x_left + width - radius, y_top, radius, radius, 270, 90); path.AddLine (x_left + width, y_top + radius, x_left + width, y_top + height - radius - radius); path.AddArc (x_left + width - radius, y_top + height - radius, radius, radius, 0, 90); path.AddLine (x_left + width - radius, y_top + height, x_left + radius, y_top + height); path.AddArc (x_left, y_top + height - radius, radius, radius, 90, 90); path.AddLine (x_left, y_top + height - radius, x_left, y_top + radius); if (Selected) { path.AddLine (x_left + 5 + thickness, y_top + radius, x_left + 5 + thickness, y_top + height / 2); path.AddLine (x_left + 5 + thickness, y_top + height / 2, x_left + 5 + thickness, y_top + radius); } path.CloseFigure (); if (IsFinalState) { path.StartFigure (); path.AddLine (x_left +width - radius, y_top + height, x_left + width, y_top + height - radius); path.CloseFigure (); } using (Brush brush = new System.Drawing.SolidBrush (color)) { using (Pen pen = new Pen (brush, thickness)) { g.DrawPath (pen, path); if (IsNotEmptyString (Name)) { DrawString (g, Name, brush, (int) ((radius * 2.0) / 3.0), new Point (x_left + radius, y_top + 1), FontStyle.Bold); } int ypos = y_top + 1 + radius + radius / 2; if (IsNotEmptyString (EntryAction)) { DrawString (g, "e:" + EntryAction, brush, radius / 2, new Point (x_left + radius, ypos), FontStyle.Regular); ypos += (radius + radius) / 3; } if (IsNotEmptyString (ExitAction)) { DrawString (g, "x:" + ExitAction, brush, radius / 2, new Point (x_left + radius, ypos), FontStyle.Regular); ypos += (radius + radius) / 3; } if (IsNotEmptyString (DoAction)) { DrawString (g, "a:" + DoAction, brush, radius / 2, new Point (x_left + radius, ypos), FontStyle.Regular); } } } } } #region IGlyph Members public override void MoveTo (Point point) { _Bounds.Offset (point.X - _Bounds.X, point.Y - _Bounds.Y); } public override void Offset (Point point) { _Bounds.Offset (point); foreach (IGlyph child in _Children) { if (!_ContactPoints.Contains (child)) { ReOffsetChild (child, point); } } foreach (IGlyph contact in _ContactPoints) { ReOffsetContactPoint (contact, point); } } #endregion protected override bool AcceptParentInFullyQualifiedName (IGlyph glyph) { System.Diagnostics.Debug.Assert (glyph != null); IStateGlyph state = glyph as IStateGlyph; System.Diagnostics.Debug.Assert (state != null); return !state.IsOverriding; } void ReOffsetContactPoint (int index, Point offset) { IGlyph contact = _ContactPoints [index] as IGlyph; ReOffsetContactPoint (contact, offset); } void ReOffsetChild (IGlyph child, Point point) { child.Offset (point); } protected override void contactPoint_OffsetChanged(IGlyph glyph, OffsetEventArgs offsetEventArgs) { Point offset = offsetEventArgs.Offset; int index = _ContactPoints.IndexOf (glyph); switch (index) { case 0: { _Bounds.X += offset.X; _Bounds.Width -= offset.X; _Bounds.Height += offset.Y; ReOffsetContactPoint (2, offset); ReOffsetContactPoint (3, offset); } break; case 1: { _Bounds.Width += offset.X; _Bounds.Height += offset.Y; ReOffsetContactPoint (2, offset); ReOffsetContactPoint (3, offset); } break; case 2: { _Bounds.Y += offset.Y; _Bounds.Height -= offset.Y; _Bounds.Width += offset.X; ReOffsetContactPoint (0, offset); ReOffsetContactPoint (1, offset); } break; case 3: { _Bounds.Height += offset.Y; _Bounds.Width += offset.X; ReOffsetContactPoint (0, offset); ReOffsetContactPoint (1, offset); } break; } } protected override Rectangle GetBounds () { return _Bounds; } bool _IsStartState; [Category ("State")] public bool IsStartState { get { return _IsStartState; } set { _IsStartState = value; } } bool _IsFinalState; [Category ("State")] public bool IsFinalState { get { return _IsFinalState; } set { _IsFinalState = value; } } bool _IsOverriding; [Category ("State")] public bool IsOverriding { get { return _IsOverriding; } set { _IsOverriding = value; } } string _EntryAction = ""; [Category ("State")] public string EntryAction { get { return _EntryAction; } set { _EntryAction = value; } } string _ExitAction = ""; [Category ("State")] public string ExitAction { get { return _ExitAction; } set { _ExitAction = value; } } string _DoAction = ""; [Category ("State")] public string DoAction { get { return _DoAction; } set { _DoAction = value; } } System.Collections.Specialized.StringCollection _StateCommands = new System.Collections.Specialized.StringCollection (); [Category ("State")] public System.Collections.Specialized.StringCollection StateCommands { get { return _StateCommands; } } } }
/* * 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.Threading; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes { public partial class Scene { /// <summary> /// Send chat to listeners. /// </summary> /// <param name='message'></param> /// <param name='type'>/param> /// <param name='channel'></param> /// <param name='fromPos'></param> /// <param name='fromName'></param> /// <param name='fromID'></param> /// <param name='targetID'></param> /// <param name='fromAgent'></param> /// <param name='broadcast'></param> protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, UUID targetID, bool fromAgent, bool broadcast) { OSChatMessage args = new OSChatMessage(); args.Message = Utils.BytesToString(message); args.Channel = channel; args.Type = type; args.Position = fromPos; args.SenderUUID = fromID; args.Scene = this; if (fromAgent) { ScenePresence user = GetScenePresence(fromID); if (user != null) args.Sender = user.ControllingClient; } else { SceneObjectPart obj = GetSceneObjectPart(fromID); args.SenderObject = obj; } args.From = fromName; args.TargetUUID = targetID; // m_log.DebugFormat( // "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}", // args.Message.Replace("\n", "\\n"), args.Channel, args.Type, fromName, broadcast); if (broadcast) EventManager.TriggerOnChatBroadcast(this, args); else EventManager.TriggerOnChatFromWorld(this, args); } protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent, bool broadcast) { SimChat(message, type, channel, fromPos, fromName, fromID, UUID.Zero, fromAgent, broadcast); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false); } public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent); } public void SimChat(string message, string fromName) { SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> /// <param name="targetID"></param> public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false); } /// <summary> /// Invoked when the client requests a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void RequestPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectGroup sog = GetGroupByPrim(primLocalID); if (sog != null) sog.SendFullUpdateToClient(remoteClient); } /// <summary> /// Invoked when the client selects a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void SelectPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(primLocalID); if (null == part) return; if (part.IsRoot) { SceneObjectGroup sog = part.ParentGroup; sog.SendPropertiesToClient(remoteClient); sog.IsSelected = true; // A prim is only tainted if it's allowed to be edited by the person clicking it. if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId) || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId)) { EventManager.TriggerParcelPrimCountTainted(); } } else { part.SendPropertiesToClient(remoteClient); } } /// <summary> /// Handle the update of an object's user group. /// </summary> /// <param name="remoteClient"></param> /// <param name="groupID"></param> /// <param name="objectLocalID"></param> /// <param name="Garbage"></param> private void HandleObjectGroupUpdate( IClientAPI remoteClient, UUID groupID, uint objectLocalID, UUID Garbage) { if (m_groupsModule == null) return; // XXX: Might be better to get rid of this special casing and have GetMembershipData return something // reasonable for a UUID.Zero group. if (groupID != UUID.Zero) { GroupMembershipData gmd = m_groupsModule.GetMembershipData(groupID, remoteClient.AgentId); if (gmd == null) { // m_log.WarnFormat( // "[GROUPS]: User {0} is not a member of group {1} so they can't update {2} to this group", // remoteClient.Name, GroupID, objectLocalID); return; } } SceneObjectGroup so = ((Scene)remoteClient.Scene).GetGroupByPrim(objectLocalID); if (so != null) { if (so.OwnerID == remoteClient.AgentId) { so.SetGroup(groupID, remoteClient); } } } /// <summary> /// Handle the deselection of a prim from the client. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void DeselectPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(primLocalID); if (part == null) return; // A deselect packet contains all the local prims being deselected. However, since selection is still // group based we only want the root prim to trigger a full update - otherwise on objects with many prims // we end up sending many duplicate ObjectUpdates if (part.ParentGroup.RootPart.LocalId != part.LocalId) return; bool isAttachment = false; // This is wrong, wrong, wrong. Selection should not be // handled by group, but by prim. Legacy cruft. // TODO: Make selection flagging per prim! // part.ParentGroup.IsSelected = false; if (part.ParentGroup.IsAttachment) isAttachment = true; else part.ParentGroup.ScheduleGroupForFullUpdate(); // If it's not an attachment, and we are allowed to move it, // then we might have done so. If we moved across a parcel // boundary, we will need to recount prims on the parcels. // For attachments, that makes no sense. // if (!isAttachment) { if (Permissions.CanEditObject( part.UUID, remoteClient.AgentId) || Permissions.CanMoveObject( part.UUID, remoteClient.AgentId)) EventManager.TriggerParcelPrimCountTainted(); } } public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, int transactiontype, string description) { EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount, transactiontype, description); EventManager.TriggerMoneyTransfer(this, args); } public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned, bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) { EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned, removeContribution, parcelLocalID, parcelArea, parcelPrice, authenticated); // First, allow all validators a stab at it m_eventManager.TriggerValidateLandBuy(this, args); // Then, check validation and transfer m_eventManager.TriggerLandBuy(this, args); } public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(localID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // Currently only grab/touch for the single prim // the client handles rez correctly obj.ObjectGrabHandler(localID, offsetPos, remoteClient); // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_start) != 0) EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg); // Deliver to the root prim if the touched prim doesn't handle touches // or if we're meant to pass on touches anyway. Don't send to root prim // if prim touched is the root prim as we just did it if (((part.ScriptEvents & scriptEvents.touch_start) == 0) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId))) { EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg); } } public virtual void ProcessObjectGrabUpdate( UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(objectID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch) != 0) EventManager.TriggerObjectGrabbing(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg); // Deliver to the root prim if the touched prim doesn't handle touches // or if we're meant to pass on touches anyway. Don't send to root prim // if prim touched is the root prim as we just did it if (((part.ScriptEvents & scriptEvents.touch) == 0) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId))) { EventManager.TriggerObjectGrabbing(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg); } } public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { SceneObjectPart part = GetSceneObjectPart(localID); if (part == null) return; SceneObjectGroup obj = part.ParentGroup; SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_end) != 0) EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg); else EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg); } public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID, UUID itemID) { SceneObjectPart part=GetSceneObjectPart(objectID); if (part == null) return; if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId)) { EventManager.TriggerScriptReset(part.LocalId, itemID); } } void ProcessViewerEffect(IClientAPI remoteClient, List<ViewerEffectEventHandlerArg> args) { // TODO: don't create new blocks if recycling an old packet ViewerEffectPacket.EffectBlock[] effectBlockArray = new ViewerEffectPacket.EffectBlock[args.Count]; for (int i = 0; i < args.Count; i++) { ViewerEffectPacket.EffectBlock effect = new ViewerEffectPacket.EffectBlock(); effect.AgentID = args[i].AgentID; effect.Color = args[i].Color; effect.Duration = args[i].Duration; effect.ID = args[i].ID; effect.Type = args[i].Type; effect.TypeData = args[i].TypeData; effectBlockArray[i] = effect; } ForEachClient( delegate(IClientAPI client) { if (client.AgentId != remoteClient.AgentId) client.SendViewerEffect(effectBlockArray); } ); } /// <summary> /// Tell the client about the various child items and folders contained in the requested folder. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { // m_log.DebugFormat( // "[USER INVENTORY]: HandleFetchInventoryDescendents() for {0}, folder={1}, fetchFolders={2}, fetchItems={3}, sortOrder={4}", // remoteClient.Name, folderID, fetchFolders, fetchItems, sortOrder); if (folderID == UUID.Zero) return; // FIXME MAYBE: We're not handling sortOrder! // TODO: This code for looking in the folder for the library should be folded somewhere else // so that this class doesn't have to know the details (and so that multiple libraries, etc. // can be handled transparently). InventoryFolderImpl fold = null; if (LibraryService != null && LibraryService.LibraryRootFolder != null) { if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null) { remoteClient.SendInventoryFolderDetails( fold.Owner, folderID, fold.RequestListOfItems(), fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems); return; } } // We're going to send the reply async, because there may be // an enormous quantity of packets -- basically the entire inventory! // We don't want to block the client thread while all that is happening. SendInventoryDelegate d = SendInventoryAsync; d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); } delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); } void SendInventoryComplete(IAsyncResult iar) { SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState; d.EndInvoke(iar); } /// <summary> /// Handle an inventory folder creation request from the client. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="folderType"></param> /// <param name="folderName"></param> /// <param name="parentID"></param> public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType, string folderName, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1); if (!InventoryService.AddFolder(folder)) { m_log.WarnFormat( "[AGENT INVENTORY]: Failed to create folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } /// <summary> /// Handle a client request to update the inventory folder /// </summary> /// /// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE /// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing, /// and needs to be changed. /// /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="type"></param> /// <param name="name"></param> /// <param name="parentID"></param> public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name, UUID parentID) { // m_log.DebugFormat( // "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId); InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.Name = name; folder.Type = (short)type; folder.ParentID = parentID; if (!InventoryService.UpdateFolder(folder)) { m_log.ErrorFormat( "[AGENT INVENTORY]: Failed to update folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } } public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.ParentID = parentID; if (!InventoryService.MoveFolder(folder)) m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID); else m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID); } else { m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID); } } delegate void PurgeFolderDelegate(UUID userID, UUID folder); /// <summary> /// This should delete all the items and folders in the given directory. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID) { PurgeFolderDelegate d = PurgeFolderAsync; try { d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d); } catch (Exception e) { m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message); } } private void PurgeFolderAsync(UUID userID, UUID folderID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, userID); if (InventoryService.PurgeFolder(folder)) m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID); else m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID); } private void PurgeFolderCompleted(IAsyncResult iar) { PurgeFolderDelegate d = (PurgeFolderDelegate)iar.AsyncState; d.EndInvoke(iar); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Xsl; using XmlCoreTest.Common; using OLEDB.Test.ModuleCore; using System.Runtime.Loader; namespace System.Xml.Tests { public class XsltcTestCaseBase : CTestCase { // Generic data for all derived test cases public String szDefaultNS = "urn:my-object"; public String szEmpty = ""; public String szInvalid = "*?%(){}[]&!@#$"; public String szLongNS = "http://www.microsoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/"; public String szLongString = "ThisIsAVeryLongStringToBeStoredAsAVariableToDetermineHowLargeThisBufferForAVariableNameCanBeAndStillFunctionAsExpected"; public String szSimple = "myArg"; public String[] szWhiteSpace = { " ", "\n", "\t", "\r", "\t\n \r\t" }; public String szXslNS = "http://www.w3.org/1999/XSL/Transform"; // Other global variables protected bool _createFromInputFile = false; // This is intiialized from a parameter passed from LTM as a dimension, that dictates whether the variation is to be created using an input file. protected bool _isInProc; // Is the current test run in proc or /Host None? private static ITestOutputHelper s_output; public XsltcTestCaseBase(ITestOutputHelper output) { s_output = output; } public override int Init(object objParam) { // initialize whether this run is in proc or not string executionMode = "File"; _createFromInputFile = executionMode.Equals("File"); return 1; } protected static void CompareOutput(string expected, Stream actualStream) { using (var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes(expected))) { CompareOutput(expectedStream, actualStream); } } protected static void CompareOutput(Stream expectedStream, Stream actualStream, int count = 0) { actualStream.Seek(0, SeekOrigin.Begin); using (var expectedReader = new StreamReader(expectedStream)) using (var actualReader = new StreamReader(actualStream)) { for (int i = 0; i < count; i++) { actualReader.ReadLine(); expectedReader.ReadLine(); } string actual = actualReader.ReadToEnd(); string expected = expectedReader.ReadToEnd(); if (actual.Equals(expected)) { return; } throw new CTestFailedException("Output was not as expected.", actual, expected, null); } } protected bool LoadPersistedTransformAssembly(string asmName, string typeName, string baselineFile, bool pdb) { var other = (AssemblyLoader)Activator.CreateInstance(typeof(AssemblyLoader), typeof(AssemblyLoader).FullName); bool result = other.Verify(asmName, typeName, baselineFile, pdb); return result; } protected string ReplaceCurrentWorkingDirectory(string commandLine) { return commandLine.Replace(@"$(CurrentWorkingDirectory)", XsltcModule.TargetDirectory); } protected bool ShouldSkip(object[] varParams) { // some test only applicable in English environment, so skip them if current cultral is not english bool isCultralEnglish = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToLower() == "en"; if (isCultralEnglish) { return false; } // look up key word "EnglishOnly", if hit return true, otherwise false return varParams != null && varParams.Any(o => o.ToString() == "EnglishOnly"); } protected void VerifyTest(String cmdLine, String baselineFile, bool loadFromFile) { VerifyTest(cmdLine, String.Empty, false, String.Empty, baselineFile, loadFromFile); } protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, String.Empty, false, baselineFile, loadFromFile); } protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String pdbName, bool pdbCreated, String baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, pdbName, pdbCreated, baselineFile, true, loadFromFile); } protected void VerifyTest(String cmdLine, String asmName, bool asmCreated, String typeName, String pdbName, bool pdbCreated, String baselineFile, bool runAssemblyVerification, bool loadFromFile) { string targetDirectory = XsltcModule.TargetDirectory; string output = asmCreated ? TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, true, targetDirectory) : TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, false, targetDirectory); //verify assembly file existence if (asmName != null && String.CompareOrdinal(String.Empty, asmName) != 0) { if (File.Exists(GetPath(asmName)) != asmCreated) { throw new CTestFailedException("Assembly File Creation Check: FAILED"); } } //verify pdb existence if (pdbName != null && String.CompareOrdinal(String.Empty, pdbName) != 0) { if (File.Exists(GetPath(pdbName)) != pdbCreated) { throw new CTestFailedException("PDB File Creation Check: FAILED"); } } if (asmCreated && !String.IsNullOrEmpty(typeName)) { if (!LoadPersistedTransformAssembly(GetPath(asmName), typeName, baselineFile, pdbCreated)) { throw new CTestFailedException("Assembly loaded failed"); } } else { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms) { AutoFlush = true }) using (var expected = new FileStream(GetPath(baselineFile), FileMode.Open, FileAccess.Read)) { sw.Write(output); CompareOutput(expected, ms, 4); } } SafeDeleteFile(GetPath(pdbName)); SafeDeleteFile(GetPath(asmName)); return; } private static void SafeDeleteFile(string fileName) { try { var fileInfo = new FileInfo(fileName); if (fileInfo.Directory != null && !fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } if (fileInfo.Exists) { fileInfo.Delete(); } } catch (ArgumentException) { } catch (PathTooLongException) { } catch (Exception e) { s_output.WriteLine(e.Message); } } // Used to generate a unique name for an input file, and write that file, based on a specified command line. private string CreateInputFile(string commandLine) { string fileName = Path.Combine(XsltcModule.TargetDirectory, Guid.NewGuid() + ".ipf"); File.WriteAllText(fileName, commandLine); return fileName; } private string GetPath(string fileName) { return XsltcModule.TargetDirectory + Path.DirectorySeparatorChar + fileName; } /// <summary> /// Currently this method supports only 1 input file. For variations that require more than one input file to test /// @file /// functionality, custom-craft and write those input files in the body of the variation method, then pass an /// appropriate /// commandline such as @file1 @file2 @file3, along with createFromInputFile = false. /// </summary> /// <param name="commandLine"></param> /// <param name="createFromInputFile"></param> /// <param name="expectedToSucceed"></param> /// <param name="targetDirectory"></param> /// <returns></returns> private string TryCreatePersistedTransformAssembly(string commandLine, bool createFromInputFile, bool expectedToSucceed, string targetDirectory) { // If createFromInputFile is specified, create an input file now that the compiler can consume. string processArguments = createFromInputFile ? "@" + CreateInputFile(commandLine) : commandLine; var processStartInfo = new ProcessStartInfo { FileName = XsltVerificationLibrary.SearchPath("xsltc.exe"), Arguments = processArguments, //WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, WorkingDirectory = targetDirectory }; // Call xsltc to create persistant assembly. var compilerProcess = new Process { StartInfo = processStartInfo }; compilerProcess.Start(); string output = compilerProcess.StandardOutput.ReadToEnd(); compilerProcess.WaitForExit(); if (createFromInputFile) { SafeDeleteFile(processArguments.Substring(1)); } if (expectedToSucceed) { // The Assembly was created successfully if (compilerProcess.ExitCode == 0) { return output; } throw new CTestFailedException("Failed to create assembly: " + output); } return output; } public class AssemblyLoader //: MarshalByRefObject { public AssemblyLoader(string asmName) { } public bool Verify(string asmName, string typeName, string baselineFile, bool pdb) { try { var xslt = new XslCompiledTransform(); Assembly xsltasm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(asmName)); if (xsltasm == null) { //_output.WriteLine("Could not load file"); return false; } Type t = xsltasm.GetType(typeName); if (t == null) { //_output.WriteLine("No type loaded"); return false; } xslt.Load(t); var inputXml = new XmlDocument(); using (var stream = new MemoryStream()) using (var sw = new StreamWriter(stream) { AutoFlush = true }) { inputXml.LoadXml("<foo><bar>Hello, world!</bar></foo>"); xslt.Transform(inputXml, null, sw); if (!XsltVerificationLibrary.CompareXml(Path.Combine(XsltcModule.TargetDirectory, baselineFile), stream)) { //_output.WriteLine("Baseline file comparison failed"); return false; } } return true; } catch (Exception e) { s_output.WriteLine(e.Message); return false; } // Turning this off as this causes noise on different platforms like IA64. // Also since we verify the assembly by loading there is not really a need for this verification. // if (succeeded && runAssemblyVerification) { // String peOutput = String.Empty; // succeeded = XsltVerificationLibrary.VerifyAssemblyUsingPEVerify( // asmName, // logger, // ref peOutput); // logger.LogMessage("Assembly Verification Result: " + peOutput); //} } private static byte[] loadFile(string filename) { using (var fs = new FileStream(filename, FileMode.Open)) { var buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); return buffer; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; [assembly: PythonModule("imp", typeof(IronPython.Modules.PythonImport))] namespace IronPython.Modules { public static class PythonImport { public const string __doc__ = "Provides functions for programmatically creating and importing modules and packages."; internal const int PythonSource = 1; internal const int PythonCompiled = 2; internal const int CExtension = 3; internal const int PythonResource = 4; internal const int PackageDirectory = 5; internal const int CBuiltin = 6; internal const int PythonFrozen = 7; internal const int PythonCodeResource = 8; internal const int SearchError = 0; internal const int ImporterHook = 9; private static readonly object _lockCountKey = new object(); [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { // set the lock count to zero on the 1st load, don't reset the lock count on reloads if (!context.HasModuleState(_lockCountKey)) { context.SetModuleState(_lockCountKey, 0L); } } public static string get_magic() { return ""; } public static List get_suffixes() { return List.FromArrayNoCopy(PythonOps.MakeTuple(".py", "U", PythonSource)); } public static PythonTuple find_module(CodeContext/*!*/ context, string/*!*/ name) { if (name == null) throw PythonOps.TypeError("find_module() argument 1 must be string, not None"); return FindBuiltinOrSysPath(context, name); } public static PythonTuple find_module(CodeContext/*!*/ context, string/*!*/ name, List path) { if (name == null) throw PythonOps.TypeError("find_module() argument 1 must be string, not None"); if (path == null) { return FindBuiltinOrSysPath(context, name); } else { return FindModulePath(context, name, path); } } public static object load_module(CodeContext/*!*/ context, string name, PythonFile file, string filename, PythonTuple/*!*/ description) { if (description == null) { throw PythonOps.TypeError("load_module() argument 4 must be 3-item sequence, not None"); } else if (description.__len__() != 3) { throw PythonOps.TypeError("load_module() argument 4 must be sequence of length 3, not {0}", description.__len__()); } PythonContext pythonContext = context.LanguageContext; // already loaded? do reload() PythonModule module = pythonContext.GetModuleByName(name); if (module != null) { Importer.ReloadModule(context, module, file); return module; } int type = context.LanguageContext.ConvertToInt32(description[2]); switch (type) { case PythonSource: return LoadPythonSource(pythonContext, name, file, filename); case CBuiltin: return LoadBuiltinModule(context, name); case PackageDirectory: return LoadPackageDirectory(pythonContext, name, filename); default: throw PythonOps.TypeError("don't know how to import {0}, (type code {1}", name, type); } } [Documentation("new_module(name) -> module\nCreates a new module without adding it to sys.modules.")] public static PythonModule/*!*/ new_module(CodeContext/*!*/ context, string/*!*/ name) { if (name == null) throw PythonOps.TypeError("new_module() argument 1 must be string, not None"); PythonModule res = new PythonModule(); res.__dict__["__name__"] = name; res.__dict__["__doc__"] = null; res.__dict__["__package__"] = null; return res; } public static bool lock_held(CodeContext/*!*/ context) { return GetLockCount(context) != 0; } public static void acquire_lock(CodeContext/*!*/ context) { lock (_lockCountKey) { SetLockCount(context, GetLockCount(context) + 1); } } public static void release_lock(CodeContext/*!*/ context) { lock (_lockCountKey) { long lockCount = GetLockCount(context); if (lockCount == 0) { throw PythonOps.RuntimeError("not holding the import lock"); } SetLockCount(context, lockCount - 1); } } public const int PY_SOURCE = PythonSource; public const int PY_COMPILED = PythonCompiled; public const int C_EXTENSION = CExtension; public const int PY_RESOURCE = PythonResource; public const int PKG_DIRECTORY = PackageDirectory; public const int C_BUILTIN = CBuiltin; public const int PY_FROZEN = PythonFrozen; public const int PY_CODERESOURCE = PythonCodeResource; public const int SEARCH_ERROR = SearchError; public const int IMP_HOOK = ImporterHook; public static object init_builtin(CodeContext/*!*/ context, string/*!*/ name) { if (name == null) throw PythonOps.TypeError("init_builtin() argument 1 must be string, not None"); return LoadBuiltinModule(context, name); } public static object init_frozen(string name) { return null; } public static object get_frozen_object(string name) { throw PythonOps.ImportError("No such frozen object named {0}", name); } public static int is_builtin(CodeContext/*!*/ context, string/*!*/ name) { if (name == null) throw PythonOps.TypeError("is_builtin() argument 1 must be string, not None"); Type ty; if (context.LanguageContext.BuiltinModules.TryGetValue(name, out ty)) { if (ty.Assembly == typeof(PythonContext).Assembly) { // supposedly these can't be re-initialized and return -1 to // indicate that here, but CPython does allow passing them // to init_builtin. return -1; } return 1; } return 0; } public static bool is_frozen(string name) { return false; } public static object load_compiled(string name, string pathname) { return null; } public static object load_compiled(string name, string pathname, PythonFile file) { return null; } public static object load_dynamic(string name, string pathname) { return null; } public static object load_dynamic(string name, string pathname, PythonFile file) { return null; } public static object load_package(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ pathname) { if (name == null) throw PythonOps.TypeError("load_package() argument 1 must be string, not None"); if (pathname == null) throw PythonOps.TypeError("load_package() argument 2 must be string, not None"); return (Importer.LoadPackageFromSource(context, name, pathname) ?? CreateEmptyPackage(context, name, pathname)); } private static PythonModule/*!*/ CreateEmptyPackage(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ pathname) { PythonContext pc = context.LanguageContext; PythonModule mod = new PythonModule(); mod.__dict__["__name__"] = name; mod.__dict__["__path__"] = pathname; pc.SystemStateModules[name] = mod; return mod; } public static object load_source(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ pathname) { if (name == null) throw PythonOps.TypeError("load_source() argument 1 must be string, not None"); if (pathname == null) throw PythonOps.TypeError("load_source() argument 2 must be string, not None"); // TODO: is this supposed to open PythonFile with Python-specific behavior? // we may need to insert additional layer to SourceUnit content provider if so PythonContext pc = context.LanguageContext; if (!pc.DomainManager.Platform.FileExists(pathname)) { throw PythonOps.IOError("Couldn't find file: {0}", pathname); } SourceUnit sourceUnit = pc.CreateFileUnit(pathname, pc.DefaultEncoding, SourceCodeKind.File); return pc.CompileModule(pathname, name, sourceUnit, ModuleOptions.Initialize); } public static object load_source(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ pathname, PythonFile/*!*/ file) { if (name == null) throw PythonOps.TypeError("load_source() argument 1 must be string, not None"); if (pathname == null) throw PythonOps.TypeError("load_source() argument 2 must be string, not None"); if (file == null) throw PythonOps.TypeError("load_source() argument 3 must be file, not None"); return LoadPythonSource(context.LanguageContext, name, file, pathname); } public static object reload(CodeContext/*!*/ context, PythonModule scope) { return Builtin.reload(context, scope); } #region Implementation private static PythonTuple FindBuiltinOrSysPath(CodeContext/*!*/ context, string/*!*/ name) { List sysPath; if (!context.LanguageContext.TryGetSystemPath(out sysPath)) { throw PythonOps.ImportError("sys.path must be a list of directory names"); } return FindModuleBuiltinOrPath(context, name, sysPath); } private static PythonTuple FindModulePath(CodeContext/*!*/ context, string name, List path) { Debug.Assert(path != null); if (name == null) { throw PythonOps.TypeError("find_module() argument 1 must be string, not None"); } PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; foreach (object d in path) { if (!(d is string dir)) continue; // skip invalid entries string pathName = Path.Combine(dir, name); if (pal.DirectoryExists(pathName)) { if (pal.FileExists(Path.Combine(pathName, "__init__.py"))) { return PythonTuple.MakeTuple(null, pathName, PythonTuple.MakeTuple("", "", PackageDirectory)); } } string fileName = pathName + ".py"; if (pal.FileExists(fileName)) { Stream fs = pal.OpenInputFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PythonFile pf = PythonFile.Create(context, fs, fileName, "U"); return PythonTuple.MakeTuple(pf, fileName, PythonTuple.MakeTuple(".py", "U", PythonSource)); } } throw PythonOps.ImportError("No module named {0}", name); } private static PythonTuple FindModuleBuiltinOrPath(CodeContext/*!*/ context, string name, List path) { if (name.Equals("sys")) return BuiltinModuleTuple(name); if (name.Equals("clr")) { context.ShowCls = true; return BuiltinModuleTuple(name); } Type ty; if (context.LanguageContext.BuiltinModules.TryGetValue(name, out ty)) { return BuiltinModuleTuple(name); } return FindModulePath(context, name, path); } private static PythonTuple BuiltinModuleTuple(string name) { return PythonTuple.MakeTuple(null, name, PythonTuple.MakeTuple("", "", CBuiltin)); } private static PythonModule/*!*/ LoadPythonSource(PythonContext/*!*/ context, string/*!*/ name, PythonFile/*!*/ file, string/*!*/ fileName) { SourceUnit sourceUnit = context.CreateSnippet(file.read(), String.IsNullOrEmpty(fileName) ? null : fileName, SourceCodeKind.File); return context.CompileModule(fileName, name, sourceUnit, ModuleOptions.Initialize); } private static PythonModule/*!*/ LoadPackageDirectory(PythonContext/*!*/ context, string moduleName, string path) { string initPath = Path.Combine(path, "__init__.py"); SourceUnit sourceUnit = context.CreateFileUnit(initPath, context.DefaultEncoding); return context.CompileModule(initPath, moduleName, sourceUnit, ModuleOptions.Initialize); } private static object LoadBuiltinModule(CodeContext/*!*/ context, string/*!*/ name) { Assert.NotNull(context, name); return Importer.ImportBuiltin(context, name); } #endregion private static long GetLockCount(CodeContext/*!*/ context) { return (long)context.LanguageContext.GetModuleState(_lockCountKey); } private static void SetLockCount(CodeContext/*!*/ context, long lockCount) { context.LanguageContext.SetModuleState(_lockCountKey, lockCount); } [PythonType] public sealed class NullImporter { public NullImporter(string path_string) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public object find_module(params object[] args) { return null; } } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEditor; using UnityEngine; using System.Collections.Generic; namespace AmplifyShaderEditor { class NodeDescriptionInfo { public bool FoldoutValue; public string Category; public string[,] Contents; } public sealed class PortLegendInfo : EditorWindow { private const string NoASEWindowWarning = "Please Open the ASE to get access to shortcut info"; private const float PixelSeparator = 5; private const string EditorShortcutsTitle = "Editor Shortcuts"; private const string MenuShortcutsTitle = "Menu Shortcuts"; private const string NodesShortcutsTitle = "Nodes Shortcuts"; private const string PortShortcutsTitle = "Port Shortcuts"; private const string PortLegendTitle = "Port Legend"; private const string NodesDescTitle = "Node Info"; private const string CompatibleAssetsTitle = "Compatible Assets"; private const string KeyboardUsageTemplate = "[{0}] - {1}"; private const string m_lockedStr = "Locked Port"; private const float WindowSizeX = 350; private const float WindowSizeY = 300; private const float WindowPosX = 5; private const float WindowPosY = 5; private const int TitleLabelWidth = 150; private Rect m_availableArea; private bool m_portAreaFoldout = true; private bool m_editorShortcutAreaFoldout = true; private bool m_menuShortcutAreaFoldout = true; private bool m_nodesShortcutAreaFoldout = true; private bool m_nodesDescriptionAreaFoldout = true; private bool m_compatibleAssetsFoldout = true; private Vector2 m_currentScrollPos; private GUIStyle m_portStyle; private GUIStyle m_labelStyleBold; private GUIStyle m_labelStyle; private GUIStyle m_nodeInfoLabelStyleBold; private GUIStyle m_nodeInfoLabelStyle; private GUIStyle m_nodeInfoFoldoutStyle; private GUIContent m_content = new GUIContent( "Helper", "Shows helper info for ASE users" ); private bool m_init = true; private List<ShortcutItem> m_editorShortcuts = null; private List<ShortcutItem> m_nodesShortcuts = null; private List<NodeDescriptionInfo> m_nodeDescriptionsInfo = null; private List<string[]> m_compatibleAssetsInfo = null; public static PortLegendInfo OpenWindow() { PortLegendInfo currentWindow = ( PortLegendInfo ) PortLegendInfo.GetWindow( typeof( PortLegendInfo ), false ); currentWindow.minSize = new Vector2( WindowSizeX, WindowSizeY ); currentWindow.maxSize = new Vector2( WindowSizeX, 2 * WindowSizeY ); ; currentWindow.wantsMouseMove = true; return currentWindow; } public void Init() { m_init = false; wantsMouseMove = false; titleContent = m_content; m_portStyle = new GUIStyle( UIUtils.GetCustomStyle( CustomStyle.PortEmptyIcon ) ); m_portStyle.alignment = TextAnchor.MiddleLeft; m_portStyle.imagePosition = ImagePosition.ImageOnly; m_portStyle.margin = new RectOffset( 5, 0, 5, 0 ); m_labelStyleBold = new GUIStyle( UIUtils.GetCustomStyle( CustomStyle.InputPortlabel ) ); m_labelStyleBold.fontStyle = FontStyle.Bold; m_labelStyleBold.fontSize = ( int ) ( Constants.TextFieldFontSize ); m_labelStyle = new GUIStyle( UIUtils.GetCustomStyle( CustomStyle.InputPortlabel ) ); m_labelStyle.clipping = TextClipping.Overflow; m_labelStyle.imagePosition = ImagePosition.TextOnly; m_labelStyle.contentOffset = new Vector2( -10, 0 ); m_labelStyle.fontSize = ( int ) ( Constants.TextFieldFontSize ); m_nodeInfoLabelStyleBold = new GUIStyle( UIUtils.GetCustomStyle( CustomStyle.InputPortlabel ) ); m_nodeInfoLabelStyleBold.fontStyle = FontStyle.Bold; m_nodeInfoLabelStyleBold.fontSize = ( int ) ( Constants.TextFieldFontSize ); m_nodeInfoLabelStyle = new GUIStyle( UIUtils.GetCustomStyle( CustomStyle.InputPortlabel ) ); m_nodeInfoLabelStyle.clipping = TextClipping.Clip; m_nodeInfoLabelStyle.imagePosition = ImagePosition.TextOnly; m_nodeInfoLabelStyle.fontSize = ( int ) ( Constants.TextFieldFontSize ); m_nodeInfoFoldoutStyle = new GUIStyle( ( GUIStyle ) "foldout" ); m_nodeInfoFoldoutStyle.fontStyle = FontStyle.Bold; if ( !EditorGUIUtility.isProSkin ) { m_labelStyleBold.normal.textColor = m_labelStyle.normal.textColor = Color.black; } m_availableArea = new Rect( WindowPosX, WindowPosY, WindowSizeX - 2 * WindowPosX, WindowSizeY - 2 * WindowPosY ); } void DrawPort( WirePortDataType type ) { EditorGUILayout.BeginHorizontal(); { GUI.color = UIUtils.GetColorForDataType( type, false ); GUILayout.Box( string.Empty, m_portStyle, GUILayout.Width( UIUtils.PortsSize.x ), GUILayout.Height( UIUtils.PortsSize.y ) ); GUI.color = Color.white; EditorGUILayout.LabelField( UIUtils.GetNameForDataType( type ), m_labelStyle ); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); } void OnGUI() { if ( !UIUtils.Initialized || UIUtils.CurrentWindow == null ) { EditorGUILayout.LabelField( NoASEWindowWarning ); return; } if ( m_init ) { Init(); } KeyCode key = Event.current.keyCode; if ( key == ShortcutsManager.ScrollUpKey ) { m_currentScrollPos.y -= 10; if ( m_currentScrollPos.y < 0 ) { m_currentScrollPos.y = 0; } Event.current.Use(); } if ( key == ShortcutsManager.ScrollDownKey ) { m_currentScrollPos.y += 10; Event.current.Use(); } if ( Event.current.type == EventType.MouseDrag && Event.current.button > 0 ) { m_currentScrollPos.x += Constants.MenuDragSpeed * Event.current.delta.x; if ( m_currentScrollPos.x < 0 ) { m_currentScrollPos.x = 0; } m_currentScrollPos.y += Constants.MenuDragSpeed * Event.current.delta.y; if ( m_currentScrollPos.y < 0 ) { m_currentScrollPos.y = 0; } } m_availableArea = new Rect( WindowPosX, WindowPosY, position.width - 2 * WindowPosX, position.height - 2 * WindowPosY ); GUILayout.BeginArea( m_availableArea ); { if ( GUILayout.Button( "Wiki Page" ) ) { Application.OpenURL( Constants.HelpURL ); } m_currentScrollPos = GUILayout.BeginScrollView( m_currentScrollPos ); { EditorGUILayout.BeginVertical(); { NodeUtils.DrawPropertyGroup( ref m_portAreaFoldout, PortLegendTitle, DrawPortInfo ); float currLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 1; NodeUtils.DrawPropertyGroup( ref m_editorShortcutAreaFoldout, EditorShortcutsTitle, DrawEditorShortcuts ); NodeUtils.DrawPropertyGroup( ref m_menuShortcutAreaFoldout, MenuShortcutsTitle, DrawMenuShortcuts ); NodeUtils.DrawPropertyGroup( ref m_nodesShortcutAreaFoldout, NodesShortcutsTitle, DrawNodesShortcuts ); NodeUtils.DrawPropertyGroup( ref m_compatibleAssetsFoldout, CompatibleAssetsTitle, DrawCompatibleAssets ); NodeUtils.DrawPropertyGroup( ref m_nodesDescriptionAreaFoldout, NodesDescTitle, DrawNodeDescriptions ); EditorGUIUtility.labelWidth = currLabelWidth; } EditorGUILayout.EndVertical(); } GUILayout.EndScrollView(); } GUILayout.EndArea(); } void DrawPortInfo() { Color originalColor = GUI.color; DrawPort( WirePortDataType.OBJECT ); DrawPort( WirePortDataType.INT ); DrawPort( WirePortDataType.FLOAT ); DrawPort( WirePortDataType.FLOAT2 ); DrawPort( WirePortDataType.FLOAT3 ); DrawPort( WirePortDataType.FLOAT4 ); DrawPort( WirePortDataType.COLOR ); DrawPort( WirePortDataType.SAMPLER2D ); DrawPort( WirePortDataType.FLOAT3x3 ); DrawPort( WirePortDataType.FLOAT4x4 ); EditorGUILayout.BeginHorizontal(); { GUI.color = Constants.LockedPortColor; GUILayout.Box( string.Empty, m_portStyle, GUILayout.Width( UIUtils.PortsSize.x ), GUILayout.Height( UIUtils.PortsSize.y ) ); GUI.color = Color.white; EditorGUILayout.LabelField( m_lockedStr, m_labelStyle ); } EditorGUILayout.EndHorizontal(); GUI.color = originalColor; } public void DrawEditorShortcuts() { AmplifyShaderEditorWindow window = UIUtils.CurrentWindow; if ( window != null ) { if ( m_editorShortcuts == null ) { m_editorShortcuts = window.ShortcutManagerInstance.AvailableEditorShortcutsList; } EditorGUI.indentLevel--; int count = m_editorShortcuts.Count; for ( int i = 0; i < count; i++ ) { DrawItem( m_editorShortcuts[ i ].Name, m_editorShortcuts[ i ].Description ); } DrawItem( "LMB Drag", "Box selection" ); DrawItem( "RMB Drag", "Camera Pan" ); DrawItem( "Alt + RMB Drag", "Scroll Menu" ); DrawItem( "Control + Node Drag", "Node move with snap" ); DrawItem( "Alt + Node Drag", "Auto-(Dis)Connect node on existing wire connection" ); EditorGUI.indentLevel++; } else { EditorGUILayout.LabelField( NoASEWindowWarning ); } } public void DrawMenuShortcuts() { AmplifyShaderEditorWindow window = UIUtils.CurrentWindow; if ( window != null ) { EditorGUI.indentLevel--; DrawItem( ShortcutsManager.ScrollUpKey.ToString(), "Scroll Up Menu" ); DrawItem( ShortcutsManager.ScrollDownKey.ToString(), "Scroll Down Menu" ); DrawItem( "RMB Drag", "Scroll Menu" ); EditorGUI.indentLevel++; } else { EditorGUILayout.LabelField( NoASEWindowWarning ); } } void DrawItem( string name, string description ) { GUILayout.BeginHorizontal(); GUILayout.Label( name, m_labelStyleBold , GUILayout.Width( TitleLabelWidth ) ); GUILayout.Label( description, m_labelStyle ); GUILayout.EndHorizontal(); GUILayout.Space( PixelSeparator ); } public void DrawNodesShortcuts() { AmplifyShaderEditorWindow window = UIUtils.CurrentWindow; if ( window != null ) { if ( m_nodesShortcuts == null ) { m_nodesShortcuts = window.ShortcutManagerInstance.AvailableNodesShortcutsList; } EditorGUI.indentLevel--; int count = m_nodesShortcuts.Count; for ( int i = 0; i < count; i++ ) { DrawItem( m_nodesShortcuts[ i ].Name, m_nodesShortcuts[ i ].Description ); } EditorGUI.indentLevel++; } else { EditorGUILayout.LabelField( NoASEWindowWarning ); } } string CreateCompatibilityString( string source ) { string[] split = source.Split( '.' ); if ( split != null && split.Length > 1 ) { return split[ 1 ]; } else { return source; } } public void DrawCompatibleAssets() { AmplifyShaderEditorWindow window = UIUtils.CurrentWindow; if ( window != null ) { if ( m_compatibleAssetsInfo == null ) { m_compatibleAssetsInfo = new List<string[]>(); List<ContextMenuItem> items = window.ContextMenuInstance.MenuItems; int count = items.Count; for ( int i = 0; i < count; i++ ) { if ( items[ i ].NodeAttributes != null && items[ i ].NodeAttributes.CastType != null ) { string types = string.Empty; if ( items[ i ].NodeAttributes.CastType.Length > 1 ) { for ( int j = 0; j < items[ i ].NodeAttributes.CastType.Length; j++ ) { types += CreateCompatibilityString( items[ i ].NodeAttributes.CastType[ j ].ToString() ); if ( j < items[ i ].NodeAttributes.CastType.Length - 1 ) { types += ", "; } } } else { types = CreateCompatibilityString( items[ i ].NodeAttributes.CastType[ 0 ].ToString() ); } m_compatibleAssetsInfo.Add( new string[] { items[ i ].NodeAttributes.Name + ": ", types } ); } } } EditorGUI.indentLevel--; int nodeCount = m_compatibleAssetsInfo.Count; for ( int j = 0; j < nodeCount; j++ ) { DrawItem( m_compatibleAssetsInfo[ j ][ 0 ], m_compatibleAssetsInfo[ j ][ 1 ] ); } EditorGUI.indentLevel++; } else { EditorGUILayout.LabelField( NoASEWindowWarning ); } } public void DrawNodeDescriptions() { AmplifyShaderEditorWindow window = UIUtils.CurrentWindow; if ( window != null ) { if ( m_nodeDescriptionsInfo == null ) { //fetch node info m_nodeDescriptionsInfo = new List<NodeDescriptionInfo>(); Dictionary<string, PaletteFilterData> nodeData = window.CurrentPaletteWindow.BuildFullList(); var enumerator = nodeData.GetEnumerator(); while ( enumerator.MoveNext() ) { List<ContextMenuItem> nodes = enumerator.Current.Value.Contents; int count = nodes.Count; NodeDescriptionInfo currInfo = new NodeDescriptionInfo(); currInfo.Contents = new string[ count, 2 ]; currInfo.Category = enumerator.Current.Key; for ( int i = 0; i < count; i++ ) { currInfo.Contents[ i, 0 ] = nodes[ i ].Name + ':'; currInfo.Contents[ i, 1 ] = nodes[ i ].Description; } m_nodeDescriptionsInfo.Add( currInfo ); } } //draw { GUILayout.Space( 5 ); int count = m_nodeDescriptionsInfo.Count; EditorGUI.indentLevel--; for ( int i = 0; i < count; i++ ) { m_nodeDescriptionsInfo[ i ].FoldoutValue = EditorGUILayout.Foldout( m_nodeDescriptionsInfo[ i ].FoldoutValue, m_nodeDescriptionsInfo[ i ].Category, m_nodeInfoFoldoutStyle ); if ( m_nodeDescriptionsInfo[ i ].FoldoutValue ) { EditorGUI.indentLevel++; int nodeCount = m_nodeDescriptionsInfo[ i ].Contents.GetLength( 0 ); for ( int j = 0; j < nodeCount; j++ ) { GUILayout.Label( m_nodeDescriptionsInfo[ i ].Contents[ j, 0 ], m_nodeInfoLabelStyleBold ); GUILayout.Label( m_nodeDescriptionsInfo[ i ].Contents[ j, 1 ], m_nodeInfoLabelStyle ); GUILayout.Space( PixelSeparator ); } EditorGUI.indentLevel--; } GUILayout.Space( PixelSeparator ); } EditorGUI.indentLevel++; } } else { EditorGUILayout.LabelField( NoASEWindowWarning ); } } private void OnDestroy() { m_nodesShortcuts = null; m_editorShortcuts = null; m_portStyle = null; m_labelStyle = null; m_labelStyleBold = null; m_nodeInfoLabelStyle = null; m_nodeInfoLabelStyleBold = null; m_nodeInfoFoldoutStyle = null; m_init = false; if ( m_nodeDescriptionsInfo != null ) { m_nodeDescriptionsInfo.Clear(); m_nodeDescriptionsInfo = null; } m_compatibleAssetsInfo.Clear(); m_compatibleAssetsInfo = null; } } }
//----------------------------------------------------------------------------- // <copyright file="SmtpDateTime.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace System.Net.Mime { using System; using System.Net.Mail; using System.Globalization; using System.Collections.Generic; using System.Diagnostics; #region RFC2822 date time string format description // Format of Date Time string as described by RFC 2822 section 4.3 which obsoletes // some field formats that were allowed under RFC 822 // date-time = [ day-of-week "," ] date FWS time [CFWS] // day-of-week = ([FWS] day-name) / obs-day-of-week // day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" // date = day month year // year = 4*DIGIT / obs-year // month = (FWS month-name FWS) / obs-month // month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / // "Sep" / "Oct" / "Nov" / "Dec" // day = ([FWS] 1*2DIGIT) / obs-day // time = time-of-day FWS zone // time-of-day = hour ":" minute [ ":" second ] // hour = 2DIGIT / obs-hour // minute = 2DIGIT / obs-minute // second = 2DIGIT / obs-second // zone = (( "+" / "-" ) 4DIGIT) / obs-zone #endregion // stores a Date and a Time Zone. These are parsed and formatted according to the // rules in RFC 2822 section 3.3. // This class is immutable internal class SmtpDateTime { #region constants // use this when a time zone is unknown or is not supplied internal const string unknownTimeZoneDefaultOffset = "-0000"; internal const string utcDefaultTimeZoneOffset = "+0000"; internal const int offsetLength = 5; // range for absolute value of minutes. it is not necessary to include a max value for hours since // the two-digit value that is parsed can't exceed the max value of hours, which is 99 internal const int maxMinuteValue = 59; // possible valid values for a date string // these do NOT include the timezone internal const string dateFormatWithDayOfWeek = "ddd, dd MMM yyyy HH:mm:ss"; internal const string dateFormatWithoutDayOfWeek = "dd MMM yyyy HH:mm:ss"; internal const string dateFormatWithDayOfWeekAndNoSeconds = "ddd, dd MMM yyyy HH:mm"; internal const string dateFormatWithoutDayOfWeekAndNoSeconds = "dd MMM yyyy HH:mm"; #endregion #region static fields // array of all possible date time values // if a string matches any one of these it will be parsed correctly internal readonly static string[] validDateTimeFormats = new string[]{ dateFormatWithDayOfWeek, dateFormatWithoutDayOfWeek, dateFormatWithDayOfWeekAndNoSeconds, dateFormatWithoutDayOfWeekAndNoSeconds }; internal readonly static char[] allowedWhiteSpaceChars = new char[] { ' ', '\t' }; internal static readonly IDictionary<string, TimeSpan> timeZoneOffsetLookup = SmtpDateTime.InitializeShortHandLookups(); // a TimeSpan must be between these two values in order for it to be within the range allowed // by RFC 2822 internal readonly static long timeSpanMaxTicks = TimeSpan.TicksPerHour * 99 + TimeSpan.TicksPerMinute * 59; // allowed max values for each digit. min value is always 0 internal readonly static int offsetMaxValue = 9959; #endregion #region static initializers internal static IDictionary<string, TimeSpan> InitializeShortHandLookups() { Dictionary<string, TimeSpan> tempTimeZoneOffsetLookup = new Dictionary<string, TimeSpan>(); // all well-known short hand time zone values and their semantic equivalents tempTimeZoneOffsetLookup.Add("UT", TimeSpan.Zero); // +0000 tempTimeZoneOffsetLookup.Add("GMT", TimeSpan.Zero); // +0000 tempTimeZoneOffsetLookup.Add("EDT", new TimeSpan(-4, 0, 0)); // -0400 tempTimeZoneOffsetLookup.Add("EST", new TimeSpan(-5, 0, 0)); // -0500 tempTimeZoneOffsetLookup.Add("CDT", new TimeSpan(-5, 0, 0)); // -0500 tempTimeZoneOffsetLookup.Add("CST", new TimeSpan(-6, 0, 0)); // -0600 tempTimeZoneOffsetLookup.Add("MDT", new TimeSpan(-6, 0, 0)); // -0600 tempTimeZoneOffsetLookup.Add("MST", new TimeSpan(-7, 0, 0)); // -0700 tempTimeZoneOffsetLookup.Add("PDT", new TimeSpan(-7, 0, 0)); // -0700 tempTimeZoneOffsetLookup.Add("PST", new TimeSpan(-8, 0, 0)); // -0800 return tempTimeZoneOffsetLookup; } #endregion #region private fields private readonly DateTime date; private readonly TimeSpan timeZone; // true if the time zone is unspecified i.e. -0000 // the time zone will usually be specified private readonly bool unknownTimeZone = false; #endregion #region constructors internal SmtpDateTime(DateTime value) { date = value; switch (value.Kind) { case DateTimeKind.Local: // GetUtcOffset takes local time zone information into account e.g. daylight savings time TimeSpan localTimeZone = TimeZoneInfo.Local.GetUtcOffset(value); this.timeZone = ValidateAndGetSanitizedTimeSpan(localTimeZone); break; case DateTimeKind.Unspecified: this.unknownTimeZone = true; break; case DateTimeKind.Utc: this.timeZone = TimeSpan.Zero; break; } } internal SmtpDateTime(string value) { string timeZoneOffset; this.date = ParseValue(value, out timeZoneOffset); if (!TryParseTimeZoneString(timeZoneOffset, out timeZone)) { // time zone is unknown this.unknownTimeZone = true; } } #endregion #region internal properties internal DateTime Date { get { if (this.unknownTimeZone) { return DateTime.SpecifyKind(this.date, DateTimeKind.Unspecified); } else { // DateTimeOffset will convert the value of this.date to the time as // specified in this.timeZone DateTimeOffset offset = new DateTimeOffset(this.date, this.timeZone); return offset.LocalDateTime; } } } #if DEBUG // this method is only called by test code internal string TimeZone { get { if (this.unknownTimeZone) { return unknownTimeZoneDefaultOffset; } return TimeSpanToOffset(this.timeZone); } } #endif #endregion #region internals // outputs the RFC 2822 formatted date string including time zone public override string ToString() { if (unknownTimeZone) { return String.Format("{0} {1}", FormatDate(this.date), unknownTimeZoneDefaultOffset); } else { return String.Format("{0} {1}", FormatDate(this.date), TimeSpanToOffset(this.timeZone)); } } // returns true if the offset is of the form [+|-]dddd and // within the range 0000 to 9959 internal void ValidateAndGetTimeZoneOffsetValues( string offset, out bool positive, out int hours, out int minutes) { Debug.Assert(!String.IsNullOrEmpty(offset), "violation of precondition: offset must not be null or empty"); Debug.Assert(offset != unknownTimeZoneDefaultOffset, "Violation of precondition: do not pass an unknown offset"); Debug.Assert(offset.StartsWith("-") || offset.StartsWith("+"), "offset initial character was not a + or -"); if (offset.Length != offsetLength) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } positive = offset.StartsWith("+"); // TryParse will parse in base 10 by default. do not allow any styles of input beyond the default // which is numeric values only if (!Int32.TryParse(offset.Substring(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out hours)) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } if (!Int32.TryParse(offset.Substring(3, 2), NumberStyles.None, CultureInfo.InvariantCulture, out minutes)) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } // we only explicitly validate the minutes. they must be below 59 // the hours are implicitly validated as a number formed from a string of length // 2 can only be <= 99 if (minutes > maxMinuteValue) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } } // returns true if the time zone short hand is all alphabetical characters internal void ValidateTimeZoneShortHandValue(string value) { // time zones can't be empty Debug.Assert(!String.IsNullOrEmpty(value), "violation of precondition: offset must not be null or empty"); // time zones must all be alphabetical characters for (int i = 0; i < value.Length; i++) { if (!Char.IsLetter(value, i)) { throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter)); } } } // formats a date only. Does not include time zone internal string FormatDate(DateTime value) { string output = value.ToString("ddd, dd MMM yyyy H:mm:ss", CultureInfo.InvariantCulture); return output; } // parses the date and time zone // postconditions: // return value is valid DateTime representation of the Date portion of data // timeZone is the portion of data which should contain the time zone data // timeZone is NOT evaluated by ParseValue internal DateTime ParseValue(string data, out string timeZone) { // check that there is something to parse if (string.IsNullOrEmpty(data)) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } // find the first occurrence of ':' // this tells us where the separator between hour and minute are int indexOfHourSeparator = data.IndexOf(':'); // no ':' means invalid value if (indexOfHourSeparator == -1) { throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter)); } // now we know where hours and minutes are separated. The first whitespace after // that MUST be the separator between the time portion and the timezone portion // timezone may have additional spaces, characters, or comments after it but // this is ok since we'll parse that whole section later int indexOfTimeZoneSeparator = data.IndexOfAny(allowedWhiteSpaceChars, indexOfHourSeparator); if (indexOfTimeZoneSeparator == -1) { throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter)); } // extract the time portion and remove all leading and trailing whitespace string date = data.Substring(0, indexOfTimeZoneSeparator).Trim(); // attempt to parse the DateTime component. DateTime dateValue; if (!DateTime.TryParseExact(date, validDateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dateValue)) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } // kind property will be Unspecified since no timezone info was in the date string Debug.Assert(dateValue.Kind == DateTimeKind.Unspecified); // extract the second half of the string. This will start with at least one whitespace character. // Trim the string to remove these characters. string timeZoneString = data.Substring(indexOfTimeZoneSeparator).Trim(); // find, if any, the first whitespace character after the timezone. // These will be CFWS and must be ignored. Remove them. int endOfTimeZoneOffset = timeZoneString.IndexOfAny(allowedWhiteSpaceChars); if (endOfTimeZoneOffset != -1) { timeZoneString = timeZoneString.Substring(0, endOfTimeZoneOffset); } if (String.IsNullOrEmpty(timeZoneString)) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } timeZone = timeZoneString; return dateValue; } // if this returns true, timeZone is the correct TimeSpan representation of the input // if it returns false then the time zone is unknown and so timeZone must be ignored internal bool TryParseTimeZoneString(string timeZoneString, out TimeSpan timeZone) { // initialize default timeZone = TimeSpan.Zero; // see if the zone is the special unspecified case, a numeric offset, or a shorthand string if (timeZoneString == unknownTimeZoneDefaultOffset) { // The inputed time zone is the special value "unknown", -0000 return false; } else if ((timeZoneString[0] == '+' || timeZoneString[0] == '-')) { bool positive; int hours; int minutes; ValidateAndGetTimeZoneOffsetValues(timeZoneString, out positive, out hours, out minutes); // Apply the negative sign, if applicable, to whichever of hours or minutes is NOT 0. if (!positive) { if (hours != 0) { hours *= -1; } else if (minutes != 0) { minutes *= -1; } } timeZone = new TimeSpan((int) hours, (int) minutes, 0); return true; } else { // not an offset so ensure that it contains no invalid characters ValidateTimeZoneShortHandValue(timeZoneString); // check if the shorthand value has a semantically equivalent offset if (timeZoneOffsetLookup.ContainsKey(timeZoneString)) { timeZone = timeZoneOffsetLookup[timeZoneString]; return true; } } // default time zone is the unspecified zone: -0000 return false; } internal TimeSpan ValidateAndGetSanitizedTimeSpan(TimeSpan span) { // sanitize the time span by removing the seconds and milliseconds. Days are not handled here TimeSpan sanitizedTimeSpan = new TimeSpan(span.Days, span.Hours, span.Minutes, 0, 0); // validate range of time span if (Math.Abs(sanitizedTimeSpan.Ticks) > timeSpanMaxTicks) { throw new FormatException(SR.GetString(SR.MailDateInvalidFormat)); } return sanitizedTimeSpan; } // precondition: span must be sanitized and within a valid range internal string TimeSpanToOffset(TimeSpan span) { Debug.Assert(span.Seconds == 0, "Span had seconds value"); Debug.Assert(span.Milliseconds == 0, "Span had milliseconds value"); if (span.Ticks == 0) { return utcDefaultTimeZoneOffset; } else { string output; // get the total number of hours since TimeSpan.Hours won't go beyond 24 // ensure that it's a whole number since the fractional part represents minutes uint hours = (uint)Math.Abs(Math.Floor(span.TotalHours)); uint minutes = (uint)Math.Abs(span.Minutes); Debug.Assert((hours != 0) || (minutes !=0), "Input validation ensures hours or minutes isn't zero"); output = span.Ticks > 0 ? "+" : "-"; // hours and minutes must be two digits if (hours < 10) { output += "0"; } output += hours.ToString(); if (minutes < 10) { output += "0"; } output += minutes.ToString(); return output; } } #endregion } }
// 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 gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>Video</c> resource.</summary> public sealed partial class VideoName : gax::IResourceName, sys::IEquatable<VideoName> { /// <summary>The possible contents of <see cref="VideoName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}/videos/{video_id}</c>.</summary> CustomerVideo = 1, } private static gax::PathTemplate s_customerVideo = new gax::PathTemplate("customers/{customer_id}/videos/{video_id}"); /// <summary>Creates a <see cref="VideoName"/> 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="VideoName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static VideoName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new VideoName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="VideoName"/> with the pattern <c>customers/{customer_id}/videos/{video_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="VideoName"/> constructed from the provided ids.</returns> public static VideoName FromCustomerVideo(string customerId, string videoId) => new VideoName(ResourceNameType.CustomerVideo, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), videoId: gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="VideoName"/> with pattern /// <c>customers/{customer_id}/videos/{video_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VideoName"/> with pattern /// <c>customers/{customer_id}/videos/{video_id}</c>. /// </returns> public static string Format(string customerId, string videoId) => FormatCustomerVideo(customerId, videoId); /// <summary> /// Formats the IDs into the string representation of this <see cref="VideoName"/> with pattern /// <c>customers/{customer_id}/videos/{video_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VideoName"/> with pattern /// <c>customers/{customer_id}/videos/{video_id}</c>. /// </returns> public static string FormatCustomerVideo(string customerId, string videoId) => s_customerVideo.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId))); /// <summary>Parses the given resource name string into a new <see cref="VideoName"/> 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}/videos/{video_id}</c></description></item> /// </list> /// </remarks> /// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="VideoName"/> if successful.</returns> public static VideoName Parse(string videoName) => Parse(videoName, false); /// <summary> /// Parses the given resource name string into a new <see cref="VideoName"/> 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}/videos/{video_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="videoName">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="VideoName"/> if successful.</returns> public static VideoName Parse(string videoName, bool allowUnparsed) => TryParse(videoName, allowUnparsed, out VideoName 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="VideoName"/> 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}/videos/{video_id}</c></description></item> /// </list> /// </remarks> /// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="VideoName"/>, 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 videoName, out VideoName result) => TryParse(videoName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VideoName"/> 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}/videos/{video_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="videoName">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="VideoName"/>, 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 videoName, bool allowUnparsed, out VideoName result) { gax::GaxPreconditions.CheckNotNull(videoName, nameof(videoName)); gax::TemplatedResourceName resourceName; if (s_customerVideo.TryParseName(videoName, out resourceName)) { result = FromCustomerVideo(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(videoName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private VideoName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string videoId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; VideoId = videoId; } /// <summary> /// Constructs a new instance of a <see cref="VideoName"/> class from the component parts of pattern /// <c>customers/{customer_id}/videos/{video_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param> public VideoName(string customerId, string videoId) : this(ResourceNameType.CustomerVideo, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), videoId: gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Video</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string VideoId { 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.CustomerVideo: return s_customerVideo.Expand(CustomerId, VideoId); 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 VideoName); /// <inheritdoc/> public bool Equals(VideoName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(VideoName a, VideoName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(VideoName a, VideoName b) => !(a == b); } public partial class Video { /// <summary> /// <see cref="VideoName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal VideoName ResourceNameAsVideoName { get => string.IsNullOrEmpty(ResourceName) ? null : VideoName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// Copyright 2012 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.TimeZones.Cldr; using NodaTime.Utility; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; namespace NodaTime.TimeZones.IO { /// <summary> /// Provides the raw data exposed by <see cref="TzdbDateTimeZoneSource"/>. /// </summary> internal sealed class TzdbStreamData { private static readonly Dictionary<TzdbStreamFieldId, Action<Builder, TzdbStreamField>> FieldHandlers = new Dictionary<TzdbStreamFieldId, Action<Builder, TzdbStreamField>> { [TzdbStreamFieldId.StringPool] = (builder, field) => builder.HandleStringPoolField(field), [TzdbStreamFieldId.TimeZone] = (builder, field) => builder.HandleZoneField(field), [TzdbStreamFieldId.TzdbIdMap] = (builder, field) => builder.HandleTzdbIdMapField(field), [TzdbStreamFieldId.TzdbVersion] = (builder, field) => builder.HandleTzdbVersionField(field), [TzdbStreamFieldId.CldrSupplementalWindowsZones] = (builder, field) => builder.HandleSupplementalWindowsZonesField(field), [TzdbStreamFieldId.ZoneLocations] = (builder, field) => builder.HandleZoneLocationsField(field), [TzdbStreamFieldId.Zone1970Locations] = (builder, field) => builder.HandleZone1970LocationsField(field) }; private const int AcceptedVersion = 0; private readonly IReadOnlyList<string> stringPool; private readonly IDictionary<string, TzdbStreamField> zoneFields; /// <summary> /// Returns the TZDB version string. /// </summary> public string TzdbVersion { get; } /// <summary> /// Returns the TZDB ID dictionary (alias to canonical ID). /// </summary> public ReadOnlyDictionary<string, string> TzdbIdMap { get; } /// <summary> /// Returns the Windows mapping dictionary. (As the type is immutable, it can be exposed directly /// to callers.) /// </summary> public WindowsZones WindowsMapping { get; } /// <summary> /// Returns the zone locations for the source, or null if no location data is available. /// </summary> public ReadOnlyCollection<TzdbZoneLocation>? ZoneLocations { get; } /// <summary> /// Returns the "zone 1970" locations for the source, or null if no such location data is available. /// </summary> public ReadOnlyCollection<TzdbZone1970Location>? Zone1970Locations { get; } [VisibleForTesting] internal TzdbStreamData(Builder builder) { stringPool = CheckNotNull(builder.stringPool, "string pool"); var mutableIdMap = CheckNotNull(builder.tzdbIdMap, "TZDB alias map"); TzdbVersion = CheckNotNull(builder.tzdbVersion, "TZDB version"); WindowsMapping = CheckNotNull(builder.windowsMapping, "CLDR Supplemental Windows Zones"); zoneFields = builder.zoneFields; ZoneLocations = builder.zoneLocations; Zone1970Locations = builder.zone1970Locations; // Add in the canonical IDs as mappings to themselves. foreach (var id in zoneFields.Keys) { mutableIdMap[id] = id; } TzdbIdMap = new ReadOnlyDictionary<string, string>(mutableIdMap); } /// <summary> /// Creates the <see cref="DateTimeZone"/> for the given canonical ID, which will definitely /// be one of the values of the TzdbAliases dictionary. /// </summary> /// <param name="id">ID for the returned zone, which may be an alias.</param> /// <param name="canonicalId">Canonical ID for zone data</param> public DateTimeZone CreateZone(string id, string canonicalId) { Preconditions.CheckNotNull(id, nameof(id)); Preconditions.CheckNotNull(canonicalId, nameof(canonicalId)); using (var stream = zoneFields[canonicalId].CreateStream()) { var reader = new DateTimeZoneReader(stream, stringPool); // Skip over the ID before the zone data itself reader.ReadString(); var type = (DateTimeZoneWriter.DateTimeZoneType) reader.ReadByte(); return type switch { DateTimeZoneWriter.DateTimeZoneType.Fixed => FixedDateTimeZone.Read(reader, id), DateTimeZoneWriter.DateTimeZoneType.Precalculated => CachedDateTimeZone.ForZone(PrecalculatedDateTimeZone.Read(reader, id)), _ => throw new InvalidNodaDataException($"Unknown time zone type {type}") }; } } // Like Preconditions.CheckNotNull, but specifically for incomplete data. private static T CheckNotNull<T>(T? input, string name) where T : class { if (input is null) { throw new InvalidNodaDataException($"Incomplete TZDB data. Missing field: {name}"); } return input; } internal static TzdbStreamData FromStream(Stream stream) { Preconditions.CheckNotNull(stream, nameof(stream)); int version = new BinaryReader(stream).ReadInt32(); if (version != AcceptedVersion) { throw new InvalidNodaDataException($"Unable to read stream with version {version}"); } Builder builder = new Builder(); foreach (var field in TzdbStreamField.ReadFields(stream)) { // Only handle fields we know about if (FieldHandlers.TryGetValue(field.Id, out Action<Builder, TzdbStreamField> handler)) { handler(builder, field); } } return new TzdbStreamData(builder); } /// <summary> /// Mutable builder class used during parsing. /// </summary> [VisibleForTesting] internal class Builder { internal IReadOnlyList<string>? stringPool; internal string? tzdbVersion; // Note: deliberately mutable, as this is useful later when we map the canonical IDs to themselves. // This is a mapping of the aliases from TZDB, at this point. internal IDictionary<string, string>? tzdbIdMap; internal ReadOnlyCollection<TzdbZoneLocation>? zoneLocations = null; internal ReadOnlyCollection<TzdbZone1970Location>? zone1970Locations = null; internal WindowsZones? windowsMapping; internal readonly IDictionary<string, TzdbStreamField> zoneFields = new Dictionary<string, TzdbStreamField>(); internal void HandleStringPoolField(TzdbStreamField field) { CheckSingleField(field, stringPool); using (var stream = field.CreateStream()) { var reader = new DateTimeZoneReader(stream, null); int count = reader.ReadCount(); var stringPoolArray = new string[count]; for (int i = 0; i < count; i++) { stringPoolArray[i] = reader.ReadString(); } stringPool = stringPoolArray; } } internal void HandleZoneField(TzdbStreamField field) { CheckStringPoolPresence(field); // Just read the ID from the zone - we don't parse the data yet. // (We could, but we might as well be lazy.) using (var stream = field.CreateStream()) { var reader = new DateTimeZoneReader(stream, stringPool); string id = reader.ReadString(); if (zoneFields.ContainsKey(id)) { throw new InvalidNodaDataException($"Multiple definitions for zone {id}"); } zoneFields[id] = field; } } internal void HandleTzdbVersionField(TzdbStreamField field) { CheckSingleField(field, tzdbVersion); tzdbVersion = field.ExtractSingleValue(reader => reader.ReadString(), null); } internal void HandleTzdbIdMapField(TzdbStreamField field) { CheckSingleField(field, tzdbIdMap); tzdbIdMap = field.ExtractSingleValue(reader => reader.ReadDictionary(), stringPool); } internal void HandleSupplementalWindowsZonesField(TzdbStreamField field) { CheckSingleField(field, windowsMapping); windowsMapping = field.ExtractSingleValue(WindowsZones.Read, stringPool); } internal void HandleZoneLocationsField(TzdbStreamField field) { CheckSingleField(field, zoneLocations); CheckStringPoolPresence(field); using (var stream = field.CreateStream()) { var reader = new DateTimeZoneReader(stream, stringPool); var count = reader.ReadCount(); var array = new TzdbZoneLocation[count]; for (int i = 0; i < count; i++) { array[i] = TzdbZoneLocation.Read(reader); } zoneLocations = Array.AsReadOnly(array); } } internal void HandleZone1970LocationsField(TzdbStreamField field) { CheckSingleField(field, zone1970Locations); CheckStringPoolPresence(field); using (var stream = field.CreateStream()) { var reader = new DateTimeZoneReader(stream, stringPool); var count = reader.ReadCount(); var array = new TzdbZone1970Location[count]; for (int i = 0; i < count; i++) { array[i] = TzdbZone1970Location.Read(reader); } zone1970Locations = Array.AsReadOnly(array); } } private void CheckSingleField(TzdbStreamField field, object? expectedNullField) { if (expectedNullField != null) { throw new InvalidNodaDataException($"Multiple fields of ID {field.Id}"); } } private void CheckStringPoolPresence(TzdbStreamField field) { if (stringPool is null) { throw new InvalidNodaDataException($"String pool must be present before field {field.Id}"); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Web.API.Areas.HelpPage.ModelDescriptions; using Web.API.Areas.HelpPage.Models; namespace Web.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object; using System; using System.Drawing; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { [Serializable] public class TouchEventArgs : EventArgs { public IAvatar Avatar; public Vector3 TouchBiNormal; public Vector3 TouchNormal; public Vector3 TouchPosition; public Vector2 TouchUV; public Vector2 TouchST; public int TouchMaterialIndex; } public delegate void OnTouchDelegate(IObject sender, TouchEventArgs e); public interface IObject : IEntity { #region Events event OnTouchDelegate OnTouch; #endregion /// <summary> /// Returns whether or not this object is still in the world. /// Eg, if you store an IObject reference, however the object /// is deleted before you use it, it will throw a NullReference /// exception. 'Exists' allows you to check the object is still /// in play before utilizing it. /// </summary> /// <example> /// IObject deleteMe = World.Objects[0]; /// /// if (deleteMe.Exists) { /// deleteMe.Say("Hello, I still exist!"); /// } /// /// World.Objects.Remove(deleteMe); /// /// if (!deleteMe.Exists) { /// Host.Console.Info("I was deleted"); /// } /// </example> /// <remarks> /// Objects should be near-guarunteed to exist for any event which /// passes them as an argument. Storing an object for a longer period /// of time however will limit their reliability. /// /// It is a good practice to use Try/Catch blocks handling for /// NullReferenceException, when accessing remote objects. /// </remarks> bool Exists { get; } /// <summary> /// The local region-unique ID for this object. /// </summary> uint LocalID { get; } /// <summary> /// The description assigned to this object. /// </summary> String Description { get; set; } /// <summary> /// Returns the UUID of the Owner of the Object. /// </summary> UUID OwnerId { get; } /// <summary> /// Returns the UUID of the Creator of the Object. /// </summary> UUID CreatorId { get; } /// <summary> /// Returns the root object of a linkset. If this object is the root, it will return itself. /// </summary> IObject Root { get; } /// <summary> /// Returns a collection of objects which are linked to the current object. Does not include the root object. /// </summary> IObject[] Children { get; } /// <summary> /// Returns a list of materials attached to this object. Each may contain unique texture /// and other visual information. For primitive based objects, this correlates with /// Object Faces. For mesh based objects, this correlates with Materials. /// </summary> IObjectMaterial[] Materials { get; } /// <summary> /// The bounding box of the object. Primitive and Mesh objects alike are scaled to fit within these bounds. /// </summary> Vector3 Scale { get; set; } /// <summary> /// The rotation of the object relative to the Scene /// </summary> Quaternion WorldRotation { get; set; } /// <summary> /// The rotation of the object relative to a parent object /// If root, works the same as WorldRotation /// </summary> Quaternion OffsetRotation { get; set; } /// <summary> /// The position of the object relative to a parent object /// If root, works the same as WorldPosition /// </summary> Vector3 OffsetPosition { get; set; } Vector3 SitTarget { get; set; } String SitTargetText { get; set; } String TouchText { get; set; } /// <summary> /// Text to be associated with this object, in the /// Second Life(r) viewer, this is shown above the /// object. /// </summary> String Text { get; set; } bool IsRotationLockedX { get; set; } // SetStatus(!ROTATE_X) bool IsRotationLockedY { get; set; } // SetStatus(!ROTATE_Y) bool IsRotationLockedZ { get; set; } // SetStatus(!ROTATE_Z) bool IsSandboxed { get; set; } // SetStatus(SANDBOX) bool IsImmotile { get; set; } // SetStatus(BLOCK_GRAB) bool IsAlwaysReturned { get; set; } // SetStatus(!DIE_AT_EDGE) bool IsTemporary { get; set; } // TEMP_ON_REZ bool IsFlexible { get; set; } IObjectShape Shape { get; } // TODO: // PrimHole // Repeats, Offsets, Cut/Dimple/ProfileCut // Hollow, Twist, HoleSize, // Taper[A+B], Shear[A+B], Revolutions, // RadiusOffset, Skew PhysicsMaterial PhysicsMaterial { get; set; } IObjectPhysics Physics { get; } IObjectSound Sound { get; } /// <summary> /// Causes the object to speak to its surroundings, /// equivilent to LSL/OSSL llSay /// </summary> /// <param name="msg">The message to send to the user</param> void Say(string msg); /// <summary> /// Causes the object to speak to on a specific channel, /// equivilent to LSL/OSSL llSay /// </summary> /// <param name="msg">The message to send to the user</param> /// <param name="channel">The channel on which to send the message</param> void Say(string msg,int channel); /// <summary> /// Opens a Dialog Panel in the Users Viewer, /// equivilent to LSL/OSSL llDialog /// </summary> /// <param name="avatar">The UUID of the Avatar to which the Dialog should be send</param> /// <param name="message">The Message to display at the top of the Dialog</param> /// <param name="buttons">The Strings that act as label/value of the Bottons in the Dialog</param> /// <param name="chat_channel">The channel on which to send the response</param> void Dialog(UUID avatar, string message, string[] buttons, int chat_channel); //// <value> /// Grants access to the objects inventory /// </value> IObjectInventory Inventory { get; } } public enum PhysicsMaterial { Default, Glass, Metal, Plastic, Wood, Rubber, Stone, Flesh } public enum TextureMapping { Default, Planar } public interface IObjectMaterial { Color Color { get; set; } UUID Texture { get; set; } TextureMapping Mapping { get; set; } // SetPrimParms(PRIM_TEXGEN) bool Bright { get; set; } // SetPrimParms(FULLBRIGHT) double Bloom { get; set; } // SetPrimParms(GLOW) bool Shiny { get; set; } // SetPrimParms(SHINY) bool BumpMap { get; set; } // SetPrimParms(BUMPMAP) [DEPRECATE IN FAVOUR OF UUID?] } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bridge.Translator { public class InvocationBlock : ConversionBlock { public InvocationBlock(IEmitter emitter, InvocationExpression invocationExpression) : base(emitter, invocationExpression) { this.Emitter = emitter; this.InvocationExpression = invocationExpression; } public InvocationExpression InvocationExpression { get; set; } protected override Expression GetExpression() { return this.InvocationExpression; } protected override void EmitConversionExpression() { this.VisitInvocationExpression(); } protected virtual bool IsEmptyPartialInvoking(IMethod method) { return method != null && method.IsPartial && !method.HasBody; } protected void WriteThisExtension(Expression target) { if (target.HasChildren) { var first = target.Children.ElementAt(0); var expression = first as Expression; if (expression != null) { expression.AcceptVisitor(this.Emitter); } else { this.WriteThis(); } } } public static bool IsConditionallyRemoved(InvocationExpression invocationExpression, IEntity entity) { if (entity == null) { return false; } var result = new List<string>(); foreach (var a in entity.Attributes) { var type = a.AttributeType.GetDefinition(); if (type != null && type.FullName.Equals("System.Diagnostics.ConditionalAttribute", StringComparison.Ordinal)) { if (a.PositionalArguments.Count > 0) { var symbol = a.PositionalArguments[0].ConstantValue as string; if (symbol != null) { result.Add(symbol); } } } } if (result.Count > 0) { var syntaxTree = invocationExpression.GetParent<SyntaxTree>(); if (syntaxTree != null) { return !result.Intersect(syntaxTree.ConditionalSymbols).Any(); } } return false; } protected void VisitInvocationExpression() { InvocationExpression invocationExpression = this.InvocationExpression; int pos = this.Emitter.Output.Length; if (this.Emitter.IsForbiddenInvocation(invocationExpression)) { throw new EmitterException(invocationExpression, "This method cannot be invoked directly"); } var oldValue = this.Emitter.ReplaceAwaiterByVar; var oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling; if (this.Emitter.IsAsync && !this.Emitter.AsyncExpressionHandling) { this.WriteAwaiters(invocationExpression); this.Emitter.ReplaceAwaiterByVar = true; this.Emitter.AsyncExpressionHandling = true; } Tuple<bool, bool, string> inlineInfo = this.Emitter.GetInlineCode(invocationExpression); var argsInfo = new ArgumentsInfo(this.Emitter, invocationExpression); var argsExpressions = argsInfo.ArgumentsExpressions; var paramsArg = argsInfo.ParamsExpression; var targetResolve = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter); var csharpInvocation = targetResolve as CSharpInvocationResolveResult; MemberReferenceExpression targetMember = invocationExpression.Target as MemberReferenceExpression; bool isObjectLiteral = csharpInvocation != null && csharpInvocation.Member.DeclaringTypeDefinition != null ? this.Emitter.Validator.IsObjectLiteral(csharpInvocation.Member.DeclaringTypeDefinition) : false; var interceptor = this.Emitter.Plugins.OnInvocation(this, this.InvocationExpression, targetResolve as InvocationResolveResult); if (interceptor.Cancel) { this.Emitter.SkipSemiColon = true; this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } if (!string.IsNullOrEmpty(interceptor.Replacement)) { this.Write(interceptor.Replacement); this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } if (inlineInfo != null) { bool isStaticMethod = inlineInfo.Item1; bool isInlineMethod = inlineInfo.Item2; string inlineScript = inlineInfo.Item3; if (isInlineMethod) { if (invocationExpression.Arguments.Count > 0) { var code = invocationExpression.Arguments.First(); var inlineExpression = code as PrimitiveExpression; if (inlineExpression == null) { throw new EmitterException(invocationExpression, "Only primitive expression can be inlined"); } string value = inlineExpression.Value.ToString().Trim(); if (value.Length > 0) { value = InlineArgumentsBlock.ReplaceInlineArgs(this, inlineExpression.Value.ToString(), invocationExpression.Arguments.Skip(1).ToArray()); this.Write(value); value = value.Trim(); if (value[value.Length - 1] == ';' || value.EndsWith("*/", StringComparison.InvariantCulture) || value.StartsWith("//")) { this.Emitter.SkipSemiColon = true; this.WriteNewLine(); } } else { // Empty string, emit nothing. this.Emitter.SkipSemiColon = true; } this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } else { MemberReferenceExpression targetMemberRef = invocationExpression.Target as MemberReferenceExpression; bool isBase = targetMemberRef != null && targetMemberRef.Target is BaseReferenceExpression; if (!String.IsNullOrEmpty(inlineScript) && (isBase || invocationExpression.Target is IdentifierExpression)) { argsInfo.ThisArgument = "this"; bool noThis = !Helpers.HasThis(inlineScript); if (inlineScript.StartsWith("<self>")) { noThis = false; inlineScript = inlineScript.Substring(6); } if (!noThis) { Emitter.ThisRefCounter++; } if (!isStaticMethod && noThis) { this.WriteThis(); this.WriteDot(); } new InlineArgumentsBlock(this.Emitter, argsInfo, inlineScript).Emit(); this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } } if (targetMember != null || isObjectLiteral) { var member = targetMember != null ? this.Emitter.Resolver.ResolveNode(targetMember.Target, this.Emitter) : null; if (targetResolve != null) { InvocationResolveResult invocationResult; bool isExtensionMethodInvocation = false; if (csharpInvocation != null) { if (member != null && member.Type.Kind == TypeKind.Delegate && (/*csharpInvocation.Member.Name == "Invoke" || */csharpInvocation.Member.Name == "BeginInvoke" || csharpInvocation.Member.Name == "EndInvoke") && !csharpInvocation.IsExtensionMethodInvocation) { throw new EmitterException(invocationExpression, "Delegate's 'Invoke' methods are not supported. Please use direct delegate invoke."); } if (csharpInvocation.IsExtensionMethodInvocation) { invocationResult = csharpInvocation; isExtensionMethodInvocation = true; var resolvedMethod = invocationResult.Member as IMethod; if (resolvedMethod != null && resolvedMethod.IsExtensionMethod) { string inline = this.Emitter.GetInline(resolvedMethod); bool isNative = this.IsNativeMethod(resolvedMethod); if (string.IsNullOrWhiteSpace(inline) && isNative) { invocationResult = null; } } } else { invocationResult = null; } if (this.IsEmptyPartialInvoking(csharpInvocation.Member as IMethod) || IsConditionallyRemoved(invocationExpression, csharpInvocation.Member)) { this.Emitter.SkipSemiColon = true; this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } else { invocationResult = targetResolve as InvocationResolveResult; if (invocationResult != null && (this.IsEmptyPartialInvoking(invocationResult.Member as IMethod) || IsConditionallyRemoved(invocationExpression, invocationResult.Member))) { this.Emitter.SkipSemiColon = true; this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } if (invocationResult == null) { invocationResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as InvocationResolveResult; } if (invocationResult != null) { var resolvedMethod = invocationResult.Member as IMethod; if (resolvedMethod != null && (resolvedMethod.IsExtensionMethod || isObjectLiteral)) { string inline = this.Emitter.GetInline(resolvedMethod); bool isNative = this.IsNativeMethod(resolvedMethod); if (isExtensionMethodInvocation || isObjectLiteral) { if (!string.IsNullOrWhiteSpace(inline)) { this.Write(""); StringBuilder savedBuilder = this.Emitter.Output; this.Emitter.Output = new StringBuilder(); this.WriteThisExtension(invocationExpression.Target); argsInfo.ThisArgument = this.Emitter.Output.ToString(); this.Emitter.Output = savedBuilder; new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit(); } else if (!isNative) { var overloads = OverloadsCollection.Create(this.Emitter, resolvedMethod); if (isObjectLiteral && !resolvedMethod.IsStatic && resolvedMethod.DeclaringType.Kind == TypeKind.Interface) { this.Write("Bridge.getType("); this.WriteThisExtension(invocationExpression.Target); this.Write(")."); } else { string name = BridgeTypes.ToJsName(resolvedMethod.DeclaringType, this.Emitter, ignoreLiteralName: false) + "."; this.Write(name); } if (isObjectLiteral && !resolvedMethod.IsStatic) { this.Write(JS.Fields.PROTOTYPE + "." + overloads.GetOverloadName() + "." + JS.Funcs.CALL); } else { this.Write(overloads.GetOverloadName()); } var isIgnoreClass = resolvedMethod.DeclaringTypeDefinition != null && this.Emitter.Validator.IsExternalType(resolvedMethod.DeclaringTypeDefinition); int openPos = this.Emitter.Output.Length; this.WriteOpenParentheses(); this.Emitter.Comma = false; if (isObjectLiteral && !resolvedMethod.IsStatic) { this.WriteThisExtension(invocationExpression.Target); this.Emitter.Comma = true; } if (!isIgnoreClass && !Helpers.IsIgnoreGeneric(resolvedMethod, this.Emitter) && argsInfo.HasTypeArguments) { this.EnsureComma(false); new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit(); this.Emitter.Comma = true; } if (!isObjectLiteral && resolvedMethod.IsStatic) { this.EnsureComma(false); this.WriteThisExtension(invocationExpression.Target); this.Emitter.Comma = true; } if (invocationExpression.Arguments.Count > 0) { this.EnsureComma(false); } new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression, openPos).Emit(); this.WriteCloseParentheses(); } if (!string.IsNullOrWhiteSpace(inline) || !isNative) { this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } else if (isNative) { if (!string.IsNullOrWhiteSpace(inline)) { this.Write(""); StringBuilder savedBuilder = this.Emitter.Output; this.Emitter.Output = new StringBuilder(); this.WriteThisExtension(invocationExpression.Target); argsInfo.ThisArgument = this.Emitter.Output.ToString(); this.Emitter.Output = savedBuilder; new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit(); } else { argsExpressions.First().AcceptVisitor(this.Emitter); this.WriteDot(); string name = this.Emitter.GetEntityName(resolvedMethod); this.Write(name); int openPos = this.Emitter.Output.Length; this.WriteOpenParentheses(); new ExpressionListBlock(this.Emitter, argsExpressions.Skip(1), paramsArg, invocationExpression, openPos).Emit(); this.WriteCloseParentheses(); } this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } } } } } var proto = false; if (targetMember != null && targetMember.Target is BaseReferenceExpression) { var rr = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter) as MemberResolveResult; if (rr != null) { proto = rr.IsVirtualCall; /*var method = rr.Member as IMethod; if (method != null && method.IsVirtual) { proto = true; } else { var prop = rr.Member as IProperty; if (prop != null && prop.IsVirtual) { proto = true; } }*/ } } if (proto) { var baseType = this.Emitter.GetBaseMethodOwnerTypeDefinition(targetMember.MemberName, targetMember.TypeArguments.Count); bool isIgnore = this.Emitter.Validator.IsExternalType(baseType); bool needComma = false; var resolveResult = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter); string name = null; if (this.Emitter.TypeInfo.GetBaseTypes(this.Emitter).Any()) { name = BridgeTypes.ToJsName(this.Emitter.TypeInfo.GetBaseClass(this.Emitter), this.Emitter); } else { name = BridgeTypes.ToJsName(baseType, this.Emitter); } string baseMethod; bool isIgnoreGeneric = false; if (resolveResult is MemberResolveResult) { MemberResolveResult memberResult = (MemberResolveResult)resolveResult; baseMethod = OverloadsCollection.Create(this.Emitter, memberResult.Member).GetOverloadName(); isIgnoreGeneric = Helpers.IsIgnoreGeneric(memberResult.Member, this.Emitter); } else { baseMethod = targetMember.MemberName; baseMethod = Object.Net.Utilities.StringUtils.ToLowerCamelCase(baseMethod); } this.Write(name, "." + JS.Fields.PROTOTYPE + ".", baseMethod); this.WriteCall(); this.WriteOpenParentheses(); this.WriteThis(); this.Emitter.Comma = true; if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments) { new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit(); } needComma = false; foreach (var arg in argsExpressions) { if (arg == null) { continue; } this.EnsureComma(false); if (needComma) { this.WriteComma(); } needComma = true; arg.AcceptVisitor(this.Emitter); } this.Emitter.Comma = false; this.WriteCloseParentheses(); } else { var dynamicResolveResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as DynamicInvocationResolveResult; IMethod method = null; if (dynamicResolveResult != null) { var group = dynamicResolveResult.Target as MethodGroupResolveResult; if (group != null && group.Methods.Count() > 1) { method = group.Methods.FirstOrDefault(m => { if (dynamicResolveResult.Arguments.Count != m.Parameters.Count) { return false; } for (int i = 0; i < m.Parameters.Count; i++) { var argType = dynamicResolveResult.Arguments[i].Type; if (argType.Kind == TypeKind.Dynamic) { argType = this.Emitter.Resolver.Compilation.FindType(TypeCode.Object); } if (!m.Parameters[i].Type.Equals(argType)) { return false; } } return true; }); if (method == null) { throw new EmitterException(invocationExpression, Bridge.Translator.Constants.Messages.Exceptions.DYNAMIC_INVOCATION_TOO_MANY_OVERLOADS); } } } else { var targetResolveResult = this.Emitter.Resolver.ResolveNode(invocationExpression.Target, this.Emitter); var invocationResolveResult = targetResolveResult as MemberResolveResult; if (invocationResolveResult != null) { method = invocationResolveResult.Member as IMethod; } } if (this.IsEmptyPartialInvoking(method) || IsConditionallyRemoved(invocationExpression, method)) { this.Emitter.SkipSemiColon = true; this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; return; } bool isIgnore = method != null && method.DeclaringTypeDefinition != null && this.Emitter.Validator.IsExternalType(method.DeclaringTypeDefinition); bool needExpand = false; if (method != null) { string paramsName = null; var paramsParam = method.Parameters.FirstOrDefault(p => p.IsParams); if (paramsParam != null) { paramsName = paramsParam.Name; } if (paramsName != null) { if (csharpInvocation != null && !csharpInvocation.IsExpandedForm) { needExpand = true; } } } int count = this.Emitter.Writers.Count; invocationExpression.Target.AcceptVisitor(this.Emitter); if (this.Emitter.Writers.Count > count) { var writer = this.Emitter.Writers.Pop(); if (method != null && method.IsExtensionMethod) { StringBuilder savedBuilder = this.Emitter.Output; this.Emitter.Output = new StringBuilder(); this.WriteThisExtension(invocationExpression.Target); argsInfo.ThisArgument = this.Emitter.Output.ToString(); this.Emitter.Output = savedBuilder; } else if (writer.ThisArg != null) { argsInfo.ThisArgument = writer.ThisArg; } new InlineArgumentsBlock(this.Emitter, argsInfo, writer.InlineCode) { IgnoreRange = writer.IgnoreRange }.Emit(); var result = this.Emitter.Output.ToString(); this.Emitter.Output = writer.Output; this.Emitter.IsNewLine = writer.IsNewLine; this.Write(result); if (writer.Callback != null) { writer.Callback.Invoke(); } } else { if (needExpand && isIgnore) { this.Write("." + JS.Funcs.APPLY); } int openPos = this.Emitter.Output.Length; this.WriteOpenParentheses(); bool isIgnoreGeneric = false; var invocationResult = targetResolve as InvocationResolveResult; if (invocationResult != null) { isIgnoreGeneric = Helpers.IsIgnoreGeneric(invocationResult.Member, this.Emitter); } bool isWrapRest = false; if (needExpand && isIgnore) { StringBuilder savedBuilder = this.Emitter.Output; this.Emitter.Output = new StringBuilder(); this.WriteThisExtension(invocationExpression.Target); var thisArg = this.Emitter.Output.ToString(); this.Emitter.Output = savedBuilder; this.Write(thisArg); this.Emitter.Comma = true; if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments) { new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit(); } this.EnsureComma(false); if (argsExpressions.Length > 1) { this.WriteOpenBracket(); var elb = new ExpressionListBlock(this.Emitter, argsExpressions.Take(argsExpressions.Length - 1).ToArray(), paramsArg, invocationExpression, openPos); elb.IgnoreExpandParams = true; elb.Emit(); this.WriteCloseBracket(); this.Write(".concat("); elb = new ExpressionListBlock(this.Emitter, new Expression[] { argsExpressions[argsExpressions.Length - 1] }, paramsArg, invocationExpression, openPos); elb.IgnoreExpandParams = true; elb.Emit(); this.Write(")"); } else { new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression, -1).Emit(); } } else { if (method != null && method.Attributes.Any(a => a.AttributeType.FullName == "Bridge.WrapRestAttribute")) { isWrapRest = true; } this.Emitter.Comma = false; if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments) { new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit(); } if (invocationExpression.Arguments.Count > 0 || argsExpressions.Length > 0 && !argsExpressions.All(expr => expr == null)) { this.EnsureComma(false); } new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression, openPos).Emit(); } if (isWrapRest) { this.EnsureComma(false); this.Write("Bridge.fn.bind(this, function () "); this.BeginBlock(); this.Emitter.WrapRestCounter++; this.Emitter.SkipSemiColon = true; } else { this.Emitter.Comma = false; this.WriteCloseParentheses(); } } } var irr = targetResolve as InvocationResolveResult; if (irr != null && irr.Member.MemberDefinition != null && irr.Member.MemberDefinition.ReturnType.Kind == TypeKind.TypeParameter) { Helpers.CheckValueTypeClone(this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter), invocationExpression, this, pos); } this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; } private bool IsNativeMethod(IMethod resolvedMethod) { return resolvedMethod.DeclaringTypeDefinition != null && this.Emitter.Validator.IsExternalType(resolvedMethod.DeclaringTypeDefinition); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.Globalization; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// TextMessageWriter writes constraint descriptions and messages /// in displayable form as a text stream. It tailors the display /// of individual message components to form the standard message /// format of NUnit assertion failure messages. /// </summary> public class TextMessageWriter : MessageWriter { #region Message Formats and Constants private static readonly int DEFAULT_LINE_LENGTH = 78; // Prefixes used in all failure messages. All must be the same // length, which is held in the PrefixLength field. Should not // contain any tabs or newline characters. /// <summary> /// Prefix used for the expected value line of a message /// </summary> public static readonly string Pfx_Expected = " Expected: "; /// <summary> /// Prefix used for the actual value line of a message /// </summary> public static readonly string Pfx_Actual = " But was: "; /// <summary> /// Length of a message prefix /// </summary> public static readonly int PrefixLength = Pfx_Expected.Length; private static readonly string Fmt_Connector = " {0} "; private static readonly string Fmt_Predicate = "{0} "; //private static readonly string Fmt_Label = "{0}"; private static readonly string Fmt_Modifier = ", {0}"; private static readonly string Fmt_Null = "null"; private static readonly string Fmt_EmptyString = "<string.Empty>"; private static readonly string Fmt_EmptyCollection = "<empty>"; private static readonly string Fmt_String = "\"{0}\""; private static readonly string Fmt_Char = "'{0}'"; private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff"; private static readonly string Fmt_ValueType = "{0}"; private static readonly string Fmt_Default = "<{0}>"; #endregion private int maxLineLength = DEFAULT_LINE_LENGTH; #region Constructors /// <summary> /// Construct a TextMessageWriter /// </summary> public TextMessageWriter() { } /// <summary> /// Construct a TextMessageWriter, specifying a user message /// and optional formatting arguments. /// </summary> /// <param name="userMessage"></param> /// <param name="args"></param> public TextMessageWriter(string userMessage, params object[] args) { if ( userMessage != null && userMessage != string.Empty) this.WriteMessageLine(userMessage, args); } #endregion #region Properties /// <summary> /// Gets or sets the maximum line length for this writer /// </summary> public override int MaxLineLength { get { return maxLineLength; } set { maxLineLength = value; } } #endregion #region Public Methods - High Level /// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a givel /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) Write(" "); if (args != null && args.Length > 0) message = string.Format(message, args); WriteLine(message); } } /// <summary> /// Display Expected and Actual lines for a constraint. This /// is called by MessageWriter's default implementation of /// WriteMessageTo and provides the generic two-line display. /// </summary> /// <param name="constraint">The constraint that failed</param> public override void DisplayDifferences(Constraint constraint) { WriteExpectedLine(constraint); WriteActualLine(constraint); } /// <summary> /// Display Expected and Actual lines for given values. This /// method may be called by constraints that need more control over /// the display of actual and expected values than is provided /// by the default implementation. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> public override void DisplayDifferences(object expected, object actual) { WriteExpectedLine(expected); WriteActualLine(actual); } /// <summary> /// Display Expected and Actual lines for given values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { WriteExpectedLine(expected, tolerance); WriteActualLine(actual); } /// <summary> /// Display the expected and actual string values on separate lines. /// If the mismatch parameter is >=0, an additional line is displayed /// line containing a caret that points to the mismatch point. /// </summary> /// <param name="expected">The expected string value</param> /// <param name="actual">The actual string value</param> /// <param name="mismatch">The point at which the strings don't match or -1</param> /// <param name="ignoreCase">If true, case is ignored in string comparisons</param> /// <param name="clipping">If true, clip the strings to fit the max line length</param> public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { // Maximum string we can display without truncating int maxDisplayLength = MaxLineLength - PrefixLength // Allow for prefix - 2; // 2 quotation marks if ( clipping ) MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); // The mismatch position may have changed due to clipping or white space conversion mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write( Pfx_Expected ); WriteExpectedValue( expected ); if ( ignoreCase ) WriteModifier( "ignoring case" ); WriteLine(); WriteActualLine( actual ); //DisplayDifferences(expected, actual); if (mismatch >= 0) WriteCaretLine(mismatch); } #endregion #region Public Methods - Low Level /// <summary> /// Writes the text for a connector. /// </summary> /// <param name="connector">The connector.</param> public override void WriteConnector(string connector) { Write(Fmt_Connector, connector); } /// <summary> /// Writes the text for a predicate. /// </summary> /// <param name="predicate">The predicate.</param> public override void WritePredicate(string predicate) { Write(Fmt_Predicate, predicate); } //public override void WriteLabel(string label) //{ // Write(Fmt_Label, label); //} /// <summary> /// Write the text for a modifier. /// </summary> /// <param name="modifier">The modifier.</param> public override void WriteModifier(string modifier) { Write(Fmt_Modifier, modifier); } /// <summary> /// Writes the text for an expected value. /// </summary> /// <param name="expected">The expected value.</param> public override void WriteExpectedValue(object expected) { WriteValue(expected); } /// <summary> /// Writes the text for an actual value. /// </summary> /// <param name="actual">The actual value.</param> public override void WriteActualValue(object actual) { WriteValue(actual); } /// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { if (val == null) Write(Fmt_Null); else if (val.GetType().IsArray) WriteArray((Array)val); else if (val is ICollection) WriteCollectionElements((ICollection)val, 0, 10); else if (val is string) WriteString((string)val); else if (val is char) WriteChar((char)val); else if (val is double) WriteDouble((double)val); else if (val is float) WriteFloat((float)val); else if (val is decimal) WriteDecimal((decimal)val); else if (val is DateTime) WriteDateTime((DateTime)val); else if (val.GetType().IsValueType) Write(Fmt_ValueType, val); else Write(Fmt_Default, val); } /// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(ICollection collection, int start, int max) { if ( collection.Count == 0 ) { Write(Fmt_EmptyCollection); return; } int count = 0; int index = 0; Write("< "); foreach (object obj in collection) { if ( index++ >= start ) { if (count > 0) Write(", "); WriteValue(obj); if ( ++count >= max ) break; } } if ( index < collection.Count ) Write("..."); Write(" >"); } private void WriteArray(Array array) { if ( array.Length == 0 ) { Write( Fmt_EmptyCollection ); return; } int rank = array.Rank; int[] products = new int[rank]; for (int product = 1, r = rank; --r >= 0; ) products[r] = product *= array.GetLength(r); int count = 0; foreach (object obj in array) { if (count > 0) Write(", "); bool startSegment = false; for (int r = 0; r < rank; r++) { startSegment = startSegment || count % products[r] == 0; if (startSegment) Write("< "); } WriteValue(obj); ++count; bool nextSegment = false; for (int r = 0; r < rank; r++) { nextSegment = nextSegment || count % products[r] == 0; if (nextSegment) Write(" >"); } } } private void WriteString(string s) { if (s == string.Empty) Write(Fmt_EmptyString); else Write(Fmt_String, s); } private void WriteChar(char c) { Write(Fmt_Char, c); } private void WriteDouble(double d) { if (double.IsNaN(d) || double.IsInfinity(d)) Write(d); else { string s = d.ToString("G17", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) Write(s + "d"); else Write(s + ".0d"); } } private void WriteFloat(float f) { if (float.IsNaN(f) || float.IsInfinity(f)) Write(f); else { string s = f.ToString("G9", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) Write(s + "f"); else Write(s + ".0f"); } } private void WriteDecimal(Decimal d) { Write(d.ToString("G29", CultureInfo.InvariantCulture) + "m"); } private void WriteDateTime(DateTime dt) { Write(dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture)); } #endregion #region Helper Methods /// <summary> /// Write the generic 'Expected' line for a constraint /// </summary> /// <param name="constraint">The constraint that failed</param> private void WriteExpectedLine(Constraint constraint) { Write(Pfx_Expected); constraint.WriteDescriptionTo(this); WriteLine(); } /// <summary> /// Write the generic 'Expected' line for a given value /// </summary> /// <param name="expected">The expected value</param> private void WriteExpectedLine(object expected) { WriteExpectedLine(expected, null); } /// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); WriteExpectedValue(expected); if (tolerance != null && !tolerance.IsEmpty) { WriteConnector("+/-"); WriteExpectedValue(tolerance.Value); } WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a constraint /// </summary> /// <param name="constraint">The constraint for which the actual value is to be written</param> private void WriteActualLine(Constraint constraint) { Write(Pfx_Actual); constraint.WriteActualValueTo(this); WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a given value /// </summary> /// <param name="actual">The actual value causing a failure</param> private void WriteActualLine(object actual) { Write(Pfx_Actual); WriteActualValue(actual); WriteLine(); } private void WriteCaretLine(int mismatch) { // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); } #endregion } }
// // System.Data.Common.DataColumnMappingCollection // // Authors: // Rodrigo Moya (rodrigo@ximian.com) // Tim Coleman (tim@timcoleman.com) // // (C) Ximian, Inc // Copyright (C) Tim Coleman, 2002-2003 // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.ComponentModel; using System.Data; namespace System.Data.Common { public sealed class DataColumnMappingCollection : MarshalByRefObject, IColumnMappingCollection , IList, ICollection, IEnumerable { #region Fields ArrayList list; Hashtable sourceColumns; Hashtable dataSetColumns; #endregion // Fields #region Constructors public DataColumnMappingCollection () { list = new ArrayList (); sourceColumns = new Hashtable (); dataSetColumns = new Hashtable (); } #endregion // Constructors #region Properties [Browsable (false)] [DataSysDescription ("The number of items in the collection")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public int Count { get { return list.Count; } } [Browsable (false)] [DataSysDescription ("The specified DataColumnMapping object.")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public DataColumnMapping this [int index] { get { return (DataColumnMapping)(list[index]); } set { DataColumnMapping mapping = (DataColumnMapping)(list[index]); sourceColumns[mapping] = value; dataSetColumns[mapping] = value; list[index] = value; } } [Browsable (false)] [DataSysDescription ("DataTableMappings_Item")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public DataColumnMapping this [string sourceColumn] { get { if (!Contains(sourceColumn)) { throw new IndexOutOfRangeException("DataColumnMappingCollection doesn't contain DataColumnMapping with SourceColumn '" + sourceColumn + "'."); } return (DataColumnMapping) sourceColumns[sourceColumn]; } set { this [list.IndexOf (sourceColumns[sourceColumn])] = value; } } object ICollection.SyncRoot { get { return list.SyncRoot; } } bool ICollection.IsSynchronized { get { return list.IsSynchronized; } } object IColumnMappingCollection.this [string sourceColumn] { get { return this [sourceColumn]; } set { if (!(value is DataColumnMapping)) throw new ArgumentException (); this [sourceColumn] = (DataColumnMapping) value; } } object IList.this [int index] { get { return this[index]; } set { if (!(value is DataColumnMapping)) throw new ArgumentException (); this [index] = (DataColumnMapping) value; } } bool IList.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } #endregion // Properties #region Methods public int Add (object value) { if (!(value is DataColumnMapping)) throw new InvalidCastException (); list.Add (value); sourceColumns[((DataColumnMapping)value).SourceColumn] = value; dataSetColumns[((DataColumnMapping)value).DataSetColumn] = value; return list.IndexOf (value); } public DataColumnMapping Add (string sourceColumn, string dataSetColumn) { DataColumnMapping mapping = new DataColumnMapping (sourceColumn, dataSetColumn); Add (mapping); return mapping; } #if NET_2_0 [MonoTODO] public void AddRange (Array values) { throw new NotImplementedException (); } #endif public void AddRange (DataColumnMapping[] values) { foreach (DataColumnMapping mapping in values) Add (mapping); } public void Clear () { list.Clear (); } public bool Contains (object value) { if (!(value is DataColumnMapping)) throw new InvalidCastException("Object is not of type DataColumnMapping"); return (list.Contains (value)); } public bool Contains (string value) { return (sourceColumns.Contains (value)); } public void CopyTo (Array array, int index) { (list.ToArray()).CopyTo(array,index); } public DataColumnMapping GetByDataSetColumn (string value) { // this should work case-insenstive. if (!(dataSetColumns[value] == null)) return (DataColumnMapping)(dataSetColumns[value]); else { string lowcasevalue = value.ToLower(); object [] keyarray = new object[dataSetColumns.Count]; dataSetColumns.Keys.CopyTo(keyarray,0); for (int i=0; i<keyarray.Length; i++) { string temp = (string) keyarray[i]; if (lowcasevalue.Equals(temp.ToLower())) return (DataColumnMapping)(dataSetColumns[keyarray[i]]); } return null; } } [EditorBrowsable (EditorBrowsableState.Advanced)] public static DataColumnMapping GetColumnMappingBySchemaAction (DataColumnMappingCollection columnMappings, string sourceColumn, MissingMappingAction mappingAction) { if (columnMappings.Contains (sourceColumn)) return columnMappings[sourceColumn]; if (mappingAction == MissingMappingAction.Ignore) return null; if (mappingAction == MissingMappingAction.Error) throw new InvalidOperationException (String.Format ("Missing SourceColumn mapping for '{0}'", sourceColumn)); return new DataColumnMapping (sourceColumn, sourceColumn); } #if NET_2_0 [MonoTODO] public static DataColumn GetDataColumn (DataColumnMappingCollection columnMappings, string sourceColumn, Type dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) { throw new NotImplementedException (); } #endif public IEnumerator GetEnumerator () { return list.GetEnumerator (); } IColumnMapping IColumnMappingCollection.Add (string sourceColumnName, string dataSetColumnName) { return Add (sourceColumnName, dataSetColumnName); } IColumnMapping IColumnMappingCollection.GetByDataSetColumn (string dataSetColumnName) { return GetByDataSetColumn (dataSetColumnName); } public int IndexOf (object value) { return list.IndexOf (value); } public int IndexOf (string sourceColumn) { return list.IndexOf (sourceColumns[sourceColumn]); } public int IndexOfDataSetColumn (string value) { // this should work case-insensitive if (!(dataSetColumns[value] == null)) return list.IndexOf (dataSetColumns[value]); else { string lowcasevalue = value.ToLower(); object [] keyarray = new object[dataSetColumns.Count]; dataSetColumns.Keys.CopyTo(keyarray,0); for (int i=0; i<keyarray.Length; i++) { string temp = (string) keyarray[i]; if (lowcasevalue.Equals(temp.ToLower())) return list.IndexOf (dataSetColumns[keyarray[i]]); } return -1; } } public void Insert (int index, object value) { list.Insert (index, value); sourceColumns[((DataColumnMapping)value).SourceColumn] = value; dataSetColumns[((DataColumnMapping)value).DataSetColumn] = value; } public void Remove (object value) { int index = list.IndexOf (value); sourceColumns.Remove(((DataColumnMapping)value).SourceColumn); dataSetColumns.Remove(((DataColumnMapping)value).DataSetColumn); if (( index < 0 ) || (index >=list.Count)) throw new ArgumentException("There is no such element in collection."); list.Remove (value); } public void RemoveAt (int index) { if (( index < 0 ) || (index >=list.Count)) throw new IndexOutOfRangeException("There is no element in collection."); Remove (list[index]); } public void RemoveAt (string sourceColumn) { RemoveAt (list.IndexOf (sourceColumns[sourceColumn])); } #endregion // Methods } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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.Reflection; using System.Threading; using NUnit.Framework; #if !NETCOREAPP1_1 using NUnit.Compatibility; #endif using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Builders; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Commands; using NUnit.Framework.Internal.Execution; namespace NUnit.TestUtilities { /// <summary> /// Utility Class used to build and run NUnit tests used as test data /// </summary> public static class TestBuilder { #region Build Tests public static TestSuite MakeSuite(string name) { return new TestSuite(name); } public static TestSuite MakeFixture(Type type) { return (TestSuite)new DefaultSuiteBuilder().BuildFrom(type); } public static TestSuite MakeFixture(object fixture) { TestSuite suite = MakeFixture(fixture.GetType()); suite.Fixture = fixture; return suite; } public static TestSuite MakeParameterizedMethodSuite(Type type, string methodName) { var suite = MakeTestFromMethod(type, methodName) as TestSuite; Assert.NotNull(suite, "Unable to create parameterized suite - most likely there is no data provided"); return suite; } public static TestMethod MakeTestCase(Type type, string methodName) { var test = MakeTestFromMethod(type, methodName) as TestMethod; Assert.NotNull(test, "Unable to create TestMethod from {0}", methodName); return test; } // Will return either a ParameterizedMethodSuite or an NUnitTestMethod // depending on whether the method takes arguments or not internal static Test MakeTestFromMethod(Type type, string methodName) { var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) Assert.Fail("Method not found: " + methodName); return new DefaultTestCaseBuilder().BuildFrom(new FixtureMethod(type, method)); } #endregion #region Create WorkItems public static WorkItem CreateWorkItem(Type type) { return CreateWorkItem(MakeFixture(type)); } public static WorkItem CreateWorkItem(Type type, string methodName) { return CreateWorkItem(MakeTestFromMethod(type, methodName)); } public static WorkItem CreateWorkItem(Test test) { var context = new TestExecutionContext(); context.Dispatcher = new SuperSimpleDispatcher(); return CreateWorkItem(test, context); } public static WorkItem CreateWorkItem(Test test, object testObject) { var context = new TestExecutionContext(); context.TestObject = testObject; context.Dispatcher = new SuperSimpleDispatcher(); return CreateWorkItem(test, context); } public static WorkItem CreateWorkItem(Test test, TestExecutionContext context) { var work = WorkItemBuilder.CreateWorkItem(test, TestFilter.Empty, true); work.InitializeContext(context); return work; } #endregion #region Run Tests public static ITestResult RunTestFixture(Type type) { return RunTest(MakeFixture(type), null); } public static ITestResult RunTestFixture(object fixture) { return RunTest(MakeFixture(fixture), fixture); } public static ITestResult RunParameterizedMethodSuite(Type type, string methodName) { var suite = MakeParameterizedMethodSuite(type, methodName); object testObject = null; if (!type.IsStatic()) testObject = Reflect.Construct(type); return RunTest(suite, testObject); } public static ITestResult RunTestCase(Type type, string methodName) { var testMethod = MakeTestCase(type, methodName); object testObject = null; if (!type.IsStatic()) testObject = Reflect.Construct(type); return RunTest(testMethod, testObject); } public static ITestResult RunTestCase(object fixture, string methodName) { var testMethod = MakeTestCase(fixture.GetType(), methodName); return RunTest(testMethod, fixture); } public static ITestResult RunAsTestCase(Action action) { var method = action.GetMethodInfo(); var testMethod = MakeTestCase(method.DeclaringType, method.Name); return RunTest(testMethod); } public static ITestResult RunTest(Test test) { return RunTest(test, null); } public static ITestResult RunTest(Test test, object testObject) { return ExecuteWorkItem(CreateWorkItem(test, testObject)); } public static ITestResult ExecuteWorkItem(WorkItem work) { work.Execute(); // TODO: Replace with an event - but not while method is static while (work.State != WorkItemState.Complete) { Thread.Sleep(1); } return work.Result; } #endregion #region Nested TestDispatcher Class /// <summary> /// SuperSimpleDispatcher merely executes the work item. /// It is needed particularly when running suites, since /// the child items require a dispatcher in the context. /// </summary> class SuperSimpleDispatcher : IWorkItemDispatcher { public int LevelOfParallelism { get { return 0; } } public void Start(WorkItem topLevelWorkItem) { topLevelWorkItem.Execute(); } public void Dispatch(WorkItem work) { work.Execute(); } public void CancelRun(bool force) { throw new NotImplementedException(); } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Data; using System.Data.Common; using Epi; using Epi.Data; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Write command /// </summary> public partial class WriteDialog : CommandDesignDialog { private object selectedDataSource; #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public WriteDialog() { InitializeComponent(); } /// <summary> /// Constructor for the Write dialog /// </summary> /// <param name="frm"></param> public WriteDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } #endregion Constructors #region Private Methods /// <summary> /// Set event handlers (in base) for OK and SaveOnly events /// </summary> private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); PopulateDataSourcePlugIns(); } } /// <summary> /// Loads cmbOutputFormats /// </summary> private void LoadOutputFormats() { ComboBox cbx = cmbOutputFormat; //TODO: Attach list from configuration //DataView dv = AppData.Instance.DatabaseFormatsDataTable.DefaultView; //dv.Sort = ColumnNames.POSITION; //cbx.DataSource = dv; cbx.DisplayMember = ColumnNames.NAME; cbx.ValueMember = ColumnNames.ID; cbx.SelectedIndex = 0; } private void LoadVariables() { VariableType scopeWord = VariableType.DataSource | VariableType.Standard | VariableType.Global; FillVariableListBox(lbxVariables, scopeWord); ////First get the list of all variables //// DataTable variables = GetAllVariablesAsDataTable(true, true, true, false); //DataTable variables = GetMemoryRegion().GetVariablesAsDataTable( // VariableType.DataSource | // VariableType.Standard | // VariableType.Global); ////Sort the data //System.Data.DataView dv = variables.DefaultView; //dv.Sort = ColumnNames.NAME; //lbxVariables.DataSource = dv; //lbxVariables.DisplayMember = ColumnNames.NAME; //lbxVariables.ValueMember = ColumnNames.NAME; lbxVariables.SelectedIndex = -1; this.lbxVariables.SelectedIndexChanged += new System.EventHandler(this.lbxVariables_SelectedIndexChanged); } private void SomethingChanged(object sender, EventArgs e) { cmbDataTable.Enabled = (cmbOutputFormat.Text != "Text"); CheckForInputSufficiency(); } /// <summary> /// Attach the DataFormats combobox with supported data formats /// </summary> private void PopulateDataSourcePlugIns() { Configuration config = Configuration.GetNewInstance(); cmbOutputFormat.Items.Clear(); foreach (Epi.DataSets.Config.DataDriverRow row in config.DataDrivers) { if (row.Type == Configuration.PostgreSQLDriver || row.Type == Configuration.MySQLDriver) { continue; } cmbOutputFormat.Items.Add(new ComboBoxItem(row.Type, row.DisplayName, null)); } //cmbOutputFormat.Items.Add(new ComboBoxItem(null, "Text", null)); cmbOutputFormat.SelectedIndex = 0; } #endregion Private Methods #region Private Nested Class private class ComboBoxItem { #region Implementation private string key; public string Key { get { return key; } set { key = value; } } private object value; public object Value { get { return this.value; } set { this.value = value; } } private string text; public string Text { get { return text; } set { text = value; } } public ComboBoxItem(string key, string text, object value) { this.key = key; this.value = value; this.text = text; } public override string ToString() { return text.ToString(); } #endregion } #endregion Private Nested Class #region Event Handlers /// <summary> /// Loads the combo box with valid data formats /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void Write_Load(object sender, System.EventArgs e) { LoadOutputFormats(); LoadVariables(); } ///// <summary> ///// Sets Enabled property of cbxAllExcept ///// </summary> ///// <param name="sender">Object that fired the event.</param> ///// <param name="e">.NET supplied event args.</param> //private void cbxAll_CheckChanged(object sender, System.EventArgs e) //{ // if (cbxAll.Checked) // { // cbxAllExcept.Enabled = false; // cbxAllExcept.Checked = false; // } // else // { // cbxAllExcept.Enabled = true; // } //} /// <summary> /// Clears user input /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { lbxVariables.SelectedIndex = -1; txtFileName.Text = string.Empty; cmbDataTable.Text = string.Empty; cmbDataTable.SelectedIndex = -1; cmbDataTable.SelectedIndex = -1; this.cmbDataTable.SelectedItem = null; //cbxAll.Checked = true; } private void btnGetFile_Click(object sender, System.EventArgs e) { ComboBoxItem selectedPlugIn = cmbOutputFormat.SelectedItem as ComboBoxItem; if (selectedPlugIn == null) { throw new GeneralException("No data source plug-in is selected in combo box."); } if (selectedPlugIn.Key == null) // default project { OpenFileDialog dlg = new OpenFileDialog(); if (cmbOutputFormat.Text == "Text" || cmbOutputFormat.Text.ToUpperInvariant() == "FLAT ASCII FILE") { dlg.Filter = "Text Files (*.txt) |*.txt"; } else { dlg.Filter = "Database Files (*.mdb) |*.mdb"; } dlg.CheckFileExists = false; dlg.CheckPathExists = false; if (dlg.ShowDialog() == DialogResult.OK) { if (cmbOutputFormat.Text.ToUpperInvariant() == "TEXT" || cmbOutputFormat.Text.ToUpperInvariant() == "FLAT ASCII FILE") { if (!dlg.FileName.EndsWith(".txt") && dlg.FileName.EndsWith(".csv")) { txtFileName.Text = dlg.FileName + ".csv"; } else { txtFileName.Text = dlg.FileName; } } else { txtFileName.Text = dlg.FileName; } } } else { IDbDriverFactory dbFactory = null; switch (selectedPlugIn.Key) { case "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver); break; case "Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver); break; case "Epi.Data.Office.AccessDBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; case "Epi.Data.Office.ExcelWBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver); break; case "Epi.Data.Office.Access2007DBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Access2007Driver); break; case "Epi.Data.Office.Excel2007WBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Excel2007Driver); break; case "Epi.Data.Office.CsvFileFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.CsvDriver); break; case "Epi.Data.PostgreSQL.PostgreSQLDBFactory, Epi.Data.PostgreSQL": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.PostgreSQLDriver); break; default: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; } DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder(); IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder); IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb(); dialog.ShouldIgnoreNonExistance = true; DialogResult result = ((Form)dialog).ShowDialog(); if (result == DialogResult.OK) { bool success = false; db.ConnectionString = dialog.DbConnectionStringBuilder.ToString(); txtFileName.Text = db.ConnectionString; try { success = db.TestConnection(); } catch { success = false; //MessageBox.Show("Could not connect to selected data source."); } if (success) { this.selectedDataSource = db; } else { this.selectedDataSource = null; } } else { this.selectedDataSource = null; } } if (selectedDataSource is IDbDriver) { IDbDriver db = selectedDataSource as IDbDriver; //this.txtDataSource.Text = db.ConnectionString; System.Collections.Generic.List<string> tableNames = db.GetTableNames(); foreach (string tableName in tableNames) { ComboBoxItem newItem=null; if (tableName.EndsWith("$") & (selectedPlugIn.Key=="Epi.Data.Office.ExcelWBFactory, Epi.Data.Office") || (selectedPlugIn.Key == "Epi.Data.Office.Excel2007WBFactory, Epi.Data.Office")) { newItem = new ComboBoxItem(tableName.Remove(tableName.Length - 1), tableName.Remove(tableName.Length - 1), tableName); } else { newItem = new ComboBoxItem(tableName, tableName, tableName); } this.cmbDataTable.Items.Add(newItem); } } else if (selectedDataSource is Project) { Project project = selectedDataSource as Project; //txtDataSource.Text = (selectedDataSource == selectedProject) ? SharedStrings.CURRENT_PROJECT : project.FullName; foreach (string s in project.GetViewNames()) { ComboBoxItem newItem = new ComboBoxItem(s, s, s); this.cmbDataTable.Items.Add(newItem); } } } private void lbxVariables_SelectedIndexChanged(object sender, System.EventArgs e) { //cbxAll.Checked = false; //if no variables are selected, then ALL (*) are requested by default //if AllExcept is checked, require at least one variable to be selected if (lbxVariables.SelectedItems.Count < 1) { cbxAllExcept.Checked = false; cbxAllExcept.Enabled = false; } else { cbxAllExcept.Enabled = true; } //cbxAllExcept.Checked = false; CheckForInputSufficiency(); } private void FileNameChanged(object sender, EventArgs e) { cmbDataTable.SelectedIndex = -1; if (cmbOutputFormat.Text == "Text") { cmbDataTable.Enabled = (cmbOutputFormat.Text != "Text"); } CheckForInputSufficiency(); } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-write.html"); } #endregion //Event Handlers #region Public Methods /// <summary> /// Checks if input is sufficient and Enables control buttons accordingly /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Protected Methods protected override void OnOK() { try { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Collections.Generic.List<string> ProblemVariableList = new System.Collections.Generic.List<string>(); if (cbxAllExcept.Checked) { foreach (string s in lbxVariables.Items) { if (!this.lbxVariables.SelectedItems.Contains(s)) { if (s.IndexOf(' ') == 0) { if (ProblemVariableList.Count == 0) { sb.Append("["); } else { sb.Append(" ,["); } sb.Append(s); sb.Append("] "); ProblemVariableList.Add(s); } } } } else { foreach (string s in lbxVariables.SelectedItems) { if (s.IndexOf(' ') == 0) { if (ProblemVariableList.Count == 0) { sb.Append("["); } else { sb.Append(" ,["); } sb.Append(s); sb.Append("] "); ProblemVariableList.Add(s); } } } if (ProblemVariableList.Count > 0) { Epi.Windows.MsgBox.ShowError(string.Format(SharedStrings.EXPORT_CANNOT_PROCEED_LEADING_TRAILING_SPACES, sb.ToString())); return; } else if (selectedDataSource is IDbDriver) { Type csv = Type.GetType("Epi.Data.Office.CsvFile, Epi.Data.Office"); if (selectedDataSource.GetType().AssemblyQualifiedName == csv.AssemblyQualifiedName) { cmbDataTable.Text = cmbDataTable.Text.Replace('.', '#'); if (!cmbDataTable.Text.Contains("#")) { //cmbDataTable.Text = cmbDataTable.Text + "#txt"; cmbDataTable.Text = cmbDataTable.Text + "#csv"; } } IDbDriver db = selectedDataSource as IDbDriver; if (db.TableExists(((Epi.Windows.Analysis.Dialogs.WriteDialog.ComboBoxItem)(cmbDataTable.SelectedItem)).Value.ToString())) { DataTable temp = db.Select(db.CreateQuery("SELECT COUNT (*) FROM " + ((Epi.Windows.Analysis.Dialogs.WriteDialog.ComboBoxItem)(cmbDataTable.SelectedItem)).Value.ToString())); if (temp.Rows.Count > 0) { int count = (int)temp.Rows[0][0]; if (count > 0) { if (rdbAppend.Checked) { if (MessageBox.Show(string.Format(SharedStrings.EXISTING_TABLE_APPEND, cmbDataTable.Text, count.ToString()), "Existing Table", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No) return; } else { if (MessageBox.Show(string.Format(SharedStrings.EXISTING_TABLE_REPLACE, cmbDataTable.Text, count.ToString()), "Existing Table", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No) return; } } } } } } catch (Exception ex) { // } base.OnOK(); } /// <summary> /// Validates user input /// </summary> /// <returns>true if ErrorMessages.Count is 0; otherwise false</returns> protected override bool ValidateInput() { base.ValidateInput(); //if no variables are selected, assume ALL (*) are requested //if cbxAllExcept is checked, at least one variable must be selected. if (lbxVariables.SelectedItems.Count < 1 && cbxAllExcept.Checked) { ErrorMessages.Add(SharedStrings.NO_VARS_SELECTED); } if (String.IsNullOrEmpty(txtFileName.Text.Trim())) { ErrorMessages.Add(SharedStrings.NO_FILENAME); } //If it's not text it requires a tablename if (cmbOutputFormat.Text != "Text" && String.IsNullOrEmpty(cmbDataTable.Text.Trim())) { ErrorMessages.Add(SharedStrings.NO_TABLE_SELECTED); } return (ErrorMessages.Count == 0); } /// <summary> /// Generates command text /// </summary> protected override void GenerateCommand() { WordBuilder command = new WordBuilder(); command.Append(CommandNames.WRITE); command.Append((rdbReplace.Checked) ? CommandNames.REPLACE : CommandNames.APPEND); if (cmbOutputFormat.Text.ToUpperInvariant() == "TEXT" || cmbOutputFormat.Text.ToUpperInvariant() == "FLAT ASCII FILE") { command.Append("\"TEXT\""); } else { command.Append("\"Epi7\""); } command.Append("{" + txtFileName.Text.Trim() + "}"); command.Append(":"); command.Append(FieldNameNeedsBrackets(cmbDataTable.Text) ? Util.InsertInSquareBrackets(cmbDataTable.Text) : cmbDataTable.Text); if (lbxVariables.SelectedItems.Count < 1) { command.Append(StringLiterals.STAR); } else { if (cbxAllExcept.Checked) { command.Append("* EXCEPT"); } foreach (string s in lbxVariables.SelectedItems) { command.Append(FieldNameNeedsBrackets(s) ? Util.InsertInSquareBrackets(s) : s); } } CommandText = command.ToString(); } #endregion Protected Methods private void FormatChanged(object sender, EventArgs e) { if (cmbOutputFormat.Text.ToLowerInvariant().Contains("server")) { lblDataTable.Text = "Destination Table"; } else if (cmbOutputFormat.Text.ToLowerInvariant().Contains("file")) { lblDataTable.Text = "Destination File"; } else { lblDataTable.Text = "Destination Table"; } txtFileName.Text = string.Empty; cmbDataTable.Text = string.Empty; cmbDataTable.Items.Clear(); SomethingChanged(sender, 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. /****************************************************************************** * 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 AndNotUInt32() { var test = new SimpleBinaryOpTest__AndNotUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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__AndNotUInt32 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int Op2ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static SimpleBinaryOpTest__AndNotUInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AndNotUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.AndNot( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.AndNot( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.AndNot( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_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.AndNot), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndNotUInt32(); var result = Avx2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.AndNot(_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<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, 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 = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if ((uint)(~left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(~left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
//------------------------------------------------------------------------------ // <copyright file="Allocator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // </copyright> //------------------------------------------------------------------------------ using System; using System.Buffers; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Microsoft.Azure.Kinect.Sensor.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f54d726c53826f259c2372d3fe68e1a122f58989796aa52500b930ff33cb0e57431b25a780b0d55c45470c8835f7a335425ef6706f9dbcf7046fe6f479d723a51f6c2c9630d986b5cadb47094d5fd6c64cb144736af739fc071cb53c1296d27e38ee99a2ac2329ed141e645b4669b32568a71607c8f7e986418825f2d37c48cf")] namespace Microsoft.Azure.Kinect.Sensor { /// <summary> /// Manages buffer allocation. /// </summary> internal class Allocator { // Objects we are tracking for disposal prior to CLR shutdown private readonly HashSet<WeakReference<IDisposable>> disposables = new HashSet<WeakReference<IDisposable>>(); // Allocations made by the managed code for the native library private readonly SortedDictionary<long, AllocationContext> allocations = new SortedDictionary<long, AllocationContext>(); // A recyclable large array pool to prevent unnecessary managed allocations and clearing of memory private readonly ArrayPool<byte> pool = new LargeArrayPool(); // Managed buffers used as caches for the native memory. private readonly Dictionary<IntPtr, BufferCacheEntry> bufferCache = new Dictionary<IntPtr, BufferCacheEntry>(); // Native delegates private readonly NativeMethods.k4a_memory_allocate_cb_t allocateDelegate; private readonly NativeMethods.k4a_memory_destroy_cb_t freeDelegate; // Native allocator hook state private bool hooked = false; // This is set when the CLR is shutting down, causing an exception during // any new object registrations. private bool noMoreDisposalRegistrations = false; private Allocator() { this.allocateDelegate = new NativeMethods.k4a_memory_allocate_cb_t(this.AllocateFunction); this.freeDelegate = new NativeMethods.k4a_memory_destroy_cb_t(this.FreeFunction); // Register for ProcessExit and DomainUnload to allow us to unhook the native layer before // native to managed callbacks are no longer allowed. AppDomain.CurrentDomain.DomainUnload += this.ApplicationExit; AppDomain.CurrentDomain.ProcessExit += this.ApplicationExit; // Default to the safe and performant configuration // Use Managed Allocator will cause the native layer to allocate from managed byte[] arrays when possible // these can then be safely referenced with a Memory<T> and exposed to user code. This should have fairly // minimal performance impact, but provides strong memory safety. this.UseManagedAllocator = true; // When managed code needs to provide access to memory that didn't originate from the managed allocator // the SafeCopyNativeBuffers options causes the managed code to make a safe cache copy of the native buffer // in a managed byte[] array. This has a more significant performance impact, but generally is only needed for // media foundation (color image) or potentially custom buffers. When set to true, the Memory<T> objects are safe // copies of the native buffers. When set to false, the Memory<T> objects are direct pointers to the native buffers // and can therefore cause native memory corruption if a Memory<T> (or Span<T>) is used after the Image is disposed // or garbage collected. this.SafeCopyNativeBuffers = true; } /// <summary> /// Gets the Allocator. /// </summary> public static Allocator Singleton { get; } = new Allocator(); /// <summary> /// Gets or sets a value indicating whether to have the native library use the managed allocator. /// </summary> public bool UseManagedAllocator { get => this.hooked; set { lock (this) { if (value && !this.hooked) { try { AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_set_allocator(this.allocateDelegate, this.freeDelegate)); this.hooked = true; } catch (Exception) { // Don't fail if we can't set the allocator since this code path is called during the global type // initialization. A failure to set the allocator is also not fatal, but will only cause a performance // issue. System.Diagnostics.Debug.WriteLine("Unable to hook native allocator"); } } if (!value && this.hooked) { // Disabling the hook once it has been enabled should not catch the exception AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_set_allocator(null, null)); this.hooked = false; } } } } /// <summary> /// Gets or sets a value indicating whether to make a safe copy of native buffers. /// </summary> public bool SafeCopyNativeBuffers { get; set; } = true; /// <summary> /// Register the object for disposal when the CLR shuts down. /// </summary> /// <param name="disposable">Object to dispose before native hooks are disconnected.</param> /// <remarks> /// When the CLR shuts down, native callbacks in to the CLR result in an application crash. The allocator free method /// is a native callback to the managed layer that is called whenever the hooked native API needs to free memory. /// /// To avoid this callback after the CLR shuts down, the native library must be completely cleaned up prior CLR shutdown. /// /// Any object that may hold references to the native library (and will therefore generate native to manged callbacks when it /// gets cleaned up) should register with the RegisterForDisposal method to ensure it is cleaned up in the correct order. /// during shutdown. /// </remarks> public void RegisterForDisposal(IDisposable disposable) { lock (this) { if (this.noMoreDisposalRegistrations) { throw new InvalidOperationException("New objects may not be registered during shutdown."); } // Track the object as one we may need to dispose during shutdown. // Use a weak reference to allow the object to be garbage collected earlier if possible. _ = this.disposables.Add(new WeakReference<IDisposable>(disposable)); } } /// <summary> /// Unregister the object for disposal. /// </summary> /// <param name="disposable">Object to unregister.</param> /// <remarks> /// This does not unhook the native allocator, but only unregisters the object for /// disposal. /// </remarks> public void UnregisterForDisposal(IDisposable disposable) { lock (this) { // Remove the object and clean up any dead weak references. _ = this.disposables.RemoveWhere((r) => { bool alive = r.TryGetTarget(out IDisposable target); return !alive || target == disposable; }); } } /// <summary> /// Get a Memory reference to the managed memory that was used by the hooked native /// allocator. /// </summary> /// <param name="address">Native address of the memory.</param> /// <param name="size">Size of the memory region.</param> /// <returns>Reference to the memory, or an empty memory reference.</returns> /// <remarks> /// If the address originally came from a managed array that was provided to the native /// API through the allocator hook, this function will return a Memory reference to the managed /// memory. Since this is a reference to the managed memory and not the native pointer, it /// is safe and not subject to use after free bugs. /// /// The address and size do not need to reference the exact pointer provided to the native layer /// by the allocator, but can refer to any region in the allocated memory. /// </remarks> public Memory<byte> GetManagedAllocatedMemory(IntPtr address, long size) { lock (this) { AllocationContext allocation = this.FindNearestContext(address); if (allocation == null) { return null; } long offset = (long)address - (long)allocation.BufferAddress; // Check that the beginning of the memory is in this allocation if (offset > allocation.Buffer.LongLength) { return null; } // Check that the end of the memory is in this allocation if (checked(offset + size) > allocation.Buffer.LongLength) { return null; } // Return a reference to this memory return new Memory<byte>(allocation.Buffer, checked((int)offset), checked((int)size)); } } /// <summary> /// Get a managed array to cache the contents of a native buffer. /// </summary> /// <param name="nativeAddress">Native buffer to mirror.</param> /// <param name="size">Size of the native memory.</param> /// <returns>A managed array populated with the content of the native buffer.</returns> /// <remarks>Multiple callers asking for the same address will get the same buffer. /// When done with the buffer the caller must call <seealso cref="ReturnBufferCache(IntPtr)"/>. /// </remarks> public byte[] GetBufferCache(IntPtr nativeAddress, int size) { BufferCacheEntry entry; lock (this) { if (this.bufferCache.ContainsKey(nativeAddress)) { entry = this.bufferCache[nativeAddress]; entry.ReferenceCount++; if (entry.UsedSize != size) { throw new AzureKinectException("Multiple image buffers sharing the same address cannot have the same size"); } } else { entry = new BufferCacheEntry { ManagedBufferCache = this.pool.Rent(size), UsedSize = size, ReferenceCount = 1, Initialized = false, }; this.bufferCache.Add(nativeAddress, entry); } } lock (entry) { if (!entry.Initialized) { Marshal.Copy(nativeAddress, entry.ManagedBufferCache, 0, entry.UsedSize); entry.Initialized = true; } } return entry.ManagedBufferCache; } /// <summary> /// Return the buffer cache. /// </summary> /// <param name="nativeAddress">Address of the native buffer.</param> /// <remarks>Must be called exactly once for each buffer provided by <see cref="GetBufferCache(IntPtr, int)"/>.</remarks> public void ReturnBufferCache(IntPtr nativeAddress) { lock (this) { BufferCacheEntry entry = this.bufferCache[nativeAddress]; entry.ReferenceCount--; if (entry.ReferenceCount == 0) { this.pool.Return(entry.ManagedBufferCache); _ = this.bufferCache.Remove(nativeAddress); } } } // Find the allocation context who's address is closest but not // greater than the search address private AllocationContext FindNearestContext(IntPtr address) { lock (this) { long[] keys = new long[this.allocations.Count]; this.allocations.Keys.CopyTo(keys, 0); int searchIndex = Array.BinarySearch(keys, (long)address); if (searchIndex >= 0) { return this.allocations[keys[searchIndex]]; } else { int nextLowestIndex = ~searchIndex - 1; if (nextLowestIndex < 0) { return null; } AllocationContext allocation = this.allocations[keys[nextLowestIndex]]; return allocation; } } } // This function is called by the native layer to allocate memory private IntPtr AllocateFunction(int size, out IntPtr context) { byte[] buffer = this.pool.Rent(size); AllocationContext allocationContext = new AllocationContext() { Buffer = buffer, BufferPin = GCHandle.Alloc(buffer, GCHandleType.Pinned), CallbackDelegate = this.freeDelegate, }; allocationContext.BufferAddress = allocationContext.BufferPin.AddrOfPinnedObject(); context = (IntPtr)GCHandle.Alloc(allocationContext); lock (this) { this.allocations.Add((long)allocationContext.BufferAddress, allocationContext); } return allocationContext.BufferAddress; } // This function is called by the native layer to free memory private void FreeFunction(IntPtr buffer, IntPtr context) { GCHandle contextPin = (GCHandle)context; AllocationContext allocationContext = (AllocationContext)contextPin.Target; lock (this) { System.Diagnostics.Debug.Assert(object.ReferenceEquals(this.allocations[(long)buffer], allocationContext), "Allocation context does not match expected value"); _ = this.allocations.Remove((long)buffer); } allocationContext.BufferPin.Free(); this.pool.Return(allocationContext.Buffer); contextPin.Free(); } // Called when the AppDomain is unloaded or the application exits private void ApplicationExit(object sender, EventArgs e) { lock (this) { // Disable the managed allocator hook to ensure no new allocations this.UseManagedAllocator = false; // Prevent more disposal registrations while we are cleaning up this.noMoreDisposalRegistrations = true; System.Diagnostics.Debug.WriteLine($"Disposable count {this.disposables.Count} (Allocation Count {this.allocations.Count})"); // First dispose of all the registered objects // Don't dispose of the objects during this loop since a // side effect of disposing of an object may be the object unregistering itself // and causing the collection to be modified. List<IDisposable> disposeList = new List<IDisposable>(); foreach (WeakReference<IDisposable> r in this.disposables) { if (r.TryGetTarget(out IDisposable disposable)) { disposeList.Add(disposable); } } this.disposables.Clear(); foreach (IDisposable disposable in disposeList) { System.Diagnostics.Debug.WriteLine($"Disposed {disposable.GetType().FullName} (Allocation Count {this.allocations.Count})"); disposable.Dispose(); } // If the allocation count is not zero, we will be called again with a free function // if this happens after the CLR has entered shutdown, the CLR will generate an exception. if (this.allocations.Count > 0) { throw new AzureKinectException("Not all native allocations have been freed before managed shutdown"); } } } private class AllocationContext { public byte[] Buffer { get; set; } public IntPtr BufferAddress { get; set; } public GCHandle BufferPin { get; set; } public NativeMethods.k4a_memory_destroy_cb_t CallbackDelegate { get; set; } } private class BufferCacheEntry { public byte[] ManagedBufferCache { get; set; } public int UsedSize { get; set; } public int ReferenceCount { get; set; } public bool Initialized { get; set; } } } }
using System; using System.Diagnostics; using System.Fabric; using System.Fabric.Query; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace Fabrilicious.Servilicious { [RoutePrefix("api/fabric")] public class FabricController : ApiController { [HttpGet] [Route("nodes")] public async Task<IHttpActionResult> GetNodes() { try { var client = new FabricClient(); var list = await client.QueryManager.GetNodeListAsync(); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("applicationTypes")] public async Task<IHttpActionResult> GetApplicationTypes() { try { var client = new FabricClient(); var list = await client.QueryManager.GetApplicationTypeListAsync(); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("applications")] public async Task<IHttpActionResult> GetApplications() { try { var client = new FabricClient(); var list = await client.QueryManager.GetApplicationListAsync(); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("serviceTypes/{applicationTypeName}/{applicationTypeVersion}")] public async Task<IHttpActionResult> GetServiceTypes(string applicationTypeName, string applicationTypeVersion) { try { var client = new FabricClient(); var list = await client.QueryManager.GetServiceTypeListAsync(applicationTypeName, applicationTypeVersion); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("services/{*applicationName}")] public async Task<IHttpActionResult> GetServices(string applicationName) { try { var client = new FabricClient(); var list = await client.QueryManager.GetServiceListAsync(new Uri(applicationName)); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("partitions/{*serviceName}")] public async Task<IHttpActionResult> GetPartitions(string serviceName) { try { var client = new FabricClient(); var list = await client.QueryManager.GetPartitionListAsync(new Uri(serviceName)); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("replicas/{partitionId}")] public async Task<IHttpActionResult> GetReplicas(Guid partitionId) { try { var client = new FabricClient(); var list = await client.QueryManager.GetReplicaListAsync(partitionId); return Ok(list); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } [HttpGet] [Route("details")] public async Task<IHttpActionResult> GetDetails() { try { var client = new FabricClient(); var nodes = (await client.QueryManager.GetNodeListAsync()) .Select(async n => { try { var applications = (await client.QueryManager.GetDeployedApplicationListAsync(n.NodeName)) .Select(async a => { var replicas = await client.QueryManager.GetDeployedReplicaListAsync(n.NodeName, a.ApplicationName); var groupedReplicas = replicas.GroupBy(r => r.ServiceName, (k, items) => new { ServiceName = k, Replicas = items.Select(i => { var replica = i as DeployedStatefulServiceReplica; if (replica != null) { return new { PartitionId = replica.Partitionid, replica.ServiceKind, Role = replica.ReplicaRole.ToString(), InstanceId = replica.ReplicaId, replica.ReplicaStatus }; } var instance = i as DeployedStatelessServiceInstance; if (instance != null) { return new { PartitionId = instance.Partitionid, instance.ServiceKind, Role = string.Empty, InstanceId = instance.InstanceId, instance.ReplicaStatus }; } return null; }) }) .ToList(); return new { a.ApplicationName, a.ApplicationTypeName, a.DeployedApplicationStatus, //Services = await Task.WhenAll(services), Services = groupedReplicas, }; }); return new { n.NodeName, n.NodeStatus, n.HealthState, Applications = await Task.WhenAll(applications) }; } catch (Exception e) { return null; } }) .ToList(); return Ok((await Task.WhenAll(nodes)).Where(n => n != null).OrderBy(n => n.NodeName)); } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } } }
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; using NSubstitute; using Octokit; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Create(null)); await AssertEx.Throws<ArgumentException>(async () => await client.Create(new NewRepository { Name = null })); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository { Name = "aName" }); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository { Name = "aName" }; client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Owner); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository { Name = "aName", Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>( async () => await client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Create(null, new NewRepository { Name = "aName" })); await AssertEx.Throws<ArgumentException>(async () => await client.Create("aLogin", null)); await AssertEx.Throws<ArgumentException>(async () => await client.Create("aLogin", new NewRepository { Name = null })); } [Fact] public async Task UsesTheOrganizatinosReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository { Name = "aName" }); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository { Name = "aName" }; await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Owner); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<ApiValidationException>( async () => await client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository { Name = "aName" }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<RepositoryExistsException>( async () => await client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Delete(null, "aRepoName")); await AssertEx.Throws<ArgumentNullException>(async () => await client.Delete("anOwner", null)); } [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("theOwner", "theRepoName"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName")); } } public class TheGetMethod { [Fact] public void RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Get("fake", "repo"); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo"), null); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await AssertEx.Throws<ArgumentNullException>(async () => await client.Get(null, "name")); await AssertEx.Throws<ArgumentNullException>(async () => await client.Get("owner", null)); } } public class TheGetAllForCurrentMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos")); } } public class TheGetAllForUserMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos")); } [Fact] public void EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); } } public class TheGetAllForOrgMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsOrganizations() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos")); } [Fact] public void EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); } } public class TheGetReadmeMethod { [Fact] public async Task ReturnsReadme() { string encodedContent = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello world")); var readmeInfo = new ReadmeResponse { Content = encodedContent, Encoding = "base64", Name = "README.md", Url = "https://github.example.com/readme.md", HtmlUrl = "https://github.example.com/readme" }; var connection = Substitute.For<IApiConnection>(); connection.Get<ReadmeResponse>(Args.Uri, null).Returns(Task.FromResult(readmeInfo)); connection.GetHtml(Args.Uri, null).Returns(Task.FromResult("<html>README</html>")); var reposEndpoint = new RepositoriesClient(connection); var readme = await reposEndpoint.GetReadme("fake", "repo"); Assert.Equal("README.md", readme.Name); connection.Received().Get<ReadmeResponse>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/readme"), null); connection.DidNotReceive().GetHtml(Arg.Is<Uri>(u => u.ToString() == "https://github.example.com/readme"), null); var htmlReadme = await readme.GetHtmlContent(); Assert.Equal("<html>README</html>", htmlReadme); connection.Received().GetHtml(Arg.Is<Uri>(u => u.ToString() == "https://github.example.com/readme"), null); } } public class TheGetReadmeHtmlMethod { [Fact] public async Task ReturnsReadmeHtml() { var connection = Substitute.For<IApiConnection>(); connection.GetHtml(Args.Uri, null).Returns(Task.FromResult("<html>README</html>")); var reposEndpoint = new RepositoriesClient(connection); var readme = await reposEndpoint.GetReadmeHtml("fake", "repo"); connection.Received().GetHtml(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/readme"), null); Assert.Equal("<html>README</html>", readme); } } public class TheGetAllBranchesMethod { [Fact] public void ReturnsBranches() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches")); } [Fact] public void EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllBranches(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllBranches("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllBranches("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllBranches("owner", "")); } } public class TheGetAllContributorsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllContributors("owner", "name"); connection.Received() .GetAll<User>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>()); } [Fact] public void EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllContributors("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllContributors("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllContributors("owner", "")); } } public class TheGetAllLanguagesMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<IDictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages"), null); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllLanguages("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams")); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllTeams("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllTeams("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllTeams("owner", "")); } } public class TheGetAllTagsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags")); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetAllTags(null, "repo")); Assert.Throws<ArgumentNullException>(() => client.GetAllTags("owner", null)); Assert.Throws<ArgumentException>(() => client.GetAllTags("", "repo")); Assert.Throws<ArgumentException>(() => client.GetAllTags("owner", "")); } } public class TheGetBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); Assert.Throws<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); Assert.Throws<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); Assert.Throws<ArgumentException>(() => client.GetBranch("", "repo", "branch")); Assert.Throws<ArgumentException>(() => client.GetBranch("owner", "", "branch")); Assert.Throws<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>()); } [Fact] public void EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); Assert.Throws<ArgumentNullException>(() => client.Edit(null, "repo", update)); Assert.Throws<ArgumentNullException>(() => client.Edit("owner", null, update)); Assert.Throws<ArgumentNullException>(() => client.Edit("owner", "repo", null)); Assert.Throws<ArgumentException>(() => client.Edit("", "repo", update)); Assert.Throws<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public void EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.Throws<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); Assert.Throws<ArgumentException>(() => client.Compare("", "repo", "base", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); Assert.Throws<ArgumentException>(() => client.Compare("owner", "", "base", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); Assert.Throws<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); Assert.Throws<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); Assert.Throws<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head"), null); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch"), null); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class ToLookupTests { [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x * 2); Assert.All(lookup, group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2); Assert.All(lookup, group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_ElementSelector(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x * 2, new ModularCongruenceComparer(count * 2)); Assert.All(lookup, group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2, new ModularCongruenceComparer(count)); Assert.All(lookup, group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); }); seen.AssertComplete(); if (count < 1) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_ElementSelector_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x % 2); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x % 2, y => -y); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_ElementSelector(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x, new ModularCongruenceComparer(2)); Assert.All(lookup, group => { seenOuter.Add(group.Key % 2); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key % 2, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); if (count < 2) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x, y => -y, new ModularCongruenceComparer(2)); Assert.All(lookup, group => { seenOuter.Add(group.Key % 2); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key % 2, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); if (count < 2) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 4, 1024 * 128 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_ElementSelector_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, EqualityComparer<int>.Default)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, y => y)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToLookup(x => x, y => y, EqualityComparer<int>.Default)); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void ToLookup_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, new FailingEqualityComparer<int>())); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, y => y, new FailingEqualityComparer<int>())); } [Fact] public static void ToLookup_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null, EqualityComparer<int>.Default)); } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Attribute : Node, INodeWithArguments { protected string _name; protected ExpressionCollection _arguments; protected ExpressionPairCollection _namedArguments; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Attribute CloneNode() { return (Attribute)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Attribute CleanClone() { return (Attribute)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Attribute; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnAttribute(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Attribute)node; if (_name != other._name) return NoMatch("Attribute._name"); if (!Node.AllMatch(_arguments, other._arguments)) return NoMatch("Attribute._arguments"); if (!Node.AllMatch(_namedArguments, other._namedArguments)) return NoMatch("Attribute._namedArguments"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_arguments != null) { Expression item = existing as Expression; if (null != item) { Expression newItem = (Expression)newNode; if (_arguments.Replace(item, newItem)) { return true; } } } if (_namedArguments != null) { ExpressionPair item = existing as ExpressionPair; if (null != item) { ExpressionPair newItem = (ExpressionPair)newNode; if (_namedArguments.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Attribute clone = (Attribute)FormatterServices.GetUninitializedObject(typeof(Attribute)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._name = _name; if (null != _arguments) { clone._arguments = _arguments.Clone() as ExpressionCollection; clone._arguments.InitializeParent(clone); } if (null != _namedArguments) { clone._namedArguments = _namedArguments.Clone() as ExpressionPairCollection; clone._namedArguments.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _arguments) { _arguments.ClearTypeSystemBindings(); } if (null != _namedArguments) { _namedArguments.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlAttribute] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public string Name { get { return _name; } set { _name = value; } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Expression))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ExpressionCollection Arguments { get { return _arguments ?? (_arguments = new ExpressionCollection(this)); } set { if (_arguments != value) { _arguments = value; if (null != _arguments) { _arguments.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(ExpressionPair))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ExpressionPairCollection NamedArguments { get { return _namedArguments ?? (_namedArguments = new ExpressionPairCollection(this)); } set { if (_namedArguments != value) { _namedArguments = value; if (null != _namedArguments) { _namedArguments.InitializeParent(this); } } } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Common; #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.IO; using NLog.Config; /// <summary> /// Writes log messages to the console with customizable coloring. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso> [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See http://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default.In multithreaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private static readonly IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules = new List<ConsoleRowHighlightingRule>() { new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.Red, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.Magenta, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.White, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.DarkGray, ConsoleOutputColor.NoChange), }; /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public ColoredConsoleTarget() { WordHighlightingRules = new List<ConsoleWordHighlightingRule>(); RowHighlightingRules = new List<ConsoleRowHighlightingRule>(); UseDefaultRowHighlightingRules = true; _pauseLogging = false; DetectConsoleAvailable = false; OptimizeBufferReuse = true; } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ColoredConsoleTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout). /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool ErrorStream { get; set; } /// <summary> /// Gets or sets a value indicating whether to use default row highlighting rules. /// </summary> /// <remarks> /// The default rules are: /// <table> /// <tr> /// <th>Condition</th> /// <th>Foreground Color</th> /// <th>Background Color</th> /// </tr> /// <tr> /// <td>level == LogLevel.Fatal</td> /// <td>Red</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Error</td> /// <td>Yellow</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Warn</td> /// <td>Magenta</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Info</td> /// <td>White</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Debug</td> /// <td>Gray</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Trace</td> /// <td>DarkGray</td> /// <td>NoChange</td> /// </tr> /// </table> /// </remarks> /// <docgen category='Highlighting Rules' order='9' /> [DefaultValue(true)] public bool UseDefaultRowHighlightingRules { get; set; } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> /// <docgen category='Console Options' order='10' /> public Encoding Encoding { get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging); set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging)) _encoding = value; } } private Encoding _encoding; #endif /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available. /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets the row highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; } /// <summary> /// Gets the word highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='11' /> [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { _pauseLogging = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason); } } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ if (_encoding != null && !_pauseLogging) Console.OutputEncoding = _encoding; #endif base.InitializeTarget(); if (Header != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Header, lei)); } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { if (Footer != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Footer, lei)); } base.CloseTarget(); } /// <summary> /// Writes the specified log event to the console highlighting entries /// and words based on a set of defined rules. /// </summary> /// <param name="logEvent">Log event.</param> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance return; } WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent)); } private void WriteToOutput(LogEventInfo logEvent, string message) { ConsoleColor oldForegroundColor = Console.ForegroundColor; ConsoleColor oldBackgroundColor = Console.BackgroundColor; bool didChangeForegroundColor = false, didChangeBackgroundColor = false; try { var matchingRule = GetMatchingRowHighlightingRule(logEvent); didChangeForegroundColor = IsColorChange(matchingRule.ForegroundColor, oldForegroundColor); if (didChangeForegroundColor) Console.ForegroundColor = (ConsoleColor)matchingRule.ForegroundColor; didChangeBackgroundColor = IsColorChange(matchingRule.BackgroundColor, oldBackgroundColor); if (didChangeBackgroundColor) Console.BackgroundColor = (ConsoleColor)matchingRule.BackgroundColor; try { var consoleStream = ErrorStream ? Console.Error : Console.Out; if (WordHighlightingRules.Count == 0) { consoleStream.WriteLine(message); } else { message = message.Replace("\a", "\a\a"); foreach (ConsoleWordHighlightingRule hl in WordHighlightingRules) { message = hl.ReplaceWithEscapeSequences(message); } ColorizeEscapeSequences(consoleStream, message, new ColorPair(Console.ForegroundColor, Console.BackgroundColor), new ColorPair(oldForegroundColor, oldBackgroundColor)); consoleStream.WriteLine(); didChangeForegroundColor = didChangeBackgroundColor = true; } } catch (IndexOutOfRangeException ex) { // This is a bug and will therefore stop the logging. For docs, see the PauseLogging property. _pauseLogging = true; InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } catch (ArgumentOutOfRangeException ex) { // This is a bug and will therefore stop the logging. For docs, see the PauseLogging property. _pauseLogging = true; InternalLogger.Warn(ex, "An ArgumentOutOfRangeException has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets"); } } finally { if (didChangeForegroundColor) Console.ForegroundColor = oldForegroundColor; if (didChangeBackgroundColor) Console.BackgroundColor = oldBackgroundColor; } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { foreach (ConsoleRowHighlightingRule rule in RowHighlightingRules) { if (rule.CheckCondition(logEvent)) return rule; } if (UseDefaultRowHighlightingRules) { foreach (ConsoleRowHighlightingRule rule in DefaultConsoleRowHighlightingRules) { if (rule.CheckCondition(logEvent)) return rule; } } return ConsoleRowHighlightingRule.Default; } private static bool IsColorChange(ConsoleOutputColor targetColor, ConsoleColor oldColor) { return (targetColor != ConsoleOutputColor.NoChange) && ((ConsoleColor)targetColor != oldColor); } private static void ColorizeEscapeSequences( TextWriter output, string message, ColorPair startingColor, ColorPair defaultColor) { var colorStack = new Stack<ColorPair>(); colorStack.Push(startingColor); int p0 = 0; while (p0 < message.Length) { int p1 = p0; while (p1 < message.Length && message[p1] >= 32) { p1++; } // text if (p1 != p0) { output.Write(message.Substring(p0, p1 - p0)); } if (p1 >= message.Length) { p0 = p1; break; } // control characters char c1 = message[p1]; char c2 = (char)0; if (p1 + 1 < message.Length) { c2 = message[p1 + 1]; } if (c1 == '\a' && c2 == '\a') { output.Write('\a'); p0 = p1 + 2; continue; } if (c1 == '\r' || c1 == '\n') { Console.ForegroundColor = defaultColor.ForegroundColor; Console.BackgroundColor = defaultColor.BackgroundColor; output.Write(c1); Console.ForegroundColor = colorStack.Peek().ForegroundColor; Console.BackgroundColor = colorStack.Peek().BackgroundColor; p0 = p1 + 1; continue; } if (c1 == '\a') { if (c2 == 'X') { colorStack.Pop(); Console.ForegroundColor = colorStack.Peek().ForegroundColor; Console.BackgroundColor = colorStack.Peek().BackgroundColor; p0 = p1 + 2; continue; } var foreground = (ConsoleOutputColor)(c2 - 'A'); var background = (ConsoleOutputColor)(message[p1 + 2] - 'A'); if (foreground != ConsoleOutputColor.NoChange) { Console.ForegroundColor = (ConsoleColor)foreground; } if (background != ConsoleOutputColor.NoChange) { Console.BackgroundColor = (ConsoleColor)background; } colorStack.Push(new ColorPair(Console.ForegroundColor, Console.BackgroundColor)); p0 = p1 + 3; continue; } output.Write(c1); p0 = p1 + 1; } if (p0 < message.Length) { output.Write(message.Substring(p0)); } } /// <summary> /// Color pair (foreground and background). /// </summary> internal struct ColorPair { private readonly ConsoleColor _foregroundColor; private readonly ConsoleColor _backgroundColor; internal ColorPair(ConsoleColor foregroundColor, ConsoleColor backgroundColor) { _foregroundColor = foregroundColor; _backgroundColor = backgroundColor; } internal ConsoleColor BackgroundColor => _backgroundColor; internal ConsoleColor ForegroundColor => _foregroundColor; } } } #endif
/* * 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 QuantConnect.Data.Market; using QuantConnect.Securities; namespace QuantConnect.Orders.Fills { /// <summary> /// Represents the default fill model used to simulate order fills /// </summary> public class ImmediateFillModel : IFillModel { /// <summary> /// Default market fill model for the base security class. Fills at the last traded price. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="SecurityTransactionModel.StopMarketFill"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent MarketFill(Security asset, MarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //Order [fill]price for a market order model is the current security price fill.FillPrice = GetPrices(asset, order.Direction).Current; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop fill model implementation in base class security. (Stop Market Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="MarketFill(Security, MarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (prices.Low < order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at lowest of the stop & asset price. fill.FillPrice = Math.Min(order.StopPrice, prices.Current - slip); } break; case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (prices.High > order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at highest of the stop & asset price. fill.FillPrice = Math.Max(order.StopPrice, prices.Current + slip); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop limit fill model implementation in base class security. (Stop Limit Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> /// <remarks> /// There is no good way to model limit orders with OHLC because we never know whether the market has /// gapped past our fill price. We have to make the assumption of a fluid, high volume market. /// /// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption /// was made the limit fill will be done with closing price of the bar after the stop has been triggered.. /// </remarks> public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (prices.High > order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using closing price of bar: // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price < order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; } } break; case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (prices.Low < order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using minimum price of the bar // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price > order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; // Fill at limit price not asset price. } } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default limit order fill model in the base security class. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="MarketFill(Security, MarketOrder)"/> public virtual OrderEvent LimitFill(Security asset, LimitOrder order) { //Initialise; var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //-> Valid Live/Model Order: switch (order.Direction) { case OrderDirection.Buy: //Buy limit seeks lowest price if (prices.Low < order.LimitPrice) { //Set order fill: fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Min(prices.High, order.LimitPrice); } break; case OrderDirection.Sell: //Sell limit seeks highest price possible if (prices.High > order.LimitPrice) { fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Max(prices.Low, order.LimitPrice); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Open Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // MOO should never fill on the same bar or on stale data // Imagine the case where we have a thinly traded equity, ASUR, and another liquid // equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe // have large gaps, in which case the currentBar.EndTime will be in the past // ASUR | | | [order] | | | | | | | // SPY | | | | | | | | | | | | | | | | | | | | var currentBar = asset.GetLastData(); var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); if (currentBar == null || localOrderTime >= currentBar.EndTime) return fill; // if the MOO was submitted during market the previous day, wait for a day to turn over if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == asset.LocalTime.Date) { return fill; } // wait until market open // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; fill.FillPrice = GetPrices(asset, order.Direction).Open; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Close Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false); // wait until market closes after the order time if (asset.LocalTime < nextMarketClose) { return fill; } fill.FillPrice = GetPrices(asset, order.Direction).Close; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Get the minimum and maximum price for this security in the last bar: /// </summary> /// <param name="asset">Security asset we're checking</param> /// <param name="direction">The order direction, decides whether to pick bid or ask</param> private Prices GetPrices(Security asset, OrderDirection direction) { var low = asset.Low; var high = asset.High; var open = asset.Open; var close = asset.Close; var current = asset.Price; if (direction == OrderDirection.Hold) { return new Prices(current, open, high, low, close); } var tick = asset.Cache.GetData<Tick>(); if (tick != null) { return new Prices(current, open, high, low, close); } var quoteBar = asset.Cache.GetData<QuoteBar>(); if (quoteBar != null) { var bar = direction == OrderDirection.Sell ? quoteBar.Bid : quoteBar.Ask; if (bar != null) { return new Prices(bar); } } var tradeBar = asset.Cache.GetData<TradeBar>(); if (tradeBar != null) { return new Prices(tradeBar); } var lastData = asset.GetLastData(); var lastBar = lastData as IBar; if (lastBar != null) { return new Prices(lastBar); } return new Prices(current, open, high, low, close); } /// <summary> /// Determines if the exchange is open using the current time of the asset /// </summary> private static bool IsExchangeOpen(Security asset) { if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime)) { // if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days) var currentBar = asset.GetLastData(); if (asset.LocalTime.Date != currentBar.EndTime.Date || !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, false)) { return false; } } return true; } private class Prices { public readonly decimal Current; public readonly decimal Open; public readonly decimal High; public readonly decimal Low; public readonly decimal Close; public Prices(IBar bar) : this(bar.Close, bar.Open, bar.High, bar.Low, bar.Close) { } public Prices(decimal current, decimal open, decimal high, decimal low, decimal close) { Current = current; Open = open == 0 ? current : open; High = high == 0 ? current : high; Low = low == 0 ? current : low; Close = close == 0 ? current : close; } } } }
// Copyright (C) Josh Smith - January 2007 using System; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace Hawk.Core.Utils { #region ListViewDragDropManager public class DragDropInfo { public object Control { get; private set; } public DragDropInfo(object control) { this.Control = control; } } /// <summary> /// Manages the dragging and dropping of ListViewItems in a ListView. /// The ItemType type parameter indicates the type of the objects in /// the ListView's items source. The ListView's ItemsSource must be /// set to an instance of ObservableCollection of ItemType, or an /// Exception will be thrown. /// </summary> /// <typeparam name="ItemType">The type of the ListView's items.</typeparam> public class ListViewDragDropManager<ItemType> where ItemType : class { #region Data bool canInitiateDrag; DragAdorner dragAdorner; double dragAdornerOpacity; int indexToSelect; bool isDragInProgress; ItemType itemUnderDragCursor; ListView listView; Point ptMouseDown; bool showDragAdorner; #endregion // Data #region Constructors /// <summary> /// Initializes a new instance of ListViewDragManager. /// </summary> public ListViewDragDropManager() { this.canInitiateDrag = false; this.dragAdornerOpacity = 0.7; this.indexToSelect = -1; this.showDragAdorner = true; } /// <summary> /// Initializes a new instance of ListViewDragManager. /// </summary> /// <param name="listView"></param> public ListViewDragDropManager( ListView listView ) : this() { this.ListView = listView; } /// <summary> /// Initializes a new instance of ListViewDragManager. /// </summary> /// <param name="listView"></param> /// <param name="dragAdornerOpacity"></param> public ListViewDragDropManager( ListView listView, double dragAdornerOpacity ) : this( listView ) { this.DragAdornerOpacity = dragAdornerOpacity; } /// <summary> /// Initializes a new instance of ListViewDragManager. /// </summary> /// <param name="listView"></param> /// <param name="showDragAdorner"></param> public ListViewDragDropManager( ListView listView, bool showDragAdorner ) : this( listView ) { this.ShowDragAdorner = showDragAdorner; } #endregion // Constructors #region Public Interface #region DragAdornerOpacity /// <summary> /// Gets/sets the opacity of the drag adorner. This property has no /// effect if ShowDragAdorner is false. The default value is 0.7 /// </summary> public double DragAdornerOpacity { get { return this.dragAdornerOpacity; } set { if( this.IsDragInProgress ) throw new InvalidOperationException( "Cannot set the DragAdornerOpacity property during a drag operation." ); if( value < 0.0 || value > 1.0 ) throw new ArgumentOutOfRangeException( "DragAdornerOpacity", value, "Must be between 0 and 1." ); this.dragAdornerOpacity = value; } } #endregion // DragAdornerOpacity #region IsDragInProgress /// <summary> /// Returns true if there is currently a drag operation being managed. /// </summary> public bool IsDragInProgress { get { return this.isDragInProgress; } private set { this.isDragInProgress = value; } } #endregion // IsDragInProgress #region ListView /// <summary> /// Gets/sets the ListView whose dragging is managed. This property /// can be set to null, to prevent drag management from occuring. If /// the ListView's AllowDrop property is false, it will be set to true. /// </summary> public ListView ListView { get { return listView; } set { if( this.IsDragInProgress ) throw new InvalidOperationException( "Cannot set the ListView property during a drag operation." ); if( this.listView != null ) { #region Unhook Events this.listView.PreviewMouseLeftButtonDown -= listView_PreviewMouseLeftButtonDown; this.listView.PreviewMouseMove -= listView_PreviewMouseMove; this.listView.DragOver -= listView_DragOver; this.listView.DragLeave -= listView_DragLeave; this.listView.DragEnter -= listView_DragEnter; this.listView.Drop -= listView_Drop; #endregion // Unhook Events } this.listView = value; if( this.listView != null ) { if( !this.listView.AllowDrop ) this.listView.AllowDrop = true; #region Hook Events this.listView.PreviewMouseLeftButtonDown += listView_PreviewMouseLeftButtonDown; this.listView.PreviewMouseMove += listView_PreviewMouseMove; this.listView.DragOver += listView_DragOver; this.listView.DragLeave += listView_DragLeave; this.listView.DragEnter += listView_DragEnter; this.listView.Drop += listView_Drop; #endregion // Hook Events } } } #endregion // ListView #region ProcessDrop [event] /// <summary> /// Raised when a drop occurs. By default the dropped item will be moved /// to the target index. Handle this event if relocating the dropped item /// requires custom behavior. Note, if this event is handled the default /// item dropping logic will not occur. /// </summary> public event EventHandler<ProcessDropEventArgs<ItemType>> ProcessDrop; #endregion // ProcessDrop [event] #region ShowDragAdorner /// <summary> /// Gets/sets whether a visual representation of the ListViewItem being dragged /// follows the mouse cursor during a drag operation. The default value is true. /// </summary> public bool ShowDragAdorner { get { return this.showDragAdorner; } set { if( this.IsDragInProgress ) throw new InvalidOperationException( "Cannot set the ShowDragAdorner property during a drag operation." ); this.showDragAdorner = value; } } #endregion // ShowDragAdorner #endregion // Public Interface #region Event Handling Methods #region listView_PreviewMouseLeftButtonDown void listView_PreviewMouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { if( this.IsMouseOverScrollbar ) { // 4/13/2007 - Set the flag to false when cursor is over scrollbar. this.canInitiateDrag = false; return; } int index = this.IndexUnderDragCursor; this.canInitiateDrag = index > -1; if( this.canInitiateDrag ) { // Remember the location and index of the ListViewItem the user clicked on for later. this.ptMouseDown = MouseUtilities.GetMousePosition( this.listView ); this.indexToSelect = index; } else { this.ptMouseDown = new Point( -10000, -10000 ); this.indexToSelect = -1; } } #endregion // listView_PreviewMouseLeftButtonDown #region listView_PreviewMouseMove void listView_PreviewMouseMove( object sender, MouseEventArgs e ) { if( !this.CanStartDragOperation ) return; // Select the item the user clicked on. if( this.listView.SelectedIndex != this.indexToSelect ) this.listView.SelectedIndex = this.indexToSelect; // If the item at the selected index is null, there's nothing // we can do, so just return; if( this.listView.SelectedItem == null ) return; ListViewItem itemToDrag = this.GetListViewItem( this.listView.SelectedIndex ); if( itemToDrag == null ) return; AdornerLayer adornerLayer = this.ShowDragAdornerResolved ? this.InitializeAdornerLayer( itemToDrag ) : null; this.InitializeDragOperation( itemToDrag ); this.PerformDragOperation(); this.FinishDragOperation( itemToDrag, adornerLayer ); } #endregion // listView_PreviewMouseMove #region listView_DragOver void listView_DragOver( object sender, DragEventArgs e ) { e.Effects = DragDropEffects.Move; if( this.ShowDragAdornerResolved ) this.UpdateDragAdornerLocation(); // Update the item which is known to be currently under the drag cursor. int index = this.IndexUnderDragCursor; this.ItemUnderDragCursor = index < 0 ? null : this.ListView.Items[index] as ItemType; } #endregion // listView_DragOver #region listView_DragLeave void listView_DragLeave( object sender, DragEventArgs e ) { if( !this.IsMouseOver( this.listView ) ) { if( this.ItemUnderDragCursor != null ) this.ItemUnderDragCursor = null; if( this.dragAdorner != null ) this.dragAdorner.Visibility = Visibility.Collapsed; } } #endregion // listView_DragLeave #region listView_DragEnter void listView_DragEnter( object sender, DragEventArgs e ) { if( this.dragAdorner != null && this.dragAdorner.Visibility != Visibility.Visible ) { // Update the location of the adorner and then show it. this.UpdateDragAdornerLocation(); this.dragAdorner.Visibility = Visibility.Visible; } } #endregion // listView_DragEnter #region listView_Drop void listView_Drop( object sender, DragEventArgs e ) { if( this.ItemUnderDragCursor != null ) this.ItemUnderDragCursor = null; e.Effects = DragDropEffects.None; if( !e.Data.GetDataPresent( typeof( DragDropInfo ) ) ) return; // Get the data object which was dropped. DragDropInfo info = e.Data.GetData( typeof(DragDropInfo) ) as DragDropInfo; var data = info.Control as ItemType; if( data == null ) return; // Get the ObservableCollection<ItemType> which contains the dropped data object. ObservableCollection<ItemType> itemsSource = this.listView.ItemsSource as ObservableCollection<ItemType>; if( itemsSource == null ) throw new Exception( "A ListView managed by ListViewDragManager must have its ItemsSource set to an ObservableCollection<ItemType>." ); int oldIndex = itemsSource.IndexOf( data ); int newIndex = this.IndexUnderDragCursor; if( newIndex < 0 ) { // The drag started somewhere else, and our ListView is empty // so make the new item the first in the list. if( itemsSource.Count == 0 ) newIndex = 0; // The drag started somewhere else, but our ListView has items // so make the new item the last in the list. else if( oldIndex < 0 ) newIndex = itemsSource.Count; // The user is trying to drop an item from our ListView into // our ListView, but the mouse is not over an item, so don't // let them drop it. else return; } // Dropping an item back onto itself is not considered an actual 'drop'. if( oldIndex == newIndex ) return; if( this.ProcessDrop != null ) { // Let the client code process the drop. ProcessDropEventArgs<ItemType> args = new ProcessDropEventArgs<ItemType>( itemsSource, data, oldIndex, newIndex, e.AllowedEffects ); this.ProcessDrop( this, args ); e.Effects = args.Effects; } else { // Move the dragged data object from it's original index to the // new index (according to where the mouse cursor is). If it was // not previously in the ListBox, then insert the item. if( oldIndex > -1 ) itemsSource.Move( oldIndex, newIndex ); else itemsSource.Insert( newIndex, data ); // Set the Effects property so that the call to DoDragDrop will return 'Move'. e.Effects = DragDropEffects.Move; } } #endregion // listView_Drop #endregion // Event Handling Methods #region Private Helpers #region CanStartDragOperation bool CanStartDragOperation { get { if( Mouse.LeftButton != MouseButtonState.Pressed ) return false; if( !this.canInitiateDrag ) return false; if( this.indexToSelect == -1 ) return false; if( !this.HasCursorLeftDragThreshold ) return false; return true; } } #endregion // CanStartDragOperation #region FinishDragOperation void FinishDragOperation( ListViewItem draggedItem, AdornerLayer adornerLayer ) { // Let the ListViewItem know that it is not being dragged anymore. ListViewItemDragState.SetIsBeingDragged( draggedItem, false ); this.IsDragInProgress = false; if( this.ItemUnderDragCursor != null ) this.ItemUnderDragCursor = null; // Remove the drag adorner from the adorner layer. if( adornerLayer != null ) { adornerLayer.Remove( this.dragAdorner ); this.dragAdorner = null; } } #endregion // FinishDragOperation #region GetListViewItem ListViewItem GetListViewItem( int index ) { if( this.listView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated ) return null; return this.listView.ItemContainerGenerator.ContainerFromIndex( index ) as ListViewItem; } ListViewItem GetListViewItem( ItemType dataItem ) { if( this.listView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated ) return null; return this.listView.ItemContainerGenerator.ContainerFromItem( dataItem ) as ListViewItem; } #endregion // GetListViewItem #region HasCursorLeftDragThreshold bool HasCursorLeftDragThreshold { get { if( this.indexToSelect < 0 ) return false; ListViewItem item = this.GetListViewItem( this.indexToSelect ); Rect bounds = VisualTreeHelper.GetDescendantBounds( item ); Point ptInItem = this.listView.TranslatePoint( this.ptMouseDown, item ); // In case the cursor is at the very top or bottom of the ListViewItem // we want to make the vertical threshold very small so that dragging // over an adjacent item does not select it. double topOffset = Math.Abs( ptInItem.Y ); double btmOffset = Math.Abs( bounds.Height - ptInItem.Y ); double vertOffset = Math.Min( topOffset, btmOffset ); double width = SystemParameters.MinimumHorizontalDragDistance * 2; double height = Math.Min( SystemParameters.MinimumVerticalDragDistance, vertOffset ) * 2; Size szThreshold = new Size( width, height ); Rect rect = new Rect( this.ptMouseDown, szThreshold ); rect.Offset( szThreshold.Width / -2, szThreshold.Height / -2 ); Point ptInListView = MouseUtilities.GetMousePosition( this.listView ); return !rect.Contains( ptInListView ); } } #endregion // HasCursorLeftDragThreshold #region IndexUnderDragCursor /// <summary> /// Returns the index of the ListViewItem underneath the /// drag cursor, or -1 if the cursor is not over an item. /// </summary> int IndexUnderDragCursor { get { int index = -1; for( int i = 0; i < this.listView.Items.Count; ++i ) { ListViewItem item = this.GetListViewItem( i ); if (item == null) return -1; if( this.IsMouseOver( item ) ) { index = i; break; } } return index; } } #endregion // IndexUnderDragCursor #region InitializeAdornerLayer AdornerLayer InitializeAdornerLayer( ListViewItem itemToDrag ) { // Create a brush which will paint the ListViewItem onto // a visual in the adorner layer. VisualBrush brush = new VisualBrush( itemToDrag ); // Create an element which displays the source item while it is dragged. this.dragAdorner = new DragAdorner( this.listView, itemToDrag.RenderSize, brush ); // Set the drag adorner's opacity. this.dragAdorner.Opacity = this.DragAdornerOpacity; AdornerLayer layer = AdornerLayer.GetAdornerLayer( this.listView ); layer.Add( dragAdorner ); // Save the location of the cursor when the left mouse button was pressed. this.ptMouseDown = MouseUtilities.GetMousePosition( this.listView ); return layer; } #endregion // InitializeAdornerLayer #region InitializeDragOperation void InitializeDragOperation( ListViewItem itemToDrag ) { // Set some flags used during the drag operation. this.IsDragInProgress = true; this.canInitiateDrag = false; // Let the ListViewItem know that it is being dragged. ListViewItemDragState.SetIsBeingDragged( itemToDrag, true ); } #endregion // InitializeDragOperation #region IsMouseOver bool IsMouseOver( Visual target ) { // We need to use MouseUtilities to figure out the cursor // coordinates because, during a drag-drop operation, the WPF // mechanisms for getting the coordinates behave strangely. Rect bounds = VisualTreeHelper.GetDescendantBounds( target ); Point mousePos = MouseUtilities.GetMousePosition( target ); return bounds.Contains( mousePos ); } #endregion // IsMouseOver #region IsMouseOverScrollbar /// <summary> /// Returns true if the mouse cursor is over a scrollbar in the ListView. /// </summary> bool IsMouseOverScrollbar { get { Point ptMouse = MouseUtilities.GetMousePosition( this.listView ); HitTestResult res = VisualTreeHelper.HitTest( this.listView, ptMouse ); if( res == null ) return false; DependencyObject depObj = res.VisualHit; while( depObj != null ) { if( depObj is ScrollBar ) return true; // VisualTreeHelper works with objects of type Visual or Visual3D. // If the current object is not derived from Visual or Visual3D, // then use the LogicalTreeHelper to find the parent element. if( depObj is Visual || depObj is System.Windows.Media.Media3D.Visual3D ) depObj = VisualTreeHelper.GetParent( depObj ); else depObj = LogicalTreeHelper.GetParent( depObj ); } return false; } } #endregion // IsMouseOverScrollbar #region ItemUnderDragCursor ItemType ItemUnderDragCursor { get { return this.itemUnderDragCursor; } set { if( this.itemUnderDragCursor == value ) return; // The first pass handles the previous item under the cursor. // The second pass handles the new one. for( int i = 0; i < 2; ++i ) { if( i == 1 ) this.itemUnderDragCursor = value; if( this.itemUnderDragCursor != null ) { ListViewItem listViewItem = this.GetListViewItem( this.itemUnderDragCursor ); if( listViewItem != null ) ListViewItemDragState.SetIsUnderDragCursor( listViewItem, i == 1 ); } } } } #endregion // ItemUnderDragCursor #region PerformDragOperation void PerformDragOperation() { ItemType selectedItem = this.listView.SelectedItem as ItemType; DragDropEffects allowedEffects = DragDropEffects.Move | DragDropEffects.Move | DragDropEffects.Link; if( DragDrop.DoDragDrop( this.listView, new DragDropInfo(selectedItem), allowedEffects ) != DragDropEffects.None ) { // The item was dropped into a new location, // so make it the new selected item. this.listView.SelectedItem = selectedItem; } } #endregion // PerformDragOperation #region ShowDragAdornerResolved bool ShowDragAdornerResolved { get { return this.ShowDragAdorner && this.DragAdornerOpacity > 0.0; } } #endregion // ShowDragAdornerResolved #region UpdateDragAdornerLocation void UpdateDragAdornerLocation() { if( this.dragAdorner != null ) { Point ptCursor = MouseUtilities.GetMousePosition( this.ListView ); double left = ptCursor.X - this.ptMouseDown.X; // 4/13/2007 - Made the top offset relative to the item being dragged. ListViewItem itemBeingDragged = this.GetListViewItem( this.indexToSelect ); Point itemLoc = itemBeingDragged.TranslatePoint( new Point( 0, 0 ), this.ListView ); double top = itemLoc.Y + ptCursor.Y - this.ptMouseDown.Y; this.dragAdorner.SetOffsets( left, top ); } } #endregion // UpdateDragAdornerLocation #endregion // Private Helpers } #endregion // ListViewDragDropManager #region ListViewItemDragState /// <summary> /// Exposes attached properties used in conjunction with the ListViewDragDropManager class. /// Those properties can be used to allow triggers to modify the appearance of ListViewItems /// in a ListView during a drag-drop operation. /// </summary> public static class ListViewItemDragState { #region IsBeingDragged /// <summary> /// Identifies the ListViewItemDragState's IsBeingDragged attached property. /// This field is read-only. /// </summary> public static readonly DependencyProperty IsBeingDraggedProperty = DependencyProperty.RegisterAttached( "IsBeingDragged", typeof( bool ), typeof( ListViewItemDragState ), new UIPropertyMetadata( false ) ); /// <summary> /// Returns true if the specified ListViewItem is being dragged, else false. /// </summary> /// <param name="item">The ListViewItem to check.</param> public static bool GetIsBeingDragged( ListViewItem item ) { return (bool)item.GetValue( IsBeingDraggedProperty ); } /// <summary> /// Sets the IsBeingDragged attached property for the specified ListViewItem. /// </summary> /// <param name="item">The ListViewItem to set the property on.</param> /// <param name="value">Pass true if the element is being dragged, else false.</param> internal static void SetIsBeingDragged( ListViewItem item, bool value ) { item.SetValue( IsBeingDraggedProperty, value ); } #endregion // IsBeingDragged #region IsUnderDragCursor /// <summary> /// Identifies the ListViewItemDragState's IsUnderDragCursor attached property. /// This field is read-only. /// </summary> public static readonly DependencyProperty IsUnderDragCursorProperty = DependencyProperty.RegisterAttached( "IsUnderDragCursor", typeof( bool ), typeof( ListViewItemDragState ), new UIPropertyMetadata( false ) ); /// <summary> /// Returns true if the specified ListViewItem is currently underneath the cursor /// during a drag-drop operation, else false. /// </summary> /// <param name="item">The ListViewItem to check.</param> public static bool GetIsUnderDragCursor( ListViewItem item ) { return (bool)item.GetValue( IsUnderDragCursorProperty ); } /// <summary> /// Sets the IsUnderDragCursor attached property for the specified ListViewItem. /// </summary> /// <param name="item">The ListViewItem to set the property on.</param> /// <param name="value">Pass true if the element is underneath the drag cursor, else false.</param> internal static void SetIsUnderDragCursor( ListViewItem item, bool value ) { item.SetValue( IsUnderDragCursorProperty, value ); } #endregion // IsUnderDragCursor } #endregion // ListViewItemDragState #region ProcessDropEventArgs /// <summary> /// Event arguments used by the ListViewDragDropManager.ProcessDrop event. /// </summary> /// <typeparam name="ItemType">The type of data object being dropped.</typeparam> public class ProcessDropEventArgs<ItemType> : EventArgs where ItemType : class { #region Data ObservableCollection<ItemType> itemsSource; ItemType dataItem; int oldIndex; int newIndex; DragDropEffects allowedEffects = DragDropEffects.None; DragDropEffects effects = DragDropEffects.None; #endregion // Data #region Constructor internal ProcessDropEventArgs( ObservableCollection<ItemType> itemsSource, ItemType dataItem, int oldIndex, int newIndex, DragDropEffects allowedEffects ) { this.itemsSource = itemsSource; this.dataItem = dataItem; this.oldIndex = oldIndex; this.newIndex = newIndex; this.allowedEffects = allowedEffects; } #endregion // Constructor #region Public Properties /// <summary> /// The items source of the ListView where the drop occurred. /// </summary> public ObservableCollection<ItemType> ItemsSource { get { return this.itemsSource; } } /// <summary> /// The data object which was dropped. /// </summary> public ItemType DataItem { get { return this.dataItem; } } /// <summary> /// The current index of the data item being dropped, in the ItemsSource collection. /// </summary> public int OldIndex { get { return this.oldIndex; } } /// <summary> /// The target index of the data item being dropped, in the ItemsSource collection. /// </summary> public int NewIndex { get { return this.newIndex; } } /// <summary> /// The drag drop effects allowed to be performed. /// </summary> public DragDropEffects AllowedEffects { get { return allowedEffects; } } /// <summary> /// The drag drop effect(s) performed on the dropped item. /// </summary> public DragDropEffects Effects { get { return effects; } set { effects = value; } } #endregion // Public Properties } #endregion // ProcessDropEventArgs }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Fonts Developer API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/fonts/docs/developer_api'>Google Fonts Developer API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160302 (426) * <tr><th>API Docs * <td><a href='https://developers.google.com/fonts/docs/developer_api'> * https://developers.google.com/fonts/docs/developer_api</a> * <tr><th>Discovery Name<td>webfonts * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Fonts Developer API can be found at * <a href='https://developers.google.com/fonts/docs/developer_api'>https://developers.google.com/fonts/docs/developer_api</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Webfonts.v1 { /// <summary>The Webfonts Service.</summary> public class WebfontsService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public WebfontsService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public WebfontsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { webfonts = new WebfontsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "webfonts"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/webfonts/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "webfonts/v1/"; } } private readonly WebfontsResource webfonts; /// <summary>Gets the Webfonts resource.</summary> public virtual WebfontsResource Webfonts { get { return webfonts; } } } ///<summary>A base abstract class for Webfonts requests.</summary> public abstract class WebfontsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new WebfontsBaseServiceRequest instance.</summary> protected WebfontsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Webfonts parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "webfonts" collection of methods.</summary> public class WebfontsResource { private const string Resource = "webfonts"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public WebfontsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API</summary> public class ListRequest : WebfontsBaseServiceRequest<Google.Apis.Webfonts.v1.Data.WebfontList> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Enables sorting of the list</summary> [Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<SortEnum> Sort { get; set; } /// <summary>Enables sorting of the list</summary> public enum SortEnum { /// <summary>Sort alphabetically</summary> [Google.Apis.Util.StringValueAttribute("alpha")] Alpha, /// <summary>Sort by date added</summary> [Google.Apis.Util.StringValueAttribute("date")] Date, /// <summary>Sort by popularity</summary> [Google.Apis.Util.StringValueAttribute("popularity")] Popularity, /// <summary>Sort by number of styles</summary> [Google.Apis.Util.StringValueAttribute("style")] Style, /// <summary>Sort by trending</summary> [Google.Apis.Util.StringValueAttribute("trending")] Trending, } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "webfonts"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "sort", new Google.Apis.Discovery.Parameter { Name = "sort", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Webfonts.v1.Data { public class Webfont : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The category of the font.</summary> [Newtonsoft.Json.JsonPropertyAttribute("category")] public virtual string Category { get; set; } /// <summary>The name of the font.</summary> [Newtonsoft.Json.JsonPropertyAttribute("family")] public virtual string Family { get; set; } /// <summary>The font files (with all supported scripts) for each one of the available variants, as a key : /// value map.</summary> [Newtonsoft.Json.JsonPropertyAttribute("files")] public virtual System.Collections.Generic.IDictionary<string,string> Files { get; set; } /// <summary>This kind represents a webfont object in the webfonts service.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The date (format "yyyy-MM-dd") the font was modified for the last time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lastModified")] public virtual string LastModified { get; set; } /// <summary>The scripts supported by the font.</summary> [Newtonsoft.Json.JsonPropertyAttribute("subsets")] public virtual System.Collections.Generic.IList<string> Subsets { get; set; } /// <summary>The available variants for the font.</summary> [Newtonsoft.Json.JsonPropertyAttribute("variants")] public virtual System.Collections.Generic.IList<string> Variants { get; set; } /// <summary>The font version.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual string Version { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class WebfontList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of fonts currently served by the Google Fonts API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Webfont> Items { get; set; } /// <summary>This kind represents a list of webfont objects in the webfonts service.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// // AudiobookLibrarySource.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008-2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Mono.Unix; using Hyena; using Banshee.Library; using Banshee.Collection; using Banshee.SmartPlaylist; using Banshee.Collection.Database; using Banshee.MediaEngine; using Banshee.Sources; using Banshee.Database; using Banshee.ServiceStack; using Banshee.Sources.Gui; using Banshee.PlaybackController; using Banshee.Query; namespace Banshee.Audiobook { public class AudiobookLibrarySource : LibrarySource, IBasicPlaybackController { internal const string LAST_PLAYED_BOOKMARK = "audiobook-lastplayed"; AudiobookModel books_model; LazyLoadSourceContents<AudiobookContent> grid_view; LazyLoadSourceContents<BookView> book_view; public BookPlaylist PlaybackSource { get; private set; } public Actions Actions { get; private set; } public AudiobookLibrarySource () : base (Catalog.GetString ("Audiobooks"), "AudiobookLibrary", 49) { MediaTypes = TrackMediaAttributes.AudioBook; NotMediaTypes = TrackMediaAttributes.Podcast | TrackMediaAttributes.VideoStream | TrackMediaAttributes.Music; SupportsPlaylists = false; Properties.SetStringList ("Icon.Name", "audiobook", "source-library"); Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search your audiobooks")); Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@" <column-controller> <add-all-defaults /> <remove-default column=""DiscColumn"" /> <remove-default column=""AlbumColumn"" /> <remove-default column=""ComposerColumn"" /> <remove-default column=""AlbumArtistColumn"" /> <remove-default column=""ConductorColumn"" /> <remove-default column=""ComposerColumn"" /> <remove-default column=""BpmColumn"" /> <sort-column direction=""asc"">track_title</sort-column> <column modify-default=""ArtistColumn""> <title>{0}</title> <long-title>{0}</long-title> </column> </column-controller> ", Catalog.GetString ("Author"))); var pattern = new AudiobookFileNamePattern (); pattern.FolderSchema = CreateSchema<string> ("folder_pattern", pattern.DefaultFolder, "", ""); pattern.FileSchema = CreateSchema<string> ("file_pattern", pattern.DefaultFile, "", ""); SetFileNamePattern (pattern); Actions = new Actions (this); grid_view = new LazyLoadSourceContents<AudiobookContent> (); book_view = new LazyLoadSourceContents<BookView> (); Properties.Set<ISourceContents> ("Nereid.SourceContents", grid_view); Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", System.Reflection.Assembly.GetExecutingAssembly ()); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true); Properties.Set<System.Action> ("ActivationAction", delegate { SwitchToGridView (); }); TracksAdded += (o, a) => { if (!IsAdding) { MergeBooksAddedSince (DateTime.Now - TimeSpan.FromHours (2)); ServiceManager.DbConnection.Execute ( "UPDATE CoreTracks SET Attributes = Attributes | ? WHERE PrimarySourceID = ?", (int)TrackMediaAttributes.AudioBook, this.DbId); } }; TrackIsPlayingHandler = ServiceManager.PlayerEngine.IsPlaying; PlaybackSource = new BookPlaylist ("audiobook-playback-source", this); PlaybackSource.DatabaseTrackModel.ForcedSortQuery = BansheeQuery.GetSort (BansheeQuery.TrackNumberField, true); ServiceManager.PlaybackController.SourceChanged += OnPlaybackSourceChanged; // Listen for playback changes and auto-set the last-played bookmark ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.EndOfStream | PlayerEvent.Seek, true); } public override string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} book", "{0} books", count); } protected override string SectionName { get { return Catalog.GetString ("Audiobooks Folder"); } } private void OnPlaybackSourceChanged (object o, EventArgs args) { if (ServiceManager.PlaybackController.Source == this) { PlaybackSource.Book = PlaybackSource.Book ?? ActiveBook; } else { PlaybackSource.Book = null; } Actions.UpdateActions (); } public override bool CanSearch { get { return false; } } internal void SwitchToGridView () { var last_book = CurrentViewBook; if (last_book != null) { CurrentViewBook = null; Properties.Set<ISourceContents> ("Nereid.SourceContents", grid_view); Actions.UpdateActions (); } } public void SwitchToBookView (DatabaseAlbumInfo book) { if (CurrentViewBook == null) { CurrentViewBook = book; book_view.SetSource (this); book_view.Contents.SetBook (book); Properties.Set<ISourceContents> ("Nereid.SourceContents", book_view); if (BooksModel.Selection.Count != 1) { var index = BooksModel.Selection.FocusedIndex; BooksModel.Selection.Clear (false); BooksModel.Selection.Select (index); } Actions.UpdateActions (); } } public DatabaseAlbumInfo CurrentViewBook { get; private set; } public DatabaseAlbumInfo ActiveBook { get { if (CurrentViewBook != null) { return CurrentViewBook; } if (BooksModel.Selection.FocusedIndex != -1) { return BooksModel [BooksModel.Selection.FocusedIndex] as DatabaseAlbumInfo; } if (BooksModel.Selection.Count > 0) { return BooksModel.SelectedItems.First () as DatabaseAlbumInfo; } if (BooksModel.Count > 0) { return BooksModel[0] as DatabaseAlbumInfo; } return null; } } private void MergeBooksAddedSince (DateTime since) { // TODO after import of files or move to audiobook: // If for a given author, there are a set of 'albums' (books) // whose names stripped of numbers are equal, merge them // into one book: // 1) If they already have sequential disc info, good to go // 2) If they do not, need to extract that from album title // -- or just generate it by incrementing a counter, assuming // that as-is they sort lexically //foreach (var book in BookModel.FetchMatching ("DateAdded > ? ORDER BY Title", since)) { //} } private DatabaseTrackInfo book_track; private void OnPlayerEvent (PlayerEventArgs args) { book_track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo; if (book_track == null || book_track.PrimarySourceId != this.DbId) { book_track = null; } switch (args.Event) { case PlayerEvent.StartOfStream: if (book_track != null) { StartTimeout (); if (PlaybackSource.Book == null || PlaybackSource.Book.DbId != book_track.AlbumId) { PlaybackSource.Book = DatabaseAlbumInfo.Provider.FetchSingle (book_track.AlbumId); } if (book_track.CacheModelId != PlaybackSource.DatabaseTrackModel.CacheId) { var index = PlaybackSource.DatabaseTrackModel.IndexOfFirst (book_track); if (index >= 0) { ServiceManager.PlaybackController.PriorTrack = PlaybackSource.TrackModel [index]; } else { Log.Error ("Audiobook track started, but couldn't find in the Audiobook.PlaybackSource"); } } } break; case PlayerEvent.EndOfStream: StopTimeout (); break; case PlayerEvent.Seek: UpdateLastPlayed (); break; } } private uint timeout_id; private void StartTimeout () { if (timeout_id == 0) { timeout_id = Application.RunTimeout (3000, delegate { UpdateLastPlayed (); return true; }); } } private void StopTimeout () { if (timeout_id != 0) { Application.IdleTimeoutRemove (timeout_id); timeout_id = 0; } } private Bookmark bookmark; private void UpdateLastPlayed () { if (book_track != null && book_track.IsPlaying && ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing) { bookmark = GetLastPlayedBookmark (book_track.AlbumId) ?? new Bookmark (); bookmark.Type = LAST_PLAYED_BOOKMARK; bookmark.CreatedAt = DateTime.Now; bookmark.Track = book_track; bookmark.Position = TimeSpan.FromMilliseconds ((int)ServiceManager.PlayerEngine.Position); bookmark.Save (); if (CurrentViewBook != null && book_track.AlbumId == CurrentViewBook.DbId) { book_view.Contents.UpdateResumeButton (bookmark); } } } public Bookmark GetLastPlayedBookmark (int book_id) { return Bookmark.Provider.FetchFirstMatching ( "Type = ? AND TrackID IN (SELECT TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND AlbumID = ?)", LAST_PLAYED_BOOKMARK, this.DbId, book_id ); } public override void Dispose () { ServiceManager.PlaybackController.SourceChanged -= OnPlaybackSourceChanged; ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); if (Actions != null) { Actions.Dispose (); Actions = null; } base.Dispose (); } protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src) { var books_model = new AudiobookModel (this, this.DatabaseTrackModel, ServiceManager.DbConnection, this.UniqueId); if (src == this) { this.books_model = books_model; } yield return books_model; } public override bool AcceptsInputFromSource (Source source) { return CanAddTracks && source != this && source.Parent != this && (source.Parent is PrimarySource || source is PrimarySource); } #region IBasicPlaybackController implementation public bool First () { return DoPlaybackAction (); } public bool Next (bool restart, bool changeImmediately) { return DoPlaybackAction (); } public bool Previous (bool restart) { return DoPlaybackAction (); } #endregion private bool DoPlaybackAction () { PlaybackSource.Book = PlaybackSource.Book ?? ActiveBook; ServiceManager.PlaybackController.Source = PlaybackSource; ServiceManager.PlaybackController.NextSource = this; return false; } public DatabaseAlbumListModel BooksModel { get { return books_model; } } public override string DefaultBaseDirectory { // FIXME should probably translate this fallback directory get { return XdgBaseDirectorySpec.GetXdgDirectoryUnderHome ("XDG_AUDIOBOOKS_DIR", "Audiobooks"); } } public override int Count { get { return 0; } } public override int FilteredCount { get { return books_model.Count; } } public override TimeSpan Duration { get { return DatabaseTrackModel.UnfilteredDuration; } } public override long FileSize { get { return DatabaseTrackModel.UnfilteredFileSize; } } public override bool ShowBrowser { get { return false; } } protected override bool HasArtistAlbum { get { return false; } } public override bool CanShuffle { get { return false; } } public override IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists { get { yield break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Threading; using System.Collections.Generic; using Xunit; namespace System.Diagnostics.Tests { public class ProcessStreamReadTests : ProcessTestBase { [Fact] public void TestSyncErrorStream() { Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.Start(); string expected = TestConsoleApp + " started error stream" + Environment.NewLine + TestConsoleApp + " closed error stream" + Environment.NewLine; Assert.Equal(expected, p.StandardError.ReadToEnd()); Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestAsyncErrorStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.ErrorDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelErrorRead(); } }; p.Start(); p.BeginErrorReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started error stream" + (i == 1 ? "" : TestConsoleApp + " closed error stream"); Assert.Equal(expected, sb.ToString()); } } private static int ErrorProcessBody() { Console.Error.WriteLine(TestConsoleApp + " started error stream"); Console.Error.WriteLine(TestConsoleApp + " closed error stream"); return SuccessExitCode; } [Fact] public void TestSyncOutputStream() { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.Start(); string s = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(TestConsoleApp + " started" + Environment.NewLine + TestConsoleApp + " closed" + Environment.NewLine, s); } [Fact] public void TestAsyncOutputStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelOutputRead(); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started" + (i == 1 ? "" : TestConsoleApp + " closed"); Assert.Equal(expected, sb.ToString()); } } private static int StreamBody() { Console.WriteLine(TestConsoleApp + " started"); Console.WriteLine(TestConsoleApp + " closed"); return SuccessExitCode; } [Fact] public void TestSyncStreams() { const string expected = "This string should come as output"; Process p = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { Assert.Equal(expected, e.Data); }; p.Start(); using (StreamWriter writer = p.StandardInput) { writer.WriteLine(expected); } Assert.True(p.WaitForExit(WaitInMS)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "There is 2 bugs in Desktop in this codepath, see: dotnet/corefx #18437 and #18436")] public void TestAsyncHalfCharacterAtATime() { var receivedOutput = false; var collectedExceptions = new List<Exception>(); Process p = CreateProcess(() => { var stdout = Console.OpenStandardOutput(); var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a"); for (int i = 0; i != bytes.Length; ++i) { stdout.WriteByte(bytes[i]); stdout.Flush(); Thread.Sleep(100); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.StandardOutputEncoding = Encoding.Unicode; p.OutputDataReceived += (s, e) => { try { if (!receivedOutput) { receivedOutput = true; Assert.Equal(e.Data, "a"); } } catch (Exception ex) { // This ensures that the exception in event handlers does not break // the whole unittest collectedExceptions.Add(ex); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.True(receivedOutput); if (collectedExceptions.Count > 0) { // Re-throw collected exceptions throw new AggregateException(collectedExceptions); } } [Fact] public void TestManyOutputLines() { const int ExpectedLineCount = 144; int nonWhitespaceLinesReceived = 0; int totalLinesReceived = 0; Process p = CreateProcess(() => { for (int i = 0; i < ExpectedLineCount; i++) { Console.WriteLine("This is line #" + i + "."); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) { nonWhitespaceLinesReceived++; } totalLinesReceived++; }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.Equal(ExpectedLineCount, nonWhitespaceLinesReceived); Assert.Equal(ExpectedLineCount + 1, totalLinesReceived); } [Fact] public void TestStreamNegativeTests() { { Process p = new Process(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.Throws<InvalidOperationException>(() => p.CancelOutputRead()); Assert.Throws<InvalidOperationException>(() => p.CancelErrorRead()); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.True(p.WaitForExit(WaitInMS)); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); StreamReader output = p.StandardOutput; StreamReader error = p.StandardError; Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.True(p.WaitForExit(WaitInMS)); } } } }
#region Apache Licensed /* Copyright 2013 Daniel Cazzulino 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 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Globalization; namespace Kzu.NuGetReferences.Properties { /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] static partial class Strings { /// <summary> /// Looks up a localized string similar to: /// (Executing Command) /// </summary> public static string ExecutingCommand { get { return Resources.ExecutingCommand; } } /// <summary> /// Looks up a localized string similar to: /// Failed to load NuGet Package Manager. Please contact support. /// </summary> public static string FailedToLoadNuGetPackage { get { return Resources.FailedToLoadNuGetPackage; } } /// <summary> /// Looks up a localized string similar to: /// Your currently installed version of NuGet Package Manager is version {installedVersion}, but the {productName} extension was tested with version {buildVersion}. Some functionality may not work as expected. /// </summary> public static string IncompatibleNuGet(object installedVersion, object productName, object buildVersion) { return Resources.IncompatibleNuGet.FormatWith(new { installedVersion = installedVersion, productName = productName, buildVersion = buildVersion, }); } /// <summary> /// Looks up a localized string similar to: /// (Initializing NuGet Console) /// </summary> public static string InitializingConsole { get { return Resources.InitializingConsole; } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class PackageInfo { /// <summary> /// Looks up a localized string similar to: /// General /// </summary> public static string Category { get { return Resources.PackageInfo_Category; } } /// <summary> /// Looks up a localized string similar to: /// NuGet Package /// </summary> public static string DisplayName { get { return Resources.PackageInfo_DisplayName; } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Id { /// <summary> /// Looks up a localized string similar to: /// Package identifier. /// </summary> public static string Description { get { return Resources.PackageInfo_Id_Description; } } /// <summary> /// Looks up a localized string similar to: /// Id /// </summary> public static string DisplayName { get { return Resources.PackageInfo_Id_DisplayName; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Version { /// <summary> /// Looks up a localized string similar to: /// Package version. /// </summary> public static string Description { get { return Resources.PackageInfo_Version_Description; } } /// <summary> /// Looks up a localized string similar to: /// Version /// </summary> public static string DisplayName { get { return Resources.PackageInfo_Version_DisplayName; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Title { /// <summary> /// Looks up a localized string similar to: /// Package title. /// </summary> public static string Description { get { return Resources.PackageInfo_Title_Description; } } /// <summary> /// Looks up a localized string similar to: /// Title /// </summary> public static string DisplayName { get { return Resources.PackageInfo_Title_DisplayName; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Authors { /// <summary> /// Looks up a localized string similar to: /// Package authors. /// </summary> public static string Description { get { return Resources.PackageInfo_Authors_Description; } } /// <summary> /// Looks up a localized string similar to: /// Authors /// </summary> public static string DisplayName { get { return Resources.PackageInfo_Authors_DisplayName; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class InstallPath { /// <summary> /// Looks up a localized string similar to: /// Package installation location. /// </summary> public static string Description { get { return Resources.PackageInfo_InstallPath_Description; } } /// <summary> /// Looks up a localized string similar to: /// Install Path /// </summary> public static string DisplayName { get { return Resources.PackageInfo_InstallPath_DisplayName; } } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Uninstall { /// <summary> /// Looks up a localized string similar to: /// Uninstall /// </summary> public static string Text { get { return Resources.Uninstall_Text; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Update { /// <summary> /// Looks up a localized string similar to: /// Update /// </summary> public static string Text { get { return Resources.Update_Text; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Package { /// <summary> /// Looks up a localized string similar to: /// Installing DevStore version {version} from {vsixPath}. /// </summary> public static string DevStoreInstalling(object version, object vsixPath) { return Resources.Package_DevStoreInstalling.FormatWith(new { version = version, vsixPath = vsixPath, }); } /// <summary> /// Looks up a localized string similar to: /// DevStore is currently not installed. /// </summary> public static string DevStoreNotInstalled { get { return Resources.Package_DevStoreNotInstalled; } } /// <summary> /// Looks up a localized string similar to: /// Installed DevStore version is {oldVersion}. Upgrading to {newVersion}. /// </summary> public static string DevStoreOldVersion(object oldVersion, object newVersion) { return Resources.Package_DevStoreOldVersion.FormatWith(new { oldVersion = oldVersion, newVersion = newVersion, }); } /// <summary> /// Looks up a localized string similar to: /// Latest version of DevStore will be activated on your next Visual Studio restart. /// </summary> public static string DevStoreRestartNeeded { get { return Resources.Package_DevStoreRestartNeeded; } } /// <summary> /// Looks up a localized string similar to: /// Could not find DevStore installer at {vsixPath}. Please reinstall {product}. /// </summary> public static string DevStoreVsixNotFound(object vsixPath, object product) { return Resources.Package_DevStoreVsixNotFound.FormatWith(new { vsixPath = vsixPath, product = product, }); } /// <summary> /// Looks up a localized string similar to: /// Verifying current version of DevStore /// </summary> public static string VerifyingDevStore { get { return Resources.Package_VerifyingDevStore; } } } /// <summary> /// Provides access to string resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("netfx-System.Strings", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Reinstall { /// <summary> /// Looks up a localized string similar to: /// Reinstall /// </summary> public static string Text { get { return Resources.Reinstall_Text; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Interactivity; using Prism.Wpf.Tests.Mocks; namespace Prism.Wpf.Tests.Interactivity { [TestClass] public class InvokeCommandActionFixture { [TestMethod] public void WhenCommandPropertyIsSet_ThenHooksUpCommandBehavior() { var someControl = new TextBox(); var commandAction = new InvokeCommandAction(); var command = new MockCommand(); commandAction.Attach(someControl); commandAction.Command = command; Assert.IsFalse(command.ExecuteCalled); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.AreSame(command, commandAction.GetValue(InvokeCommandAction.CommandProperty)); } [TestMethod] public void WhenAttachedAfterCommandPropertyIsSetAndInvoked_ThenInvokesCommand() { var someControl = new TextBox(); var commandAction = new InvokeCommandAction(); var command = new MockCommand(); commandAction.Command = command; commandAction.Attach(someControl); Assert.IsFalse(command.ExecuteCalled); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.AreSame(command, commandAction.GetValue(InvokeCommandAction.CommandProperty)); } [TestMethod] public void WhenChangingProperty_ThenUpdatesCommand() { var someControl = new TextBox(); var oldCommand = new MockCommand(); var newCommand = new MockCommand(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = oldCommand; commandAction.Command = newCommand; commandAction.InvokeAction(null); Assert.IsTrue(newCommand.ExecuteCalled); Assert.IsFalse(oldCommand.ExecuteCalled); } [TestMethod] public void WhenInvokedWithCommandParameter_ThenPassesCommandParaeterToExecute() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsNull(command.ExecuteParameter); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); Assert.IsNotNull(command.ExecuteParameter); Assert.AreSame(parameter, command.ExecuteParameter); } [TestMethod] public void WhenCommandParameterChanged_ThenUpdatesIsEnabledState() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; Assert.IsNull(command.CanExecuteParameter); Assert.IsTrue(someControl.IsEnabled); command.CanExecuteReturnValue = false; commandAction.CommandParameter = parameter; Assert.IsNotNull(command.CanExecuteParameter); Assert.AreSame(parameter, command.CanExecuteParameter); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenCanExecuteChanged_ThenUpdatesIsEnabledState() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsTrue(someControl.IsEnabled); command.CanExecuteReturnValue = false; command.RaiseCanExecuteChanged(); Assert.IsNotNull(command.CanExecuteParameter); Assert.AreSame(parameter, command.CanExecuteParameter); Assert.IsFalse(someControl.IsEnabled); } [TestMethod] public void WhenDetatched_ThenSetsCommandAndCommandParameterToNull() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Attach(someControl); commandAction.Command = command; commandAction.CommandParameter = parameter; Assert.IsNotNull(commandAction.Command); Assert.IsNotNull(commandAction.CommandParameter); commandAction.Detach(); Assert.IsNull(commandAction.Command); Assert.IsNull(commandAction.CommandParameter); } [TestMethod] public void WhenCommandIsSetAndThenBehaviorIsAttached_ThenCommandsCanExecuteIsCalledOnce() { var someControl = new TextBox(); var command = new MockCommand(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); Assert.AreEqual(1, command.CanExecuteTimesCalled); } [TestMethod] public void WhenCommandAndCommandParameterAreSetPriorToBehaviorBeingAttached_ThenCommandIsExecutedCorrectlyOnInvoke() { var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.CommandParameter = parameter; commandAction.Attach(someControl); commandAction.InvokeAction(null); Assert.IsTrue(command.ExecuteCalled); } [TestMethod] public void WhenCommandParameterNotSet_ThenEventArgsPassed() { var eventArgs = new TestEventArgs(null); var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.Attach(someControl); commandAction.InvokeAction(eventArgs); Assert.IsInstanceOfType(command.ExecuteParameter, typeof(TestEventArgs)); } [TestMethod] public void WhenCommandParameterNotSetAndEventArgsParameterPathSet_ThenPathedValuePassed() { var eventArgs = new TestEventArgs("testname"); var someControl = new TextBox(); var command = new MockCommand(); var parameter = new object(); var commandAction = new InvokeCommandAction(); commandAction.Command = command; commandAction.TriggerParameterPath = "Thing1.Thing2.Name"; commandAction.Attach(someControl); commandAction.InvokeAction(eventArgs); Assert.AreEqual("testname", command.ExecuteParameter); } } class TestEventArgs : EventArgs { public TestEventArgs(string name) { this.Thing1 = new Thing1 { Thing2 = new Thing2 { Name = name } }; } public Thing1 Thing1 { get; set; } } class Thing1 { public Thing2 Thing2 { get; set; } } class Thing2 { public string Name { get; set; } } }
/* insert license info here */ using System; using System.Collections; namespace Business.Data.Laboratorio { /// <summary> /// Generated by MyGeneration using the NHibernate Object Mapping template /// </summary> [Serializable] public sealed class ObservacionResultado: Business.BaseDataAccess { #region Private Members private bool m_isChanged; private int m_idobservacionresultado; private Efector m_idefector; private TipoServicio m_idtiposervicio; private string m_codigo; private string m_nombre; private bool m_baja; private Usuario m_idusuarioregistro; private DateTime m_fecharegistro; #endregion #region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public ObservacionResultado() { m_idobservacionresultado = 0; m_idefector =new Efector(); m_idtiposervicio = new TipoServicio(); m_codigo = String.Empty; m_nombre = String.Empty; m_baja = false; m_idusuarioregistro = new Usuario(); m_fecharegistro = DateTime.MinValue; } #endregion // End of Default ( Empty ) Class Constuctor #region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public ObservacionResultado( Efector idefector, TipoServicio idtiposervicio, string codigo, string nombre, bool baja, Usuario idusuarioregistro, DateTime fecharegistro) : this() { m_idefector = idefector; m_idtiposervicio = idtiposervicio; m_codigo = codigo; m_nombre = nombre; m_baja = baja; m_idusuarioregistro = idusuarioregistro; m_fecharegistro = fecharegistro; } #endregion // End Required Fields Only Constructor #region Public Properties /// <summary> /// /// </summary> public int IdObservacionResultado { get { return m_idobservacionresultado; } set { m_isChanged |= ( m_idobservacionresultado != value ); m_idobservacionresultado = value; } } /// <summary> /// /// </summary> public Efector IdEfector { get { return m_idefector; } set { m_isChanged |= ( m_idefector != value ); m_idefector = value; } } /// <summary> /// /// </summary> public TipoServicio IdTipoServicio { get { return m_idtiposervicio; } set { m_isChanged |= (m_idtiposervicio != value); m_idtiposervicio = value; } } /// <summary> /// /// </summary> public string Codigo { get { return m_codigo; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Codigo", value, "null"); if( value.Length > 5) throw new ArgumentOutOfRangeException("Invalid value for Codigo", value, value.ToString()); m_isChanged |= (m_codigo != value); m_codigo = value; } } /// <summary> /// /// </summary> public string Nombre { get { return m_nombre; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Nombre", value, "null"); if( value.Length > 500) throw new ArgumentOutOfRangeException("Invalid value for Nombre", value, value.ToString()); m_isChanged |= (m_nombre != value); m_nombre = value; } } /// <summary> /// /// </summary> public bool Baja { get { return m_baja; } set { m_isChanged |= ( m_baja != value ); m_baja = value; } } /// <summary> /// /// </summary> public Usuario IdUsuarioRegistro { get { return m_idusuarioregistro; } set { m_isChanged |= ( m_idusuarioregistro != value ); m_idusuarioregistro = value; } } /// <summary> /// /// </summary> public DateTime FechaRegistro { get { return m_fecharegistro; } set { m_isChanged |= ( m_fecharegistro != value ); m_fecharegistro = value; } } /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public bool IsChanged { get { return m_isChanged; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { public partial class TCRead2 : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCRead2 // Test Case public override void AddChildren() { // for function v2 { this.AddChild(new CVariation(v2) { Attribute = new Variation("Read after Close") }); } // for function v3 { this.AddChild(new CVariation(v3) { Attribute = new Variation("Read stream less than 4K") }); } // for function v4 { this.AddChild(new CVariation(v4) { Attribute = new Variation("Read with surrogate character entity") }); } // for function v6 { this.AddChild(new CVariation(v6) { Attribute = new Variation("Read with surrogates inside, comments/PIs, text, CDATA") }); } // for function v10 { this.AddChild(new CVariation(v10) { Attribute = new Variation("Tag name > 4K") }); } // for function v12 { this.AddChild(new CVariation(v12) { Attribute = new Variation("Whitespace characters in character entities") }); } // for function v13 { this.AddChild(new CVariation(v13) { Attribute = new Variation("Root element 18 chars length") }); } // for function v14 { this.AddChild(new CVariation(v14) { Attribute = new Variation("File with external DTD") }); } // for function Read31 { this.AddChild(new CVariation(Read31) { Attribute = new Variation("Namespace prefix starting with xml") }); } // for function XmlExceptionCtorWithNoParamsDoesNotThrow { this.AddChild(new CVariation(XmlExceptionCtorWithNoParamsDoesNotThrow) { Attribute = new Variation("Instantiate an XmlException object without a parameter") }); } // for function ReadEmpty { this.AddChild(new CVariation(ReadEmpty) { Attribute = new Variation("Test Read of Empty Elements") }); } // for function Read33 { this.AddChild(new CVariation(Read33) { Attribute = new Variation("1.Parsing this 'some]' as fragment fails with 'Unexpected EOF' error") }); } // for function Read33a { this.AddChild(new CVariation(Read33a) { Attribute = new Variation("2. Parsing this 'some]' as fragment fails with 'Unexpected EOF' error") }); } // for function Read34 { this.AddChild(new CVariation(Read34) { Attribute = new Variation("Parsing xml:space attribute with spaces") }); } // for function Read35 { this.AddChild(new CVariation(Read35) { Attribute = new Variation("Parsing valid xml in ASCII encoding") }); } // for function Read36 { this.AddChild(new CVariation(Read36) { Attribute = new Variation("Parsing valid xml with huge attributes") }); } // for function Read37 { this.AddChild(new CVariation(Read37) { Attribute = new Variation("XmlReader accepts invalid <!ATTLIST e a NOTATION (prefix:name) #IMPLIED> declaration") }); } // for function Read38 { this.AddChild(new CVariation(Read38) { Attribute = new Variation("XmlReader reports strange error message on &#; character entity reference") }); } // for function Read39 { this.AddChild(new CVariation(Read39) { Attribute = new Variation("Assert and wrong XmlException.Message when run non-wf xml") }); } // for function Read41 { this.AddChild(new CVariation(Read41) { Attribute = new Variation("Testing general entity references itself") }); } // for function Read42 { this.AddChild(new CVariation(Read42) { Attribute = new Variation("Testing duplicate attribute") }); } // for function Read43 { this.AddChild(new CVariation(Read43) { Attribute = new Variation("Testing xml without root element") }); } // for function Read44 { this.AddChild(new CVariation(Read44) { Attribute = new Variation("Testing xml with unexpected token") }); } // for function Read45 { this.AddChild(new CVariation(Read45) { Attribute = new Variation("XmlException when run non-wf xml") }); } // for function Read46 { this.AddChild(new CVariation(Read46) { Attribute = new Variation("Parsing valid xml with 100 attributes with same names and diff.namespaces") }); } // for function Read47 { this.AddChild(new CVariation(Read47) { Attribute = new Variation("Parsing xml with invalid surrogate pair in PUBLIC") }); } // for function Read48 { this.AddChild(new CVariation(Read48) { Attribute = new Variation("Recursive entity reference inside attribute") }); } // for function Read49 { this.AddChild(new CVariation(Read49) { Attribute = new Variation("Parsing valid xml with large number of attributes inside single element") }); } // for function Read50 { this.AddChild(new CVariation(Read50) { Attribute = new Variation("3.Test DTD with namespaces") { Param = 3 } }); this.AddChild(new CVariation(Read50) { Attribute = new Variation("1.Test DTD with namespaces") { Param = 1 } }); this.AddChild(new CVariation(Read50) { Attribute = new Variation("2.Test DTD with namespaces") { Param = 2 } }); } // for function Read53 { this.AddChild(new CVariation(Read53) { Attribute = new Variation("4.Parsing invalid DOCTYPE") { Param = 4 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("2.Parsing invalid DOCTYPE") { Param = 2 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("3.Parsing invalid DOCTYPE") { Param = 3 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("1.Parsing invalid DOCTYPE") { Param = 1 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("5.Parsing invalid DOCTYPE") { Param = 5 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("6.Parsing invalid DOCTYPE") { Param = 6 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("7.Parsing invalid DOCTYPE") { Param = 7 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("8.Parsing invalid xml version") { Param = 8 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("9.Parsing invalid xml version,DOCTYPE") { Param = 9 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("10.Parsing invalid xml version") { Param = 10 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("11.Parsing invalid xml version") { Param = 11 } }); this.AddChild(new CVariation(Read53) { Attribute = new Variation("12.Parsing invalid xml version") { Param = 12 } }); } // for function Read54 { this.AddChild(new CVariation(Read54) { Attribute = new Variation("Parse an XML declaration that will have some whitespace before the closing") }); } // for function Read55 { this.AddChild(new CVariation(Read55) { Attribute = new Variation("Parsing xml with DTD and 200 attributes") { Param = 1 } }); this.AddChild(new CVariation(Read55) { Attribute = new Variation("Parsing xml with DTD and 200 attributes with ns") { Param = 2 } }); } // for function Read56 { this.AddChild(new CVariation(Read56) { Attribute = new Variation("Parsing xml with DTD and 200 attributes and 1 duplicate") { Param = 1 } }); this.AddChild(new CVariation(Read56) { Attribute = new Variation("Parsing xml with DTD and 200 attributes with ns and 1 duplicate") { Param = 2 } }); } // for function Read57 { this.AddChild(new CVariation(Read57) { Attribute = new Variation("Parse xml with whitespaces nodes") }); } // for function Read58 { this.AddChild(new CVariation(Read58) { Attribute = new Variation("Parse xml with whitespaces nodes and invalid char") }); } // for function Read59 { this.AddChild(new CVariation(Read59) { Attribute = new Variation("Parse xml with uri attribute") }); } // for function Read63 { this.AddChild(new CVariation(Read63) { Attribute = new Variation("XmlReader doesn't fail when numeric character entity computation overflows") }); } // for function Read64 { this.AddChild(new CVariation(Read64) { Attribute = new Variation("XmlReader should fail on ENTITY name with colons in it") { Param = 1 } }); this.AddChild(new CVariation(Read64) { Attribute = new Variation("XmlReader should fail on ENTITY name with colons in it") { Param = 1 } }); } // for function Read65 { } // for function Read66 { this.AddChild(new CVariation(Read66) { Attribute = new Variation("Parse input with a character zero 0x00 at root level.") }); } // for function Read68 { this.AddChild(new CVariation(Read68) { Attribute = new Variation("3.Parse input with utf-16 encoding") { Param = "charset03.xml" } }); this.AddChild(new CVariation(Read68) { Attribute = new Variation("1.Parse input with utf-16 encoding") { Param = "charset01.xml" } }); } // for function Read68a { this.AddChild(new CVariation(Read68a) { Attribute = new Variation("2.Parse input with utf-16 encoding") { Param = "charset02.xml" } }); } // for function Read70 { this.AddChild(new CVariation(Read70) { Attribute = new Variation("Add column position to the exception reported when end tag does not match the start tag") }); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Runtime.InteropServices; using System.Security; using System.Text; // Once Serialization is available on CoreCLR: using System.Runtime.Serialization.Formatters.Binary; namespace Microsoft.PowerShell.Commands { /// <summary> /// Displays the hexadecimal equivalent of the input data. /// </summary> [Cmdlet(VerbsCommon.Format, "Hex", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096611")] [OutputType(typeof(ByteCollection))] [Alias("fhx")] public sealed class FormatHex : PSCmdlet { private const int BUFFERSIZE = 16; /// <summary> /// For cases where a homogenous collection of bytes or other items are directly piped in, we collect all the /// bytes in a List&lt;byte&gt; and then output the formatted result all at once in EndProcessing(). /// </summary> private readonly List<byte> _inputBuffer = new(); /// <summary> /// Expect to group <see cref="InputObject"/>s by default. When receiving input that should not be grouped, /// e.g., arrays, strings, FileInfo objects, this flag will be disabled until the next groupable /// <see cref="InputObject"/> is received over the pipeline. /// </summary> private bool _groupInput = true; /// <summary> /// Keep track of prior input types to determine if we're given a heterogenous collection. /// </summary> private Type _lastInputType; #region Parameters /// <summary> /// Gets or sets the path of file(s) to process. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Path")] [ValidateNotNullOrEmpty()] public string[] Path { get; set; } /// <summary> /// Gets or sets the literal path of file to process. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "LiteralPath")] [ValidateNotNullOrEmpty()] [Alias("PSPath", "LP")] public string[] LiteralPath { get; set; } /// <summary> /// Gets or sets the object to process. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByInputObject", ValueFromPipeline = true)] public PSObject InputObject { get; set; } /// <summary> /// Gets or sets the type of character encoding for InputObject. /// </summary> [Parameter(ParameterSetName = "ByInputObject")] [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] public Encoding Encoding { get { return _encoding; } set { EncodingConversion.WarnIfObsolete(this, value); _encoding = value; } } private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// <summary> /// Gets or sets count of bytes to read from the input stream. /// </summary> [Parameter] [ValidateRange(ValidateRangeKind.Positive)] public long Count { get; set; } = long.MaxValue; /// <summary> /// Gets or sets offset of bytes to start reading the input stream from. /// </summary> [Parameter] [ValidateRange(ValidateRangeKind.NonNegative)] public long Offset { get; set; } /// <summary> /// Gets or sets whether the file input should be swallowed as is. This parameter is no-op, deprecated. /// </summary> [Parameter(ParameterSetName = "ByInputObject", DontShow = true)] [Obsolete("Raw parameter is deprecated.", true)] public SwitchParameter Raw { get; set; } #endregion #region Overrides /// <summary> /// Implements the ProcessRecord method for the FormatHex command. /// </summary> protected override void ProcessRecord() { if (string.Equals(ParameterSetName, "ByInputObject", StringComparison.OrdinalIgnoreCase)) { ProcessInputObjects(InputObject); } else { List<string> pathsToProcess = string.Equals(ParameterSetName, "LiteralPath", StringComparison.OrdinalIgnoreCase) ? ResolvePaths(LiteralPath, true) : ResolvePaths(Path, false); ProcessPath(pathsToProcess); } } /// <summary> /// Implements the EndProcessing method for the FormatHex command. /// </summary> protected override void EndProcessing() { FlushInputBuffer(); } #endregion #region Paths /// <summary> /// Validate each path provided and if valid, add to array of paths to process. /// If path is a literal path it is added to the array to process; we cannot validate them until we /// try to process file contents. /// </summary> /// <param name="path">The file path to resolve.</param> /// <param name="literalPath">The paths to process.</param> /// <returns></returns> private List<string> ResolvePaths(string[] path, bool literalPath) { List<string> pathsToProcess = new(); ProviderInfo provider = null; foreach (string currentPath in path) { List<string> newPaths = new(); if (literalPath) { newPaths.Add(Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(currentPath, out provider, out _)); } else { try { newPaths.AddRange(Context.SessionState.Path.GetResolvedProviderPathFromPSPath(currentPath, out provider)); } catch (ItemNotFoundException e) { if (!WildcardPattern.ContainsWildcardCharacters(currentPath)) { ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); WriteError(errorRecord); continue; } } } if (!provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) { // Write a non-terminating error message indicating that path specified is not supported. string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexOnlySupportsFileSystemPaths, currentPath); ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "FormatHexOnlySupportsFileSystemPaths", ErrorCategory.InvalidArgument, currentPath); WriteError(errorRecord); continue; } pathsToProcess.AddRange(newPaths); } return pathsToProcess; } /// <summary> /// Pass each valid path on to process its contents. /// </summary> /// <param name="pathsToProcess">The paths to process.</param> private void ProcessPath(List<string> pathsToProcess) { foreach (string path in pathsToProcess) { ProcessFileContent(path); } } /// <summary> /// Creates a binary reader that reads the file content into a buffer (byte[]) 16 bytes at a time, and /// passes a copy of that array on to the WriteHexadecimal method to output. /// </summary> /// <param name="path">The file path to retrieve content from for processing.</param> private void ProcessFileContent(string path) { Span<byte> buffer = stackalloc byte[BUFFERSIZE]; try { using var reader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)); long offset = Offset; int bytesRead = 0; long count = 0; reader.BaseStream.Position = Offset; while ((bytesRead = reader.Read(buffer)) > 0) { count += bytesRead; if (count > Count) { bytesRead -= (int)(count - Count); WriteHexadecimal(buffer.Slice(0, bytesRead), path, offset); break; } WriteHexadecimal(buffer.Slice(0, bytesRead), path, offset); offset += bytesRead; } } catch (IOException fileException) { // IOException takes care of FileNotFoundException, DirectoryNotFoundException, and PathTooLongException WriteError(new ErrorRecord(fileException, "FormatHexIOError", ErrorCategory.WriteError, path)); } catch (ArgumentException argException) { WriteError(new ErrorRecord(argException, "FormatHexArgumentError", ErrorCategory.WriteError, path)); } catch (NotSupportedException notSupportedException) { WriteError(new ErrorRecord( notSupportedException, "FormatHexPathRefersToANonFileDevice", ErrorCategory.InvalidArgument, path)); } catch (SecurityException securityException) { WriteError(new ErrorRecord( securityException, "FormatHexUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); } } #endregion #region InputObjects private void ProcessString(string originalString) { Span<byte> bytes = Encoding.GetBytes(originalString); int offset = Math.Min(bytes.Length, Offset < int.MaxValue ? (int)Offset : int.MaxValue); int count = Math.Min(bytes.Length - offset, Count < int.MaxValue ? (int)Count : int.MaxValue); if (offset != 0 || count != bytes.Length) { WriteHexadecimal(bytes.Slice(offset, count), offset: 0, label: GetGroupLabel(typeof(string))); } else { WriteHexadecimal(bytes, offset: 0, label: GetGroupLabel(typeof(string))); } } private static readonly Random _idGenerator = new(); private static string GetGroupLabel(Type inputType) => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); private void FlushInputBuffer() { if (_inputBuffer.Count == 0) { return; } int offset = Math.Min(_inputBuffer.Count, Offset < int.MaxValue ? (int)Offset : int.MaxValue); int count = Math.Min(_inputBuffer.Count - offset, Count < int.MaxValue ? (int)Count : int.MaxValue); if (offset != 0 || count != _inputBuffer.Count) { WriteHexadecimal( _inputBuffer.GetRange(offset, count).ToArray(), offset: 0, label: GetGroupLabel(_lastInputType)); } else { WriteHexadecimal( _inputBuffer.ToArray(), offset: 0, label: GetGroupLabel(_lastInputType)); } // Reset flags so we can go back to filling up the buffer when needed. _lastInputType = null; _groupInput = true; _inputBuffer.Clear(); } /// <summary> /// Creates a byte array from the object passed to the cmdlet (based on type) and passes /// that array on to the WriteHexadecimal method to output. /// </summary> /// <param name="inputObject">The pipeline input object being processed.</param> private void ProcessInputObjects(PSObject inputObject) { object obj = inputObject.BaseObject; if (obj is FileSystemInfo fsi) { // Output already processed objects first, then process the file input. FlushInputBuffer(); string[] path = { fsi.FullName }; List<string> pathsToProcess = ResolvePaths(path, true); ProcessPath(pathsToProcess); return; } if (obj is string str) { // Output already processed objects first, then process the string input. FlushInputBuffer(); ProcessString(str); return; } byte[] inputBytes = ConvertToBytes(obj); if (!_groupInput) { FlushInputBuffer(); } if (inputBytes != null) { _inputBuffer.AddRange(inputBytes); } else { string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexTypeNotSupported, obj.GetType()); ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "FormatHexTypeNotSupported", ErrorCategory.InvalidArgument, obj.GetType()); WriteError(errorRecord); } } /// <summary> /// Converts the input object to a byte array based on the underlying type for basic value types and strings, /// as well as enum values or arrays. /// </summary> /// <param name="inputObject">The object to convert.</param> /// <returns>Returns a byte array of the input values, or null if there is no available conversion path.</returns> private byte[] ConvertToBytes(object inputObject) { Type baseType = inputObject.GetType(); byte[] result = null; int elements = 1; bool isArray = false; bool isBool = false; bool isEnum = false; if (baseType.IsArray) { FlushInputBuffer(); _lastInputType = baseType; _groupInput = false; baseType = baseType.GetElementType(); dynamic dynamicObject = inputObject; elements = (int)dynamicObject.Length; isArray = true; } if (baseType.IsEnum) { baseType = baseType.GetEnumUnderlyingType(); isEnum = true; } if (baseType.IsPrimitive && elements > 0) { if (_groupInput) { if (_lastInputType != null && baseType != _lastInputType) { _groupInput = false; FlushInputBuffer(); } _lastInputType = baseType; } if (baseType == typeof(bool)) { isBool = true; } var elementSize = Marshal.SizeOf(baseType); result = new byte[elementSize * elements]; if (!isArray) { inputObject = new object[] { inputObject }; } int index = 0; foreach (dynamic obj in (Array)inputObject) { if (elementSize == 1) { result[index] = (byte)obj; } else { dynamic toBytes; if (isEnum) { toBytes = Convert.ChangeType(obj, baseType); } else if (isBool) { // bool is 1 byte apparently toBytes = Convert.ToByte(obj); } else { toBytes = obj; } var bytes = BitConverter.GetBytes(toBytes); for (int i = 0; i < bytes.Length; i++) { result[i + index] = bytes[i]; } } index += elementSize; } } return result; } #endregion #region Output /// <summary> /// Outputs the hexadecimal representation of the input data. /// </summary> /// <param name="inputBytes">Bytes for the hexadecimal representation.</param> /// <param name="path">File path.</param> /// <param name="offset">Offset in the file.</param> private void WriteHexadecimal(Span<byte> inputBytes, string path, long offset) { const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject ? inputBytes.Length - index : bytesPerObject; var bytes = inputBytes.Slice(index, count); WriteObject(new ByteCollection((ulong)index + (ulong)offset, bytes.ToArray(), path)); } } /// <summary> /// Outputs the hexadecimal representation of the input data. /// </summary> /// <param name="inputBytes">Bytes for the hexadecimal representation.</param> /// <param name="offset">Offset in the file.</param> /// <param name="label"> /// The label for the byte group. This may be a file path, a string value, or a /// formatted identifying string for the group. /// </param> private void WriteHexadecimal(Span<byte> inputBytes, long offset, string label) { const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject ? inputBytes.Length - index : bytesPerObject; var bytes = inputBytes.Slice(index, count); WriteObject(new ByteCollection((ulong)index + (ulong)offset, label, bytes.ToArray())); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertVector128Int161() { var test = new InsertVector128Test__InsertVector128Int161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertVector128Test__InsertVector128Int161 { private struct TestStruct { public Vector256<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertVector128Int161 testClass) { var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector128<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable; static InsertVector128Test__InsertVector128Int161() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public InsertVector128Test__InsertVector128Int161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.InsertVector128( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.InsertVector128( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), LoadVector128((Int16*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.InsertVector128( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), LoadVector128((Int16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.InsertVector128), new Type[] { typeof(Vector256<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertVector128Int161(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i > 7 ? result[i] != right[i - 8] : result[i] != left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.InsertVector128)}<Int16>(Vector256<Int16>, Vector128<Int16>.1): {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.Collections.Generic; using System.Composition.Hosting.Core; using System.Composition.Hosting; namespace System.Composition { /// <summary> /// Provides retrieval of exports from the composition. /// </summary> public abstract class CompositionContext { private const string ImportManyImportMetadataConstraintName = "IsImportMany"; /// <summary> /// Retrieve the single <paramref name="contract"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="contract">The contract to retrieve.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public abstract bool TryGetExport(CompositionContract contract, out object export); /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public TExport GetExport<TExport>() { return GetExport<TExport>((string)null); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public TExport GetExport<TExport>(string contractName) { return (TExport)GetExport(typeof(TExport), contractName); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport(Type exportType, string contractName, out object export) { return TryGetExport(new CompositionContract(exportType, contractName), out export); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport(Type exportType, out object export) { return TryGetExport(exportType, null, out export); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport<TExport>(out TExport export) { return TryGetExport<TExport>(null, out export); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The type of the export to retrieve.</typeparam> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public bool TryGetExport<TExport>(string contractName, out TExport export) { object untypedExport; if (!TryGetExport(typeof(TExport), contractName, out untypedExport)) { export = default(TExport); return false; } export = (TExport)untypedExport; return true; } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(Type exportType) { return GetExport(exportType, (string)null); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">Optionally, a discriminator that constrains the selection of the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(Type exportType, string contractName) { return GetExport(new CompositionContract(exportType, contractName)); } /// <summary> /// Retrieve the single <paramref name="contract"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="contract">The contract of the export to retrieve.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public object GetExport(CompositionContract contract) { object export; if (!TryGetExport(contract, out export)) throw new CompositionFailedException( string.Format(SR.CompositionContext_NoExportFoundForContract, contract)); return export; } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <exception cref="CompositionFailedException" /> public IEnumerable<object> GetExports(Type exportType) { return GetExports(exportType, (string)null); } /// <summary> /// Retrieve the single <paramref name="exportType"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="exportType">The type of the export to retrieve.</param> /// <param name="contractName">The discriminator to apply when selecting the export.</param> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public IEnumerable<object> GetExports(Type exportType, string contractName) { var manyContract = new CompositionContract( exportType.MakeArrayType(), contractName, new Dictionary<string, object> { { ImportManyImportMetadataConstraintName, true } }); return (IEnumerable<object>)GetExport(manyContract); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The export type to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <exception cref="CompositionFailedException" /> public IEnumerable<TExport> GetExports<TExport>() { return GetExports<TExport>((string)null); } /// <summary> /// Retrieve the single <typeparamref name="TExport"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <typeparam name="TExport">The export type to retrieve.</typeparam> /// <returns>An instance of the export.</returns> /// <param name="contractName">The discriminator to apply when selecting the export.</param> /// <exception cref="CompositionFailedException" /> public IEnumerable<TExport> GetExports<TExport>(string contractName) { return (IEnumerable<TExport>)GetExports(typeof(TExport), contractName); } } }
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 Abp.App.TestWebAPI.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; } } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.ClientStack; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.UserAccountService; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; namespace OpenSim { /// <summary> /// Common OpenSimulator simulator code /// </summary> public class OpenSimBase : RegionApplicationBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // These are the names of the plugin-points extended by this // class during system startup. // private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache"; private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient"; // OpenSim.ini Section name for ESTATES Settings public const string ESTATE_SECTION_NAME = "Estates"; protected string proxyUrl; protected int proxyOffset = 0; public string userStatsURI = String.Empty; public string managedStatsURI = String.Empty; protected bool m_autoCreateClientStack = true; /// <value> /// The file used to load and save prim backup xml if no filename has been specified /// </value> protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml"; public ConfigSettings ConfigurationSettings { get { return m_configSettings; } set { m_configSettings = value; } } protected ConfigSettings m_configSettings; protected ConfigurationLoader m_configLoader; public ConsoleCommand CreateAccount = null; protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>(); /// <value> /// The config information passed into the OpenSimulator region server. /// </value> public OpenSimConfigSource ConfigSource { get; private set; } public List<IClientNetworkServer> ClientServers { get { return m_clientServers; } } protected EnvConfigSource m_EnvConfigSource = new EnvConfigSource(); public EnvConfigSource envConfigSource { get { return m_EnvConfigSource; } } protected List<IClientNetworkServer> m_clientServers = new List<IClientNetworkServer>(); public uint HttpServerPort { get { return m_httpServerPort; } } protected IRegistryCore m_applicationRegistry = new RegistryCore(); public IRegistryCore ApplicationRegistry { get { return m_applicationRegistry; } } /// <summary> /// Constructor. /// </summary> /// <param name="configSource"></param> public OpenSimBase(IConfigSource configSource) : base() { LoadConfigSettings(configSource); } protected virtual void LoadConfigSettings(IConfigSource configSource) { m_configLoader = new ConfigurationLoader(); ConfigSource = m_configLoader.LoadConfigSettings(configSource, envConfigSource, out m_configSettings, out m_networkServersInfo); Config = ConfigSource.Source; ReadExtraConfigSettings(); } protected virtual void ReadExtraConfigSettings() { IConfig networkConfig = Config.Configs["Network"]; if (networkConfig != null) { proxyUrl = networkConfig.GetString("proxy_url", ""); proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0")); } IConfig startupConfig = Config.Configs["Startup"]; if (startupConfig != null) { Util.LogOverloads = startupConfig.GetBoolean("LogOverloads", true); } } protected virtual void LoadPlugins() { IConfig startupConfig = Config.Configs["Startup"]; string registryLocation = (startupConfig != null) ? startupConfig.GetString("RegistryLocation", String.Empty) : String.Empty; // The location can also be specified in the environment. If there // is no location in the configuration, we must call the constructor // without a location parameter to allow that to happen. if (registryLocation == String.Empty) { using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this))) { loader.Load("/OpenSim/Startup"); m_plugins = loader.Plugins; } } else { using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this), registryLocation)) { loader.Load("/OpenSim/Startup"); m_plugins = loader.Plugins; } } } protected override List<string> GetHelpTopics() { List<string> topics = base.GetHelpTopics(); Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) topics.AddRange(s.GetCommanders().Keys); return topics; } /// <summary> /// Performs startup specific to the region server, including initialization of the scene /// such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { IConfig startupConfig = Config.Configs["Startup"]; if (startupConfig != null) { string pidFile = startupConfig.GetString("PIDFile", String.Empty); if (pidFile != String.Empty) CreatePIDFile(pidFile); userStatsURI = startupConfig.GetString("Stats_URI", String.Empty); managedStatsURI = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty); } // Load the simulation data service IConfig simDataConfig = Config.Configs["SimulationDataStore"]; if (simDataConfig == null) throw new Exception("Configuration file is missing the [SimulationDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?"); string module = simDataConfig.GetString("LocalServiceModule", String.Empty); if (String.IsNullOrEmpty(module)) throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section."); m_simulationDataService = ServerUtils.LoadPlugin<ISimulationDataService>(module, new object[] { Config }); if (m_simulationDataService == null) throw new Exception( string.Format( "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.", module)); // Load the estate data service IConfig estateDataConfig = Config.Configs["EstateDataStore"]; if (estateDataConfig == null) throw new Exception("Configuration file is missing the [EstateDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?"); module = estateDataConfig.GetString("LocalServiceModule", String.Empty); if (String.IsNullOrEmpty(module)) throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] section"); m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config }); if (m_estateDataService == null) throw new Exception( string.Format( "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.", module)); base.StartupSpecific(); LoadPlugins(); foreach (IApplicationPlugin plugin in m_plugins) { plugin.PostInitialise(); } if (m_console != null) AddPluginCommands(m_console); } protected virtual void AddPluginCommands(ICommandConsole console) { List<string> topics = GetHelpTopics(); foreach (string topic in topics) { string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1); // This is a hack to allow the user to enter the help command in upper or lowercase. This will go // away at some point. console.Commands.AddCommand(capitalizedTopic, false, "help " + topic, "help " + capitalizedTopic, "Get help on plugin command '" + topic + "'", HandleCommanderHelp); console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic, "help " + capitalizedTopic, "Get help on plugin command '" + topic + "'", HandleCommanderHelp); ICommander commander = null; Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) { if (s.GetCommanders().ContainsKey(topic)) commander = s.GetCommanders()[topic]; } if (commander == null) continue; foreach (string command in commander.Commands.Keys) { console.Commands.AddCommand(capitalizedTopic, false, topic + " " + command, topic + " " + commander.Commands[command].ShortHelp(), String.Empty, HandleCommanderCommand); } } } private void HandleCommanderCommand(string module, string[] cmd) { SceneManager.SendCommandToPluginModules(cmd); } private void HandleCommanderHelp(string module, string[] cmd) { // Only safe for the interactive console, since it won't // let us come here unless both scene and commander exist // ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower()); if (moduleCommander != null) m_console.Output(moduleCommander.Help); } protected override void Initialize() { // Called from base.StartUp() m_httpServerPort = m_networkServersInfo.HttpListenerPort; SceneManager.OnRestartSim += HandleRestartRegion; // Only enable the watchdogs when all regions are ready. Otherwise we get false positives when cpu is // heavily used during initial startup. // // FIXME: It's also possible that region ready status should be flipped during an OAR load since this // also makes heavy use of the CPU. SceneManager.OnRegionsReadyStatusChange += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; }; } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <returns></returns> public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene) { return CreateRegion(regionInfo, portadd_flag, false, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <returns></returns> public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, out IScene scene) { return CreateRegion(regionInfo, false, true, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <param name="do_post_init"></param> /// <returns></returns> public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene) { int port = regionInfo.InternalEndPoint.Port; // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims) // Commented this out because otherwise regions can't register with // the grid as there is already another region with the same UUID // at those coordinates. This is required for the load balancer to work. // --Mike, 2009.02.25 //regionInfo.originRegionID = regionInfo.RegionID; // set initial ServerURI regionInfo.HttpPort = m_httpServerPort; regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/"; regionInfo.osSecret = m_osSecret; if ((proxyUrl.Length > 0) && (portadd_flag)) { // set proxy url to RegionInfo regionInfo.proxyUrl = proxyUrl; regionInfo.ProxyOffset = proxyOffset; Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName); } List<IClientNetworkServer> clientServers; Scene scene = SetupScene(regionInfo, proxyOffset, Config, out clientServers); m_log.Info("[MODULES]: Loading Region's modules (old style)"); // Use this in the future, the line above will be deprecated soon m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)"); IRegionModulesController controller; if (ApplicationRegistry.TryGet(out controller)) { controller.AddRegionToModules(scene); } else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing..."); scene.SetModuleInterfaces(); while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null) SetUpEstateOwner(scene); // Prims have to be loaded after module configuration since some modules may be invoked during the load scene.LoadPrimsFromStorage(regionInfo.originRegionID); // TODO : Try setting resource for region xstats here on scene MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo)); scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID); scene.EventManager.TriggerParcelPrimCountUpdate(); try { scene.RegisterRegionWithGrid(); } catch (Exception e) { m_log.ErrorFormat( "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}", e.Message, e.StackTrace); // Carrying on now causes a lot of confusion down the // line - we need to get the user's attention Environment.Exit(1); } // We need to do this after we've initialized the // scripting engines. scene.CreateScriptInstances(); SceneManager.Add(scene); if (m_autoCreateClientStack) { foreach (IClientNetworkServer clientserver in clientServers) { m_clientServers.Add(clientserver); clientserver.Start(); } } scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); }; mscene = scene; return clientServers; } /// <summary> /// Try to set up the estate owner for the given scene. /// </summary> /// <remarks> /// The involves asking the user for information about the user on the console. If the user does not already /// exist then it is created. /// </remarks> /// <param name="scene"></param> private void SetUpEstateOwner(Scene scene) { RegionInfo regionInfo = scene.RegionInfo; string estateOwnerFirstName = null; string estateOwnerLastName = null; string estateOwnerEMail = null; string estateOwnerPassword = null; string rawEstateOwnerUuid = null; if (Config.Configs[ESTATE_SECTION_NAME] != null) { string defaultEstateOwnerName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim(); string[] ownerNames = defaultEstateOwnerName.Split(' '); if (ownerNames.Length >= 2) { estateOwnerFirstName = ownerNames[0]; estateOwnerLastName = ownerNames[1]; } // Info to be used only on Standalone Mode rawEstateOwnerUuid = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null); estateOwnerEMail = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null); estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null); } MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName); List<char> excluded = new List<char>(new char[1]{' '}); if (estateOwnerFirstName == null || estateOwnerLastName == null) { estateOwnerFirstName = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded); estateOwnerLastName = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded); } UserAccount account = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName); if (account == null) { // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than // itself! // if (scene.UserAccountService is LocalUserAccountServicesConnector) // { // IUserAccountService innerUas // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService; // // m_log.DebugFormat("B {0}", innerUas.GetType()); // // if (innerUas is UserAccountService) // { if (scene.UserAccountService is UserAccountService) { if (estateOwnerPassword == null) estateOwnerPassword = MainConsole.Instance.PasswdPrompt("Password"); if (estateOwnerEMail == null) estateOwnerEMail = MainConsole.Instance.CmdPrompt("Email"); if (rawEstateOwnerUuid == null) rawEstateOwnerUuid = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString()); UUID estateOwnerUuid = UUID.Zero; if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid)) { m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid); return; } // If we've been given a zero uuid then this signals that we should use a random user id if (estateOwnerUuid == UUID.Zero) estateOwnerUuid = UUID.Random(); account = ((UserAccountService)scene.UserAccountService).CreateUser( regionInfo.ScopeID, estateOwnerUuid, estateOwnerFirstName, estateOwnerLastName, estateOwnerPassword, estateOwnerEMail); } } if (account == null) { m_log.ErrorFormat( "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first at the grid level."); } else { regionInfo.EstateSettings.EstateOwner = account.PrincipalID; regionInfo.EstateSettings.Save(); } } private void ShutdownRegion(Scene scene) { m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName); IRegionModulesController controller; if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller)) { controller.RemoveRegionFromModules(scene); } } public void RemoveRegion(Scene scene, bool cleanup) { // only need to check this if we are not at the // root level if ((SceneManager.CurrentScene != null) && (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { SceneManager.TrySetCurrentScene(".."); } if (cleanup) { // only allow the console comand delete-region to remove objects from DB scene.DeleteAllSceneObjects(); } SceneManager.CloseScene(scene); ShutdownClientServer(scene.RegionInfo); if (!cleanup) return; if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile)) { if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml")) { File.Delete(scene.RegionInfo.RegionFile); m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile); } if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini")) { try { IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile); if (source.Configs[scene.RegionInfo.RegionName] != null) { source.Configs.Remove(scene.RegionInfo.RegionName); if (source.Configs.Count == 0) { File.Delete(scene.RegionInfo.RegionFile); } else { source.Save(scene.RegionInfo.RegionFile); } } } catch (Exception) { } } } } public void RemoveRegion(string name, bool cleanUp) { Scene target; if (SceneManager.TryGetScene(name, out target)) RemoveRegion(target, cleanUp); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="scene"></param> /// <returns></returns> public void CloseRegion(Scene scene) { // only need to check this if we are not at the // root level if ((SceneManager.CurrentScene != null) && (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { SceneManager.TrySetCurrentScene(".."); } SceneManager.CloseScene(scene); ShutdownClientServer(scene.RegionInfo); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="name"></param> /// <returns></returns> public void CloseRegion(string name) { Scene target; if (SceneManager.TryGetScene(name, out target)) CloseRegion(target); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene(RegionInfo regionInfo, out List<IClientNetworkServer> clientServer) { return SetupScene(regionInfo, 0, null, out clientServer); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="proxyOffset"></param> /// <param name="configSource"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene( RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out List<IClientNetworkServer> clientServer) { List<IClientNetworkServer> clientNetworkServers = null; AgentCircuitManager circuitManager = new AgentCircuitManager(); IPAddress listenIP = regionInfo.InternalEndPoint.Address; //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP)) // listenIP = IPAddress.Parse("0.0.0.0"); uint port = (uint) regionInfo.InternalEndPoint.Port; if (m_autoCreateClientStack) { clientNetworkServers = m_clientStackManager.CreateServers( listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource, circuitManager); } else { clientServer = null; } regionInfo.InternalEndPoint.Port = (int) port; Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager); if (m_autoCreateClientStack) { foreach (IClientNetworkServer clientnetserver in clientNetworkServers) { clientnetserver.AddScene(scene); } } clientServer = clientNetworkServers; scene.LoadWorldMap(); Vector3 regionExtent = new Vector3(regionInfo.RegionSizeX, regionInfo.RegionSizeY, regionInfo.RegionSizeZ); scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName, regionExtent); scene.PhysicsScene.RequestAssetMethod = scene.PhysicsRequestAsset; scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight); return scene; } protected override ClientStackManager CreateClientStackManager() { return new ClientStackManager(m_configSettings.ClientstackDll); } protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService, IEstateDataService estateDataService, AgentCircuitManager circuitManager) { SceneCommunicationService sceneGridService = new SceneCommunicationService(); return new Scene( regionInfo, circuitManager, sceneGridService, simDataService, estateDataService, Config, m_version); } protected void ShutdownClientServer(RegionInfo whichRegion) { // Close and remove the clientserver for a region bool foundClientServer = false; int clientServerElement = 0; Location location = new Location(whichRegion.RegionHandle); for (int i = 0; i < m_clientServers.Count; i++) { if (m_clientServers[i].HandlesRegion(location)) { clientServerElement = i; foundClientServer = true; break; } } if (foundClientServer) { m_clientServers[clientServerElement].Stop(); m_clientServers.RemoveAt(clientServerElement); } } protected virtual void HandleRestartRegion(RegionInfo whichRegion) { m_log.InfoFormat( "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})", whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY); ShutdownClientServer(whichRegion); IScene scene; CreateRegion(whichRegion, true, out scene); scene.Start(); } # region Setup methods protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier, Vector3 regionExtent) { return GetPhysicsScene( m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, Config, osSceneIdentifier, regionExtent); } /// <summary> /// Handler to supply the current status of this sim /// </summary> /// <remarks> /// Currently this is always OK if the simulator is still listening for connections on its HTTP service /// </remarks> public class SimStatusHandler : BaseStreamHandler { public SimStatusHandler() : base("GET", "/simstatus", "SimStatus", "Simulator Status") {} protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes("OK"); } public override string ContentType { get { return "text/plain"; } } } /// <summary> /// Handler to supply the current extended status of this sim /// Sends the statistical data in a json serialization /// </summary> public class XSimStatusHandler : BaseStreamHandler { OpenSimBase m_opensim; public XSimStatusHandler(OpenSimBase sim) : base("GET", "/" + Util.SHA1Hash(sim.osSecret), "XSimStatus", "Simulator XStatus") { m_opensim = sim; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public override string ContentType { get { return "text/plain"; } } } /// <summary> /// Handler to supply the current extended status of this sim to a user configured URI /// Sends the statistical data in a json serialization /// If the request contains a key, "callback" the response will be wrappend in the /// associated value for jsonp used with ajax/javascript /// </summary> protected class UXSimStatusHandler : BaseStreamHandler { OpenSimBase m_opensim; public UXSimStatusHandler(OpenSimBase sim) : base("GET", "/" + sim.userStatsURI, "UXSimStatus", "Simulator UXStatus") { m_opensim = sim; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public override string ContentType { get { return "text/plain"; } } } #endregion /// <summary> /// Performs any last-minute sanity checking and shuts down the region server /// </summary> protected override void ShutdownSpecific() { if (proxyUrl.Length > 0) { Util.XmlRpcCommand(proxyUrl, "Stop"); } m_log.Info("[SHUTDOWN]: Closing all threads"); m_log.Info("[SHUTDOWN]: Killing listener thread"); m_log.Info("[SHUTDOWN]: Killing clients"); m_log.Info("[SHUTDOWN]: Closing console and terminating"); try { SceneManager.Close(); } catch (Exception e) { m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e); } base.ShutdownSpecific(); } /// <summary> /// Get the start time and up time of Region server /// </summary> /// <param name="starttime">The first out parameter describing when the Region server started</param> /// <param name="uptime">The second out parameter describing how long the Region server has run</param> public void GetRunTime(out string starttime, out string uptime) { starttime = m_startuptime.ToString(); uptime = (DateTime.Now - m_startuptime).ToString(); } /// <summary> /// Get the number of the avatars in the Region server /// </summary> /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param> public void GetAvatarNumber(out int usernum) { usernum = SceneManager.GetCurrentSceneAvatars().Count; } /// <summary> /// Get the number of regions /// </summary> /// <param name="regionnum">The first out parameter describing the number of regions</param> public void GetRegionNumber(out int regionnum) { regionnum = SceneManager.Scenes.Count; } /// <summary> /// Create an estate with an initial region. /// </summary> /// <remarks> /// This method doesn't allow an estate to be created with the same name as existing estates. /// </remarks> /// <param name="regInfo"></param> /// <param name="estatesByName">A list of estate names that already exist.</param> /// <param name="estateName">Estate name to create if already known</param> /// <returns>true if the estate was created, false otherwise</returns> public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName) { // Create a new estate regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true); string newName; if (!string.IsNullOrEmpty(estateName)) newName = estateName; else newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName); if (estatesByName.ContainsKey(newName)) { MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName); return false; } regInfo.EstateSettings.EstateName = newName; // FIXME: Later on, the scene constructor will reload the estate settings no matter what. // Therefore, we need to do an initial save here otherwise the new estate name will be reset // back to the default. The reloading of estate settings by scene could be eliminated if it // knows that the passed in settings in RegionInfo are already valid. Also, it might be // possible to eliminate some additional later saves made by callers of this method. regInfo.EstateSettings.Save(); return true; } /// <summary> /// Load the estate information for the provided RegionInfo object. /// </summary> /// <param name="regInfo"></param> public bool PopulateRegionEstateInfo(RegionInfo regInfo) { if (EstateDataService != null) regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false); if (regInfo.EstateSettings.EstateID != 0) return false; // estate info in the database did not change m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName); List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll(); Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>(); foreach (EstateSettings estate in estates) estatesByName[estate.EstateName] = estate; string defaultEstateName = null; if (Config.Configs[ESTATE_SECTION_NAME] != null) { defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null); if (defaultEstateName != null) { EstateSettings defaultEstate; bool defaultEstateJoined = false; if (estatesByName.ContainsKey(defaultEstateName)) { defaultEstate = estatesByName[defaultEstateName]; if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID)) defaultEstateJoined = true; } else { if (CreateEstate(regInfo, estatesByName, defaultEstateName)) defaultEstateJoined = true; } if (defaultEstateJoined) return true; // need to update the database else m_log.ErrorFormat( "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName); } } // If we have no default estate or creation of the default estate failed then ask the user. while (true) { if (estates.Count == 0) { m_log.Info("[ESTATE]: No existing estates found. You must create a new one."); if (CreateEstate(regInfo, estatesByName, null)) break; else continue; } else { string response = MainConsole.Instance.CmdPrompt( string.Format( "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName), "yes", new List<string>() { "yes", "no" }); if (response == "no") { if (CreateEstate(regInfo, estatesByName, null)) break; else continue; } else { string[] estateNames = estatesByName.Keys.ToArray(); response = MainConsole.Instance.CmdPrompt( string.Format( "Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames)), estateNames[0]); List<int> estateIDs = EstateDataService.GetEstates(response); if (estateIDs.Count < 1) { MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again."); continue; } int estateID = estateIDs[0]; regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID); if (EstateDataService.LinkRegion(regInfo.RegionID, estateID)) break; MainConsole.Instance.Output("Joining the estate failed. Please try again."); } } } return true; // need to update the database } } public class OpenSimConfigSource { public IConfigSource Source; } }
using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Text; using System.Linq; using System.Linq.Expressions; namespace MonoDroid { public class NetProxyGenerator : CodeGenerator { static readonly string[] myKeywords = new string[] { "namespace", "in", "out", "checked", "params", "lock", "ref", "internal", "out", "object", "string", "bool" }; static readonly int myTypeCount = 3; static string[] myReplaceKeyword = new string[myKeywords.Length]; static string[] myStartKeywords = new string[myKeywords.Length]; static string[] myStartReplaceKeywords = new string[myKeywords.Length]; static string[] myEndKeywords = new string[myKeywords.Length]; static string[] myEndReplaceKeywords = new string[myKeywords.Length]; static string[] myContainKeywords = new string[myKeywords.Length]; static string[] myContainReplaceKeywords = new string[myKeywords.Length]; static string EscapeName(string name) { return EscapeName(name, true); } static string EscapeName(string name, bool doExactMatchOnTypes) { for (int i = 0; i < myKeywords.Length; i++) { var keyword = myStartKeywords[i]; if (!name.StartsWith(keyword)) continue; name = myStartReplaceKeywords[i] + name.Substring(keyword.Length); break; } for (int i = 0; i < myKeywords.Length; i++) { var keyword = myEndKeywords[i]; if (!name.EndsWith(keyword)) continue; name = name.Substring(0, name.Length - keyword.Length) + myEndReplaceKeywords[i]; break; } for (int i = 0; i < myKeywords.Length; i++) { var keyword = myContainKeywords[i]; if (!name.Contains(keyword)) continue; name = name.Replace(keyword, myContainReplaceKeywords[i]); } for (int i = 0; i < (doExactMatchOnTypes ? myKeywords.Length : myKeywords.Length - myTypeCount); i++) { if (name != myKeywords[i]) continue; name = myReplaceKeyword[i]; } return name; } public Type FindType(string typeName) { if (typeName == null) return null; typeName = typeName.TrimEnd(']', '['); return myModel.FindType(typeName); } public void AddAllTypes(ObjectModel model, HashSet<Type> hash, Type type) { if (type == null) return; if (hash.Contains(type)) return; hash.Add(type); AddAllTypes(model, hash, FindType(type.Name + "Constants")); AddAllTypes(model, hash, type.ParentType); foreach (var iface in type.InterfaceTypes) { AddAllTypes(model, hash, iface); } foreach (var field in type.Fields) { AddAllTypes(model, hash, FindType(field.Type)); } foreach (var method in type.Methods) { AddAllTypes(model, hash, method.ReturnType ?? FindType(method.Return)); foreach (var par in method.Parameters) AddAllTypes(model, hash, FindType(par)); } } ObjectModel myModel; HashSet<Type> myTypesOfInterest = new HashSet<Type>(); protected override void Prepare (ObjectModel model) { myModel = model; var androidTypes = from type in myModel.Types where (type.Name.StartsWith("android.") || type.Name.StartsWith("java.")) && (!type.Name.StartsWith("android.test.")) select type; foreach (var type in androidTypes) { AddAllTypes(myModel, myTypesOfInterest, type); } foreach (var type in model.Types) { type.Name = EscapeName(type.Name); foreach (var method in type.Methods) { method.Name = EscapeName(method.Name); for (int i = 0; i < method.Parameters.Count; i++) { method.Parameters[i] = EscapeName(method.Parameters[i], false); } if (method.Return != null) { method.Return = EscapeName(method.Return, false); } } if (type.Parent != null) type.Parent = EscapeName(type.Parent); for (int i = 0; i < type.Interfaces.Count; i++) { type.Interfaces[i] = EscapeName(type.Interfaces[i]); } for (int i = 0; i < type.Fields.Count; i++) { type.Fields[i].Name = EscapeName(type.Fields[i].Name); type.Fields[i].Type = EscapeName(type.Fields[i].Type, false); } } } static NetProxyGenerator() { for (int i = 0; i < myKeywords.Length; i++) { string keyword = myKeywords[i]; myReplaceKeyword[i] = '@' + keyword; myStartKeywords[i] = keyword + '.'; myStartReplaceKeywords[i] = '@' + keyword + '.'; myEndKeywords[i] = '.' + keyword; myEndReplaceKeywords[i] = ".@" + keyword; myContainKeywords[i] = '.' + keyword + '.'; myContainReplaceKeywords[i] = ".@" + keyword + '.'; } } protected override void BeginNamespace (Type type) { WriteLine("namespace {0}", type.Namespace); WriteLine("{"); } protected override string GetFilePath (Type type) { var file = Path.Combine(type.Namespace.Replace('.', Path.DirectorySeparatorChar), type.SimpleName + ".cs").Replace("@", string.Empty); return Path.Combine("generated", file); } protected override bool BeginType (Type type) { myInitJni.Clear(); if (!myTypesOfInterest.Contains(type)) return false; if (type.WrappedInterface == null) { if (type.IsInterface) { WriteLine("[global::MonoJavaBridge.JavaInterface(typeof(global::{0}_))]", type.Name); } else if (type.Abstract) { WriteLine("[global::MonoJavaBridge.JavaClass(typeof(global::{0}_))]", type.Name); } else if (!type.NoAttributes) { WriteLine("[global::MonoJavaBridge.JavaClass()]"); } } else { WriteLine("[global::MonoJavaBridge.JavaProxy(typeof(global::{0}))]", type.Name.Substring(0, type.Name.Length - 1)); } Write(type.Scope); if (type.IsNew) Write("new"); if (type.Abstract && !type.IsInterface) Write("abstract"); if (type.IsSealed) Write("sealed"); if (type.Static) Write("static"); if (type.IsInterface) Write("partial interface {0}", type.SimpleName); else Write("partial class {0}", type.SimpleName); if (type.Parent != null || type.Interfaces.Count > 0) Write(":"); if (type.IsInterface && type.Interfaces.Count == 0) Write(" : global::MonoJavaBridge.IJavaObject"); if (type.Parent != null) { if (type.Name != "java.lang.Throwable") Write(type.Parent, false); else Write("global::MonoJavaBridge.JavaException", false); } if (!type.IsInterface && type.Interfaces.Count > 0) { Write(","); } WriteDelimited(type.InterfaceTypes, (v, i) => type.Qualifier.StartsWith(v.Qualifier) ? v.SimpleName : v.Name, ","); WriteLine(); WriteLine("{"); if (!type.IsInterface && !type.Static) { myIndent++; WriteLine("internal {0}static global::MonoJavaBridge.JniGlobalHandle staticClass;", type.Parent == null ? "" : "new "); /* if (!type.HasEmptyConstructor) { WriteLine("public {0}(){{}}", type.SimpleName); } */ WriteLine("{1} {0}(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)", type.SimpleName, type.IsSealed ? "internal" : "protected"); WriteLine("{"); WriteLine("}"); myIndent--; } return true; } /* void AddAllTypes(Type type, HashSet<Type> types) { if (type == null) return; if (types.Contains(type)) return; types.Add(type, types); AddAllTypes(type.ParentType); foreach (var i in type.Interfaces) { AddAllTypes(i, types); } } */ void AddAllInterfaces(Type interfaceType, HashSet<Type> interfaces) { if (!interfaces.Contains(interfaceType)) interfaces.Add(interfaceType); foreach (var i in interfaceType.InterfaceTypes) { AddAllInterfaces(i, interfaces); } } void GenerateInterfaceStubs(Type interfaceType) { WriteLine(); Type wrapperType = new Type(); wrapperType.WrappedInterface = interfaceType.Name; wrapperType.WrappedInterfaceType = interfaceType; wrapperType.Name = interfaceType.Name + "_"; wrapperType.Scope = interfaceType.Scope; wrapperType.IsSealed = true; if (interfaceType.IsInterface) { wrapperType.Parent = "java.lang.Object"; wrapperType.ParentType = myModel.FindType("java.lang.Object"); wrapperType.Interfaces.Add(interfaceType.Name); wrapperType.InterfaceTypes.Add(interfaceType); wrapperType.Scope = "internal"; var h = new HashSet<Type>(); AddAllInterfaces(interfaceType, h); foreach (var i in h) { foreach (var m in i.Methods) { var mc = new Method(); mc.Type = wrapperType; mc.Name = i.Name + "." + m.Name; mc.Parameters.AddRange(m.Parameters); mc.ParameterTypes.AddRange(m.ParameterTypes); mc.Return = m.Return; mc.ReturnType = m.ReturnType; if (!wrapperType.Methods.Contains(mc)) wrapperType.Methods.Add(mc); } } } else { wrapperType.Scope = "internal"; wrapperType.Parent = interfaceType.Name; wrapperType.ParentType = interfaceType; var curType = interfaceType; var allImplementedMethods = new Methods(); while (curType != null) { foreach (var m in curType.Methods) { if (!m.Abstract) { if (!allImplementedMethods.Contains(m)) allImplementedMethods.Add(m); continue; } if (allImplementedMethods.Contains(m)) continue; var mc = new Method(); mc.Type = wrapperType; mc.Name = m.Name; mc.Scope = m.Scope; mc.IsOverride = true; mc.Parameters.AddRange(m.Parameters); mc.ParameterTypes.AddRange(m.ParameterTypes); mc.Return = m.Return; mc.ReturnType = m.ReturnType; if (!wrapperType.Methods.Contains(mc)) wrapperType.Methods.Add(mc); } curType = curType.ParentType; } } myIndent--; myTypesOfInterest.Add(wrapperType); GenerateType(wrapperType); myIndent++; if (interfaceType.IsDelegate) { WriteLine(); var delegateMethod = interfaceType.Methods.First(); Write("public delegate {0} {1}Delegate(", false, delegateMethod.Return, interfaceType.SimpleName); WriteDelimited(delegateMethod.Parameters, (v, i) => string.Format("{0} arg{1}", v, i), ","); WriteLine(");"); WriteLine(); var delegateWrapper = new Type(); myTypesOfInterest.Add(delegateWrapper); delegateWrapper.Name = interfaceType.Name + "DelegateWrapper"; delegateWrapper.NativeName = interfaceType.NativeName.Replace('$', '_') + "DelegateWrapper"; if (delegateWrapper.NativeName.StartsWith("java.")) delegateWrapper.NativeName = delegateWrapper.NativeName.Replace("java.", "internal.java."); delegateWrapper.HasEmptyConstructor = true; delegateWrapper.Scope = "internal"; delegateWrapper.Parent = "java.lang.Object"; delegateWrapper.ParentType = myModel.FindType("java.lang.Object"); delegateWrapper.NoAttributes = true; var constructor = new Method(); constructor.IsConstructor = true; constructor.Scope = "public"; constructor.Type = delegateWrapper; constructor.Name = delegateWrapper.SimpleName; delegateWrapper.Methods.Add(constructor); delegateWrapper.Interfaces.Add(interfaceType.Name); delegateWrapper.InterfaceTypes.Add(interfaceType); myIndent--; GenerateType(delegateWrapper); myIndent++; //WriteLine("[global::MonoJavaBridge.JavaDelegateProxy]"); WriteLine("internal partial class {0}", delegateWrapper.SimpleName); WriteLine("{"); myIndent++; WriteLine("private {0}Delegate myDelegate;", interfaceType.SimpleName); Write("public {0} {1}(", false, delegateMethod.Return, delegateMethod.Name); WriteDelimited(delegateMethod.Parameters, (v, i) => string.Format("{0} arg{1}", v, i), ","); WriteLine(")"); WriteLine("{"); myIndent++; if (delegateMethod.Return != "void") Write("return myDelegate(", false); else Write("myDelegate(", false); WriteDelimited(delegateMethod.Parameters, (v, i) => string.Format("arg{0}", i), ","); WriteLine(");"); myIndent--; WriteLine("}"); WriteLine("public static implicit operator {0}({1}Delegate d)", delegateWrapper.SimpleName, interfaceType.SimpleName); WriteLine("{"); myIndent++; WriteLine("global::{0} ret = new global::{0}();", delegateWrapper.Name); WriteLine("ret.myDelegate = d;"); WriteLine("global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);"); WriteLine("return ret;"); myIndent--; WriteLine("}"); myIndent--; WriteLine("}"); } } protected override void EndType (Type type) { if (type.IsInterface || type.Static) { myInitJni.Clear(); base.EndType(type); if (type.IsInterface) GenerateInterfaceStubs(type); return; } myIndent++; WriteLine("static {0}()", type.SimpleName); WriteLine("{"); myIndent++; WriteLine("global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;"); if (type.WrappedInterface == null) WriteLine("global::{0}.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"{1}\"));", type.Name, GetJavaName(type).Replace('.', '/')); else WriteLine("global::{0}.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"{1}\"));", type.Name, GetJavaName(type.WrappedInterfaceType).Replace('.', '/')); foreach (var initJni in myInitJni) { WriteLine(initJni); } myIndent--; WriteLine("}"); /* WriteLine("internal static void InitJNI()"); WriteLine("{"); WriteLine("}"); */ myIndent--; myInitJni.Clear(); base.EndType(type); if (type.Abstract) GenerateInterfaceStubs(type); } public static string GetFieldStatement(string typeName, Type type) { if (typeName == "void") return "@__env.Call{0}VoidMethod({1});"; switch (typeName) { case "bool": return "return @__env.Get{0}BooleanField({1});"; case "int": return "return @__env.Get{0}IntField({1});"; case "double": return "return @__env.Get{0}DoubleField({1});"; case "float": return "return @__env.Get{0}FloatField({1});"; case "short": return "return @__env.Get{0}ShortField({1});"; case "long": return "return @__env.Get{0}LongField({1});"; case "char": return "return @__env.Get{0}CharField({1});"; case "byte": return "return @__env.Get{0}ByteField({1});"; } StringBuilder ret = new StringBuilder(); if (typeName.EndsWith("[]")) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<{0}>", typeName.Substring(0, typeName.Length - 2)); else if (type.IsInterface) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::{0}>", typeName); else if (!type.IsSealed) ret.Append("return global::MonoJavaBridge.JavaBridge.WrapJavaObject"); else ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<{0}>", typeName); ret.Append("(@__env.Get{0}ObjectField({1}))"); ret.AppendFormat(" as {0};", typeName); return ret.ToString(); } List<string> myInitJni = new List<string>(); int myMemberCounter = 0; protected override void EmitField (Field field) { if (field.Scope == "protected") return; bool hasValue = !string.IsNullOrEmpty(field.Value); var containingType = field.ContainingType; if (containingType.Static) containingType = FindType(containingType.Name.Substring(0, containingType.Name.Length - "Constants".Length).Replace("@", string.Empty)); var fieldId = string.Format("_{0}{1}", field.Name.Replace("@",""), myMemberCounter++); var signature = GetSignature(field.FieldType, field.Type); string initJni = string.Format("global::{0}.{1} = @__env.Get{4}FieldIDNoThrow(global::{0}.staticClass, \"{2}\", \"{3}\");", containingType.Name, fieldId, field.Name, signature, field.Static ? "Static" : string.Empty); if (!hasValue) { WriteLine("internal static global::MonoJavaBridge.FieldId {0};", fieldId); myInitJni.Add(initJni); } Write(field.Scope); if (field.Static) Write("static"); Write("{0}{1}", ObjectModel.IsSystemType(field.Type) ? string.Empty : "global::", field.Type); Write(field.Name, false); WriteLine(); WriteLine("{"); myIndent++; WriteLine("get"); WriteLine("{"); if (hasValue) { myIndent++; string val = field.Value; val = val.Replace("\\" , "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n"); if (field.Type == "java.lang.String") { Write("return \"{0}\"", false, val); } else if (field.Type == "char") { val = val.Replace("'", "\\'"); // there's a weird compile error happening here due to unicode chars or something... if (field.Name == "HEX_INPUT" || field.Name == "PICKER_DIALOG_INPUT") val = "0"; Write("return '{0}'", false, val); } else { Write("return {0}", false, field.Value); } if (field.Type == "long") Write("L", false); else if (field.Type == "float") Write("f", false); WriteLine(";"); myIndent--; } else { myIndent++; WriteLine("global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;"); string fieldStatement = GetFieldStatement(field.Type, field.FieldType); if (field.Static) { var contents = string.Format("global::{0}{2}.staticClass, {1}", containingType.Name, fieldId, containingType.IsInterface ? "_" : string.Empty); WriteLine(fieldStatement, "Static", contents); } else { var contents = string.Format("this.JvmHandle, {0}", fieldId); WriteLine(fieldStatement, string.Empty, contents); } //WriteLine("return default({0}{1});", ObjectModel.IsSystemType(field.Type) ? string.Empty : "global::", field.Type); myIndent--; } WriteLine("}"); if (!field.IsReadOnly) { WriteLine("set"); WriteLine("{"); WriteLine("}"); } myIndent--; WriteLine("}"); } public static string GetMethodSignature(Method method) { StringBuilder ret = new StringBuilder(); ret.Append('('); for (int i = 0; i < method.Parameters.Count; i++) { var typeName = method.Parameters[i]; var type = method.ParameterTypes[i]; ret.Append(GetSignature(type, typeName)); } ret.Append(')'); ret.Append(GetSignature(method.ReturnType, method.Return)); return ret.ToString(); } public static string GetJavaName(Type type) { if (type.NativeName != null) return type.NativeName; string typeName = type.SimpleName; var root = type; while (root.NestingClass != null) { typeName = root.NestingClass.SimpleName + "$" + typeName; root = root.NestingClass; } typeName = root.Namespace + "." + typeName; return typeName; } public static string GetSignature(Type type, string typeName) { if (type == null && typeName == null) return "V"; if (type != null) typeName = GetJavaName(type); typeName = typeName.Replace('_', '$'); string low = typeName.ToLowerInvariant(); int arr = low.LastIndexOf("["); string array = ""; while (arr != -1) { array += "["; low = low.Substring(0, arr); arr = low.LastIndexOf("["); } switch (low) { case "bool": return array + "Z"; case "int": return array + "I"; case "double": return array + "D"; case "float": return array + "F"; case "short": return array + "S"; case "long": return array + "J"; case "char": return array + "C"; case "byte": return array + "B"; case "void": return array + "V"; default: return array + "L" + typeName.Substring(0, low.Length).Replace('.', '/') + ";"; } } public static string GetMethodStatement(Method method) { if (method.IsConstructor) return "global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject({1});"; var type = method.ReturnType; var typeName = method.Return; if (typeName == "void") return "@__env.Call{0}VoidMethod({1});"; switch (typeName) { case "bool": return "return @__env.Call{0}BooleanMethod({1});"; case "int": return "return @__env.Call{0}IntMethod({1});"; case "double": return "return @__env.Call{0}DoubleMethod({1});"; case "float": return "return @__env.Call{0}FloatMethod({1});"; case "short": return "return @__env.Call{0}ShortMethod({1});"; case "long": return "return @__env.Call{0}LongMethod({1});"; case "char": return "return @__env.Call{0}CharMethod({1});"; case "byte": return "return @__env.Call{0}ByteMethod({1});"; } StringBuilder ret = new StringBuilder(); if (method.IsConstructor || method.Static) // || method.Type.IsSealed { if (method.Return.EndsWith("[]")) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<{0}>", method.Return.Substring(0, method.Return.Length - 2)); else if (method.ReturnType.IsInterface) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::{0}>", method.Return); else if (!type.IsSealed) ret.Append("return global::MonoJavaBridge.JavaBridge.WrapJavaObject"); else ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<{0}>", typeName); ret.Append("(@__env.Call{0}ObjectMethod({1}))"); } else { string callType = null; string templateArg = string.Empty; if (method.Return.EndsWith("[]")) { templateArg = "<" + method.Return.Substring(0, method.Return.Length - 2) + ">"; callType = "Array"; } else if (method.ReturnType.IsInterface) { templateArg = "<" + method.Return + ">"; callType = "IJava"; } else if (!type.IsSealed) { callType = string.Empty; } else { templateArg = "<" + method.Return + ">"; callType = "SealedClass"; } ret.Append("return global::MonoJavaBridge.JavaBridge.Call{0}" + callType + "ObjectMethod" + templateArg + "({1})"); } ret.AppendFormat(" as {0};", method.Return); return ret.ToString(); } public string GetParameterStatement(Type parameterType, string parameter) { return "ConvertToValue({0})"; } protected string GetOverloadedType(Type type) { if (type == null) return null; if (type.Name == "java.lang.CharSequence") return "string"; if (type.IsDelegate) return "global::" + type.Name + "Delegate"; return null; } protected List<string> GetOverloadedDelegateTypes(Method method) { List<string> ret = new List<string>(); bool hasOverload = false; for (int i = 0; i < method.Parameters.Count; i++) { var type = method.ParameterTypes[i]; var overload = GetOverloadedType(type); if (overload == null) { ret.Add(method.Parameters[i]); } else { hasOverload = true; ret.Add(overload); } } if (!hasOverload) return null; return ret; } private string FixCasing(Method method) { return method.Name; // this causes all sorts of fun errors. For example, java has a type called Format, which has a method called format. /* if (method.IsConstructor) return method.Name; string name = method.Name; int index = name.LastIndexOf('.'); if (index == -1) index = 0; else index++; if (char.IsUpper(name[index])) return name; var ret = name.Substring(0, index) + char.ToUpper(name[index]) + (index == name.Length - 1 ? string.Empty : name.Substring(index + 1)); if (!method.Type.IsInterface && ret == method.Type.SimpleName) return method.Name; if (FindType(method.Type.Name + "." + ret) != null) return method.Name; return ret; */ } protected override void EmitMethod (Method method) { if (method.IsSynthetic) return; if (method.IsOverride && !method.IsConstructor && !method.Abstract && !method.Static) { Type parent = method.Type.ParentType; while (parent != null) { parent = parent.ParentType; } } if (method.PropertyType.HasValue && (method.Name.StartsWith("get") || (method.Name.StartsWith("set") && method.PropertyType == PropertyType.WriteOnly))) { var propertyType = method.PropertyType.Value; if (method.Scope != null) Write(method.Scope); if (method.Static) Write("static"); else Write("new"); var overload = GetOverloadedType(method.ReturnType); var returnType = propertyType == PropertyType.WriteOnly ? method.Parameters[0] : method.Return; if (overload == null) Write("{0}{1}", ObjectModel.IsSystemType(returnType) ? string.Empty : "global::", returnType); else Write(overload); WriteLine(method.Name.Substring(3), false); WriteLine("{"); myIndent++; if (propertyType == PropertyType.ReadWrite || propertyType == PropertyType.ReadOnly) { WriteLine("get"); WriteLine("{"); myIndent++; if (overload == "string") WriteLine("return get{0}().toString();", method.Name.Substring(3)); else if (overload != null) WriteLine("return new {0}(get{1}().{2});", overload, method.Name.Substring(3), method.ReturnType.Methods.First().Name); else WriteLine("return get{0}();", method.Name.Substring(3)); myIndent--; WriteLine("}"); } if (propertyType == PropertyType.ReadWrite || propertyType == PropertyType.WriteOnly) { WriteLine("set"); WriteLine("{"); myIndent++; if (overload == "string") WriteLine("set{0}((global::java.lang.CharSequence)(global::java.lang.String)value);", method.Name.Substring(3)); else WriteLine("set{0}(value);", method.Name.Substring(3)); myIndent--; WriteLine("}"); } myIndent--; WriteLine("}"); } String initJni = null; string methodId = null; string signature = null; String methodIdLookup = null; if (!method.Type.IsInterface) { if (!method.Static && method.Parameters.Count == 0 && ((method.Name == "iterator" && method.Scope == "public") || method.Name == "java.lang.Iterable.iterator")) { WriteLine("public global::System.Collections.IEnumerator GetEnumerator()"); WriteLine("{"); myIndent++; if (method.Name == "iterator") WriteLine("return global::java.lang.IterableHelper.WrapIterator(iterator());"); else WriteLine("return global::java.lang.IterableHelper.WrapIterator(((global::java.lang.Iterable)this).iterator());"); myIndent--; WriteLine("}"); } signature = GetMethodSignature(method); if (method.Name.LastIndexOf('.') == -1) methodId = method.Name; else methodId = method.Name.Substring(method.Name.LastIndexOf('.') + 1); methodIdLookup = methodId; methodId = methodId.Replace("@", string.Empty); methodId = string.Format("_m{0}", method.Index); /* methodId = string.Format("_{0}{1}", methodId.Replace("@",""), myMemberCounter++); */ initJni = string.Format("global::{0}.{1} = @__env.Get{4}MethodIDNoThrow(global::{0}.staticClass, \"{2}\", \"{3}\");", method.Type.Name, methodId, method.IsConstructor ? "<init>" : methodIdLookup, signature, method.Static ? "Static" : string.Empty); //myInitJni.Add(initJni); WriteLine("private static global::MonoJavaBridge.MethodId {0};", methodId); if (method.Scope != null) Write(method.Scope); if (method.Abstract) Write("abstract"); else { if (method.Static) { Write("static"); } else if (!method.IsConstructor) { if (method.IsOverride && method.Type.Name != "java.lang.Throwable") { if (method.IsSealed) Write("sealed"); Write("override"); } else if (!method.Type.IsSealed && method.Scope != string.Empty) Write("virtual"); } } } if (method.Return != null) Write("{0}{1}", ObjectModel.IsSystemType(method.Return) ? string.Empty : "global::", method.Return); Write(FixCasing(method), false); Write("(", false); WriteDelimited(method.Parameters, (v, i) => string.Format("{0} arg{1}", v, i), ","); if (method.Type.IsInterface || method.Abstract || method.Scope == "internal") { WriteLine(");"); } else { Write(")", false); if (method.IsConstructor) WriteLine(" : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)"); else WriteLine(); WriteLine("{"); myIndent++; if (method.IsConstructor || method.Static) { WriteLine("global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;"); WriteLine("if (global::{0}.{1}.native == global::System.IntPtr.Zero)", method.Type.Name, methodId); myIndent++; WriteLine(initJni); myIndent--; } var statement = GetMethodStatement(method); StringBuilder parBuilder = new StringBuilder(); if (method.Static || method.IsConstructor) parBuilder.AppendFormat("{0}.staticClass, ", method.Type.Name); else parBuilder.Append("this.JvmHandle, "); parBuilder.AppendFormat("global::{0}.{1}", method.Type.Name, methodId); //if (method.IsConstructor) // parBuilder.Append(", this"); bool hasCharSequenceArgument = false; for (int i = 0; i < method.Parameters.Count; i++) { parBuilder.Append(", "); var parType = method.ParameterTypes[i]; var par = method.Parameters[i]; if (par == "java.lang.CharSequence") hasCharSequenceArgument = true; parBuilder.Append("global::MonoJavaBridge.JavaBridge."); parBuilder.Append(string.Format(GetParameterStatement(parType, par), "arg" + i)); } if (method.Static || method.IsConstructor) { WriteLine(statement, method.Static ? "Static" : string.Empty, parBuilder); if (method.IsConstructor) WriteLine("Init(@__env, handle);"); } else { if (false)//method.Type.IsSealed) { if (method.Type.WrappedInterface != null) WriteLine(statement, string.Empty, parBuilder); else WriteLine(statement, "NonVirtual", string.Format(parBuilder.ToString().Replace("this.JvmHandle, ", "this.JvmHandle, global::{0}.staticClass, "), method.Type.Name)); } else { var s = string.Format(statement, string.Empty, string.Format(parBuilder.ToString().Replace("this.JvmHandle, ", "this, global::{0}.staticClass, \"{1}\", \"{2}\", ref "), method.Type.Name, methodIdLookup, signature)); s = s.Replace("@__env.", "global::MonoJavaBridge.JavaBridge."); WriteLine(s); } /* if (!method.Type.IsSealed || method.Type.WrappedInterface != null) { if (method.Type.WrappedInterface == null) { WriteLine("if (!IsClrObject)", method.Type.Name); myIndent++; } WriteLine(statement, string.Empty, parBuilder); if (method.Type.WrappedInterface == null) { myIndent--; WriteLine("else"); myIndent++; } } if (method.Type.WrappedInterface == null) WriteLine(statement, "NonVirtual", string.Format(parBuilder.ToString().Replace("this.JvmHandle, ", "this.JvmHandle, global::{0}.staticClass, "), method.Type.Name)); if (!method.Type.IsSealed && method.Type.WrappedInterface == null) myIndent--; */ } myIndent--; WriteLine("}"); var overloads = GetOverloadedDelegateTypes(method); if ((overloads != null || hasCharSequenceArgument) && !method.IsConstructor && !string.IsNullOrEmpty(method.Scope)) { var em = method; //myExtensionMethods.Add(method); Write(method.Scope); if (method.Static) Write("static"); Write("{0} {1}(", false, em.Return, em.Name); //Write("this global::{0} __this", false, em.Type.Name); WriteDelimited(em.Parameters, (v, i) => string.Format("{0} arg{1}", v == "java.lang.CharSequence" ? "string" : overloads != null ? overloads[i] : v, i), ","); WriteLine(")"); WriteLine("{"); myIndent++; if (em.Return != "void") Write("return"); Write("{0}(", false, em.Name); WriteDelimited(em.Parameters, (v, i) => string.Format("{0}arg{1}", v == "java.lang.CharSequence" ? "(global::java.lang.CharSequence)(global::java.lang.String)" : overloads != null ? overloads[i] != em.Parameters[i] ? string.Format("({0}Wrapper)", overloads[i]) : string.Empty : string.Empty, i), ","); WriteLine(");"); myIndent--; WriteLine("}"); } } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXORULE { using System; using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// Address book EntryIDs can represent several types of Address Book objects including individual users, distribution lists, containers, and templates. /// </summary> public class AddressBookEntryID { /// <summary> /// MUST be 0x00000000. /// </summary> public readonly uint Flags = 0x00000000; /// <summary> /// The ProviderUID value that MUST be %xDC.A7.40.C8.C0.42.10.1A.B4.B9.08.00.2B.2F.E1.82. /// </summary> public readonly byte[] ProviderUID = new byte[] { 0xDC, 0xA7, 0x40, 0xC8, 0xC0, 0x42, 0x10, 0x1A, 0xB4, 0xB9, 0x08, 0x00, 0x2B, 0x2F, 0xE1, 0x82 }; /// <summary> /// MUST be set to %x01.00.00.00. /// </summary> public readonly uint Version = 0x00000001; /// <summary> /// A 32-bit integer representing the type of the object. /// </summary> private ObjectTypes type; /// <summary> /// The X500 DN of the Address Book object. X500DN is a null-terminated string of 8-bit characters. /// </summary> private string valueOfX500DN; /// <summary> /// Initializes a new instance of the AddressBookEntryID class. /// </summary> public AddressBookEntryID() { } /// <summary> /// Initializes a new instance of the AddressBookEntryID class. /// </summary> /// <param name="valueOfx500DN">The X500 DN of the Address Book object. This must not be a null-terminated string.</param> public AddressBookEntryID(string valueOfx500DN) { this.Type = ObjectTypes.LocalMailUser; this.valueOfX500DN = valueOfx500DN; } /// <summary> /// Initializes a new instance of the AddressBookEntryID class. /// </summary> /// <param name="valueOfx500DN">The X500 DN of the Address Book object. This must not be a null-terminated string.</param> /// <param name="types">Type of object.</param> public AddressBookEntryID(string valueOfx500DN, ObjectTypes types) { this.Type = types; this.valueOfX500DN = valueOfx500DN; } /// <summary> /// A 32-bit integer representing the type of the object. /// </summary> public enum ObjectTypes : uint { /// <summary> /// Local mail user type /// </summary> LocalMailUser = 0x0000, /// <summary> /// Distribution list type /// </summary> DistributionList = 0x0001, /// <summary> /// Bulletin board or public folder type /// </summary> BulletinBoardOrPublicFolder = 0x0002, /// <summary> /// Automated mailbox type /// </summary> AutomatedMailbox = 0x0003, /// <summary> /// Organizational mailbox type /// </summary> OrganizationalMailbox = 0x0004, /// <summary> /// Private distribution list type /// </summary> PrivateDistributionList = (ushort)PropertyId.PidTagAutoForwarded, /// <summary> /// Remote mail user type /// </summary> RemoteMailUser = 0x0006, /// <summary> /// Container type /// </summary> Container = 0x0100, /// <summary> /// Template type /// </summary> Template = 0x0101, /// <summary> /// One-off user type /// </summary> OneOffUser = 0x0102, /// <summary> /// Search type /// </summary> Search = 0x0200 } /// <summary> /// Gets or sets the X500 DN of the Address Book object. X500DN is a null-terminated string of 8-bit characters. /// </summary> public string ValueOfX500DN { get { return this.valueOfX500DN; } set { this.valueOfX500DN = value; } } /// <summary> /// Gets or sets a 32-bit integer representing the type of the object. /// </summary> public ObjectTypes Type { get { return this.type; } set { this.type = value; } } /// <summary> /// Get size of this class /// </summary> /// <returns>Size in byte of this class.</returns> public int Size() { return this.Serialize().Length; } /// <summary> /// Get serialized byte array for this struct /// </summary> /// <returns>Serialized byte array.</returns> public byte[] Serialize() { List<byte> bytes = new List<byte>(); bytes.AddRange(BitConverter.GetBytes(this.Flags)); bytes.AddRange(this.ProviderUID); bytes.AddRange(BitConverter.GetBytes(this.Version)); bytes.AddRange(BitConverter.GetBytes((uint)this.Type)); bytes.AddRange(Encoding.ASCII.GetBytes(this.valueOfX500DN + "\0")); return bytes.ToArray(); } /// <summary> /// Deserialized byte array to an ActionBlock instance /// </summary> /// <param name="buffer">Byte array contain data of an ActionBlock instance.</param> /// <returns>Bytes count that deserialized in buffer.</returns> public uint Deserialize(byte[] buffer) { BufferReader reader = new BufferReader(buffer); uint flags = reader.ReadUInt32(); if (this.Flags != flags) { throw new ParseException("Flags MUST be 0x00000000."); } byte[] providerUID = reader.ReadBytes(16); if (!Common.CompareByteArray(this.ProviderUID, providerUID)) { throw new ParseException("ProviderUID MUST be %xDC.A7.40.C8.C0.42.10.1A.B4.B9.08.00.2B.2F.E1.82."); } uint version = reader.ReadUInt32(); if (this.Version != version) { throw new ParseException("Version MUST be 0x00000001."); } this.Type = (ObjectTypes)reader.ReadUInt32(); this.valueOfX500DN = reader.ReadASCIIString(); return reader.Position; } } }
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; using NuGet; using Pomona.Common; namespace Pomona.CodeGen { public class TypeDefinitionCloner { // Copies a self-contained class or several classes, with templating possibilities private readonly ModuleDefinition destinationModule; private readonly Dictionary<FieldReference, FieldReference> fieldMap = new Dictionary<FieldReference, FieldReference>(); private readonly Dictionary<MethodReference, MethodReference> methodMap = new Dictionary<MethodReference, MethodReference>(); private readonly Dictionary<PropertyReference, PropertyReference> propertyMap = new Dictionary<PropertyReference, PropertyReference>(); private readonly Dictionary<TypeReference, TypeReference> typeMap = new Dictionary<TypeReference, TypeReference>(); public TypeDefinitionCloner(ModuleDefinition destinationModule) { this.destinationModule = destinationModule; } public TypeDefinition Clone(TypeDefinition sourceType) { if (sourceType.HasGenericParameters) throw new NotSupportedException("Does not yet support cloning types having generic parameters"); if (sourceType.HasNestedTypes) throw new NotSupportedException("Does not support cloning types having nested types."); var destType = new TypeDefinition( sourceType.Namespace, sourceType.Name, sourceType.Attributes); this.destinationModule.Types.Add(destType); this.typeMap[sourceType] = destType; if (sourceType.BaseType != null) destType.BaseType = Import(sourceType.BaseType); foreach (var sourceInteface in sourceType.Interfaces) destType.Interfaces.Add(Import(sourceInteface)); foreach (var sourceField in sourceType.Fields) { var destField = new FieldDefinition(sourceField.Name, sourceField.Attributes, Import(sourceField.FieldType)); destType.Fields.Add(destField); this.fieldMap[sourceField] = destField; CopyAttributes(sourceField, destField); if (sourceField.HasConstant) throw new NotImplementedException("Can't copy constant field"); } var methodParamMap = new Dictionary<ParameterDefinition, ParameterDefinition>(); foreach (var sourceMethod in sourceType.Methods) CopyMethodDeclaration(sourceMethod, destType, methodParamMap); foreach (var sourceMethod in sourceType.Methods) CopyMethodBody(sourceMethod, methodParamMap); foreach (var sourceProp in sourceType.Properties) CopyProperty(sourceProp, destType); return destType; } private CustomAttribute Clone(CustomAttribute sourceAttribute) { return new CustomAttribute(Import(sourceAttribute.Constructor), sourceAttribute.GetBlob()); } private void CopyAttributes(ICustomAttributeProvider source, ICustomAttributeProvider destination) { destination.CustomAttributes.AddRange(source.CustomAttributes.Select(Clone)); } private void CopyExceptionHandlers(ExceptionHandler sourceHandler, Dictionary<Instruction, Instruction> instMap, MethodBody destBody) { var destHandler = new ExceptionHandler(sourceHandler.HandlerType) { CatchType = sourceHandler.CatchType != null ? Import(sourceHandler.CatchType) : null, FilterStart = MapInstructionSafe(instMap, sourceHandler.FilterStart), HandlerStart = MapInstructionSafe(instMap, sourceHandler.HandlerStart), HandlerEnd = MapInstructionSafe(instMap, sourceHandler.HandlerEnd), TryStart = MapInstructionSafe(instMap, sourceHandler.TryStart), TryEnd = MapInstructionSafe(instMap, sourceHandler.TryEnd) }; destBody.ExceptionHandlers.Add(destHandler); } private void CopyMethodBody(MethodDefinition sourceMethod, Dictionary<ParameterDefinition, ParameterDefinition> methodParamMap) { var destMethod = (MethodDefinition)this.methodMap[sourceMethod]; var varMap = new Dictionary<VariableDefinition, VariableDefinition>(); var postActions = new List<Action>(); var nopInstruction = Instruction.Create(OpCodes.Nop); var instMap = new Dictionary<Instruction, Instruction>(); if (sourceMethod.HasBody) { var destBody = destMethod.Body; var sourceBody = sourceMethod.Body; foreach (var sourceVar in sourceBody.Variables) { var destVar = new VariableDefinition(sourceVar.Name, Import(sourceVar.VariableType)); destBody.Variables.Add(destVar); varMap[sourceVar] = destVar; } destBody.InitLocals = sourceBody.InitLocals; destBody.MaxStackSize = sourceBody.MaxStackSize; var destIl = destBody.GetILProcessor(); foreach (var si in sourceBody.Instructions) { Instruction di; var operand = si.Operand; if (operand == null) di = destIl.Create(si.OpCode); else if (operand is MethodReference) di = destIl.Create(si.OpCode, (MethodReference)Import((MethodReference)operand)); else if (operand is FieldReference) di = destIl.Create(si.OpCode, (FieldReference)Import((FieldReference)operand)); else if (operand is ParameterDefinition) di = destIl.Create(si.OpCode, methodParamMap[(ParameterDefinition)operand]); else if (operand is VariableDefinition) di = destIl.Create(si.OpCode, varMap[(VariableDefinition)operand]); else if (operand is Instruction) { var siInstOperand = (Instruction)operand; di = destIl.Create(si.OpCode, nopInstruction); postActions.Add(() => di.Operand = instMap[siInstOperand]); } else if (operand is Instruction[]) { var siInstOperand = (Instruction[])operand; di = destIl.Create(si.OpCode, new[] { nopInstruction }); postActions.Add(() => di.Operand = siInstOperand.Select(y => instMap[y]).ToArray()); } else if (operand is byte) di = destIl.Create(si.OpCode, (byte)operand); else if (operand is double) di = destIl.Create(si.OpCode, (double)operand); else if (operand is float) di = destIl.Create(si.OpCode, (float)operand); else if (operand is int) di = destIl.Create(si.OpCode, (int)operand); else if (operand is long) di = destIl.Create(si.OpCode, (long)operand); else if (operand is sbyte) di = destIl.Create(si.OpCode, (sbyte)operand); else if (operand is string) di = destIl.Create(si.OpCode, (string)operand); else if (operand is TypeReference) di = destIl.Create(si.OpCode, Import((TypeReference)operand)); else throw new NotImplementedException("Does not support copying opcode " + si.OpCode); instMap[si] = di; destIl.Append(di); } foreach (var pa in postActions) pa(); foreach (var sourceHandler in sourceBody.ExceptionHandlers) CopyExceptionHandlers(sourceHandler, instMap, destBody); } CopyAttributes(sourceMethod, destMethod); } private void CopyMethodDeclaration(MethodDefinition sourceMethod, TypeDefinition destType, Dictionary<ParameterDefinition, ParameterDefinition> methodParamMap) { var destMethod = new MethodDefinition( sourceMethod.Name, sourceMethod.Attributes, Import(sourceMethod.ReturnType)); destType.Methods.Add(destMethod); this.methodMap[sourceMethod] = destMethod; foreach (var sourceParam in sourceMethod.Parameters) { var destParam = new ParameterDefinition(sourceParam.Name, sourceParam.Attributes, Import(sourceParam.ParameterType)); destMethod.Parameters.Add(destParam); CopyAttributes(sourceParam, destParam); methodParamMap[sourceParam] = destParam; } } private void CopyProperty(PropertyDefinition sourceProp, TypeDefinition destType) { var destProp = new PropertyDefinition(sourceProp.Name, sourceProp.Attributes, Import(sourceProp.PropertyType)); destType.Properties.Add(destProp); this.propertyMap[sourceProp] = destProp; if (sourceProp.GetMethod != null) destProp.GetMethod = (MethodDefinition)Import(sourceProp.GetMethod); if (sourceProp.SetMethod != null) destProp.SetMethod = (MethodDefinition)Import(sourceProp.SetMethod); CopyAttributes(sourceProp, destProp); } private FieldReference Import(FieldReference fieldReference) { return this.fieldMap.GetOrCreate(fieldReference, () => this.destinationModule.Import(fieldReference)); } private MethodReference Import(MethodReference methodReference) { return this.methodMap.GetOrCreate(methodReference, () => { GenericInstanceMethod sourceInstance = methodReference as GenericInstanceMethod; if (sourceInstance != null) { var destInstance = new GenericInstanceMethod(Import(sourceInstance.ElementMethod)); destInstance.GenericArguments.AddRange( sourceInstance.GenericArguments.Select(Import)); return destInstance; } var imported = this.destinationModule.Import(methodReference); if (imported.DeclaringType != null) imported.DeclaringType = Import(methodReference.DeclaringType); return imported; }); } private TypeReference Import(TypeReference typeReference) { return this.typeMap.GetOrCreate(typeReference, () => { if (typeReference.IsByReference) return Import(typeReference.GetElementType()).MakeByReferenceType(); var sourceInstance = typeReference as GenericInstanceType; if (sourceInstance != null) { var destInstance = new GenericInstanceType(Import(sourceInstance.ElementType)); destInstance.GenericArguments.AddRange( sourceInstance.GenericArguments.Select(Import)); return destInstance; } return this.destinationModule.Import(typeReference); }); } private static Instruction MapInstructionSafe(Dictionary<Instruction, Instruction> instMap, Instruction sourceFilterStart) { return sourceFilterStart != null ? instMap[sourceFilterStart] : null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ExtendToVector256Single() { var test = new GenericUnaryOpTest__ExtendToVector256Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class GenericUnaryOpTest__ExtendToVector256Single { private struct TestStruct { public Vector128<Single> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256Single testClass) { var result = Avx.ExtendToVector256<Single>(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar; private Vector128<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static GenericUnaryOpTest__ExtendToVector256Single() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public GenericUnaryOpTest__ExtendToVector256Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.ExtendToVector256<Single>( Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.ExtendToVector256<Single>( Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.ExtendToVector256<Single>( Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.ExtendToVector256<Single>( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr); var result = Avx.ExtendToVector256<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx.ExtendToVector256<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx.ExtendToVector256<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new GenericUnaryOpTest__ExtendToVector256Single(); var result = Avx.ExtendToVector256<Single>(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.ExtendToVector256<Single>(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.ExtendToVector256(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (firstOp[0] != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0)) { Succeeded = false; break; } } } if (!Succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } } }